1use std::future;
2use std::sync::Arc;
3
4use anyhow::{anyhow, Result};
5use copilot::copilot_chat::{
6 ChatMessage, CopilotChat, Model as CopilotChatModel, Request as CopilotChatRequest,
7 Role as CopilotChatRole,
8};
9use copilot::{Copilot, Status};
10use futures::future::BoxFuture;
11use futures::stream::BoxStream;
12use futures::{FutureExt, StreamExt};
13use gpui::{
14 percentage, svg, Animation, AnimationExt, AnyView, App, AsyncApp, Entity, Render, Subscription,
15 Task, Transformation,
16};
17use language_model::{
18 AuthenticateError, LanguageModel, LanguageModelCompletionEvent, LanguageModelId,
19 LanguageModelName, LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
20 LanguageModelProviderState, LanguageModelRequest, RateLimiter, Role,
21};
22use settings::SettingsStore;
23use std::time::Duration;
24use strum::IntoEnumIterator;
25use ui::prelude::*;
26
27use super::anthropic::count_anthropic_tokens;
28use super::google::count_google_tokens;
29use super::open_ai::count_open_ai_tokens;
30
31const PROVIDER_ID: &str = "copilot_chat";
32const PROVIDER_NAME: &str = "GitHub Copilot Chat";
33
34#[derive(Default, Clone, Debug, PartialEq)]
35pub struct CopilotChatSettings {}
36
37pub struct CopilotChatLanguageModelProvider {
38 state: Entity<State>,
39}
40
41pub struct State {
42 _copilot_chat_subscription: Option<Subscription>,
43 _settings_subscription: Subscription,
44}
45
46impl State {
47 fn is_authenticated(&self, cx: &App) -> bool {
48 CopilotChat::global(cx)
49 .map(|m| m.read(cx).is_authenticated())
50 .unwrap_or(false)
51 }
52}
53
54impl CopilotChatLanguageModelProvider {
55 pub fn new(cx: &mut App) -> Self {
56 let state = cx.new(|cx| {
57 let _copilot_chat_subscription = CopilotChat::global(cx)
58 .map(|copilot_chat| cx.observe(&copilot_chat, |_, _, cx| cx.notify()));
59 State {
60 _copilot_chat_subscription,
61 _settings_subscription: cx.observe_global::<SettingsStore>(|_, cx| {
62 cx.notify();
63 }),
64 }
65 });
66
67 Self { state }
68 }
69}
70
71impl LanguageModelProviderState for CopilotChatLanguageModelProvider {
72 type ObservableEntity = State;
73
74 fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
75 Some(self.state.clone())
76 }
77}
78
79impl LanguageModelProvider for CopilotChatLanguageModelProvider {
80 fn id(&self) -> LanguageModelProviderId {
81 LanguageModelProviderId(PROVIDER_ID.into())
82 }
83
84 fn name(&self) -> LanguageModelProviderName {
85 LanguageModelProviderName(PROVIDER_NAME.into())
86 }
87
88 fn icon(&self) -> IconName {
89 IconName::Copilot
90 }
91
92 fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
93 let model = CopilotChatModel::default();
94 Some(Arc::new(CopilotChatLanguageModel {
95 model,
96 request_limiter: RateLimiter::new(4),
97 }) as Arc<dyn LanguageModel>)
98 }
99
100 fn provided_models(&self, _cx: &App) -> Vec<Arc<dyn LanguageModel>> {
101 CopilotChatModel::iter()
102 .map(|model| {
103 Arc::new(CopilotChatLanguageModel {
104 model,
105 request_limiter: RateLimiter::new(4),
106 }) as Arc<dyn LanguageModel>
107 })
108 .collect()
109 }
110
111 fn is_authenticated(&self, cx: &App) -> bool {
112 self.state.read(cx).is_authenticated(cx)
113 }
114
115 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
116 if self.is_authenticated(cx) {
117 return Task::ready(Ok(()));
118 };
119
120 let Some(copilot) = Copilot::global(cx) else {
121 return Task::ready( Err(anyhow!(
122 "Copilot must be enabled for Copilot Chat to work. Please enable Copilot and try again."
123 ).into()));
124 };
125
126 let err = match copilot.read(cx).status() {
127 Status::Authorized => return Task::ready(Ok(())),
128 Status::Disabled => anyhow!("Copilot must be enabled for Copilot Chat to work. Please enable Copilot and try again."),
129 Status::Error(err) => anyhow!(format!("Received the following error while signing into Copilot: {err}")),
130 Status::Starting { task: _ } => anyhow!("Copilot is still starting, please wait for Copilot to start then try again"),
131 Status::Unauthorized => anyhow!("Unable to authorize with Copilot. Please make sure that you have an active Copilot and Copilot Chat subscription."),
132 Status::SignedOut => anyhow!("You have signed out of Copilot. Please sign in to Copilot and try again."),
133 Status::SigningIn { prompt: _ } => anyhow!("Still signing into Copilot..."),
134 };
135
136 Task::ready(Err(err.into()))
137 }
138
139 fn configuration_view(&self, _: &mut Window, cx: &mut App) -> AnyView {
140 let state = self.state.clone();
141 cx.new(|cx| ConfigurationView::new(state, cx)).into()
142 }
143
144 fn reset_credentials(&self, _cx: &mut App) -> Task<Result<()>> {
145 Task::ready(Err(anyhow!(
146 "Signing out of GitHub Copilot Chat is currently not supported."
147 )))
148 }
149}
150
151pub struct CopilotChatLanguageModel {
152 model: CopilotChatModel,
153 request_limiter: RateLimiter,
154}
155
156impl LanguageModel for CopilotChatLanguageModel {
157 fn id(&self) -> LanguageModelId {
158 LanguageModelId::from(self.model.id().to_string())
159 }
160
161 fn name(&self) -> LanguageModelName {
162 LanguageModelName::from(self.model.display_name().to_string())
163 }
164
165 fn provider_id(&self) -> LanguageModelProviderId {
166 LanguageModelProviderId(PROVIDER_ID.into())
167 }
168
169 fn provider_name(&self) -> LanguageModelProviderName {
170 LanguageModelProviderName(PROVIDER_NAME.into())
171 }
172
173 fn telemetry_id(&self) -> String {
174 format!("copilot_chat/{}", self.model.id())
175 }
176
177 fn max_token_count(&self) -> usize {
178 self.model.max_token_count()
179 }
180
181 fn count_tokens(
182 &self,
183 request: LanguageModelRequest,
184 cx: &App,
185 ) -> BoxFuture<'static, Result<usize>> {
186 match self.model {
187 CopilotChatModel::Claude3_5Sonnet => count_anthropic_tokens(request, cx),
188 CopilotChatModel::Gemini20Flash => count_google_tokens(request, cx),
189 _ => {
190 let model = match self.model {
191 CopilotChatModel::Gpt4o => open_ai::Model::FourOmni,
192 CopilotChatModel::Gpt4 => open_ai::Model::Four,
193 CopilotChatModel::Gpt3_5Turbo => open_ai::Model::ThreePointFiveTurbo,
194 CopilotChatModel::O1 | CopilotChatModel::O3Mini => open_ai::Model::Four,
195 CopilotChatModel::Claude3_5Sonnet | CopilotChatModel::Gemini20Flash => {
196 unreachable!()
197 }
198 };
199 count_open_ai_tokens(request, model, cx)
200 }
201 }
202 }
203
204 fn stream_completion(
205 &self,
206 request: LanguageModelRequest,
207 cx: &AsyncApp,
208 ) -> BoxFuture<'static, Result<BoxStream<'static, Result<LanguageModelCompletionEvent>>>> {
209 if let Some(message) = request.messages.last() {
210 if message.contents_empty() {
211 const EMPTY_PROMPT_MSG: &str =
212 "Empty prompts aren't allowed. Please provide a non-empty prompt.";
213 return futures::future::ready(Err(anyhow::anyhow!(EMPTY_PROMPT_MSG))).boxed();
214 }
215
216 // Copilot Chat has a restriction that the final message must be from the user.
217 // While their API does return an error message for this, we can catch it earlier
218 // and provide a more helpful error message.
219 if !matches!(message.role, Role::User) {
220 const USER_ROLE_MSG: &str = "The final message must be from the user. To provide a system prompt, you must provide the system prompt followed by a user prompt.";
221 return futures::future::ready(Err(anyhow::anyhow!(USER_ROLE_MSG))).boxed();
222 }
223 }
224
225 let copilot_request = self.to_copilot_chat_request(request);
226 let is_streaming = copilot_request.stream;
227
228 let request_limiter = self.request_limiter.clone();
229 let future = cx.spawn(|cx| async move {
230 let response = CopilotChat::stream_completion(copilot_request, cx);
231 request_limiter.stream(async move {
232 let response = response.await?;
233 let stream = response
234 .filter_map(move |response| async move {
235 match response {
236 Ok(result) => {
237 let choice = result.choices.first();
238 match choice {
239 Some(choice) if !is_streaming => {
240 match &choice.message {
241 Some(msg) => Some(Ok(msg.content.clone().unwrap_or_default())),
242 None => Some(Err(anyhow::anyhow!(
243 "The Copilot Chat API returned a response with no message content"
244 ))),
245 }
246 },
247 Some(choice) => {
248 match &choice.delta {
249 Some(delta) => Some(Ok(delta.content.clone().unwrap_or_default())),
250 None => Some(Err(anyhow::anyhow!(
251 "The Copilot Chat API returned a response with no delta content"
252 ))),
253 }
254 },
255 None => Some(Err(anyhow::anyhow!(
256 "The Copilot Chat API returned a response with no choices, but hadn't finished the message yet. Please try again."
257 ))),
258 }
259 }
260 Err(err) => Some(Err(err)),
261 }
262 })
263 .boxed();
264 Ok(stream)
265 }).await
266 });
267
268 async move {
269 Ok(future
270 .await?
271 .map(|result| result.map(LanguageModelCompletionEvent::Text))
272 .boxed())
273 }
274 .boxed()
275 }
276
277 fn use_any_tool(
278 &self,
279 _request: LanguageModelRequest,
280 _name: String,
281 _description: String,
282 _schema: serde_json::Value,
283 _cx: &AsyncApp,
284 ) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
285 future::ready(Err(anyhow!("not implemented"))).boxed()
286 }
287}
288
289impl CopilotChatLanguageModel {
290 pub fn to_copilot_chat_request(&self, request: LanguageModelRequest) -> CopilotChatRequest {
291 CopilotChatRequest::new(
292 self.model.clone(),
293 request
294 .messages
295 .into_iter()
296 .map(|msg| ChatMessage {
297 role: match msg.role {
298 Role::User => CopilotChatRole::User,
299 Role::Assistant => CopilotChatRole::Assistant,
300 Role::System => CopilotChatRole::System,
301 },
302 content: msg.string_contents(),
303 })
304 .collect(),
305 )
306 }
307}
308
309struct ConfigurationView {
310 copilot_status: Option<copilot::Status>,
311 state: Entity<State>,
312 _subscription: Option<Subscription>,
313}
314
315impl ConfigurationView {
316 pub fn new(state: Entity<State>, cx: &mut Context<Self>) -> Self {
317 let copilot = Copilot::global(cx);
318
319 Self {
320 copilot_status: copilot.as_ref().map(|copilot| copilot.read(cx).status()),
321 state,
322 _subscription: copilot.as_ref().map(|copilot| {
323 cx.observe(copilot, |this, model, cx| {
324 this.copilot_status = Some(model.read(cx).status());
325 cx.notify();
326 })
327 }),
328 }
329 }
330}
331
332impl Render for ConfigurationView {
333 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
334 if self.state.read(cx).is_authenticated(cx) {
335 const LABEL: &str = "Authorized.";
336 h_flex()
337 .gap_1()
338 .child(Icon::new(IconName::Check).color(Color::Success))
339 .child(Label::new(LABEL))
340 } else {
341 let loading_icon = svg()
342 .size_8()
343 .path(IconName::ArrowCircle.path())
344 .text_color(window.text_style().color)
345 .with_animation(
346 "icon_circle_arrow",
347 Animation::new(Duration::from_secs(2)).repeat(),
348 |svg, delta| svg.with_transformation(Transformation::rotate(percentage(delta))),
349 );
350
351 const ERROR_LABEL: &str = "Copilot Chat requires an active GitHub Copilot subscription. Please ensure Copilot is configured and try again, or use a different Assistant provider.";
352
353 match &self.copilot_status {
354 Some(status) => match status {
355 Status::Disabled => v_flex().gap_6().p_4().child(Label::new(ERROR_LABEL)),
356 Status::Starting { task: _ } => {
357 const LABEL: &str = "Starting Copilot...";
358 v_flex()
359 .gap_6()
360 .justify_center()
361 .items_center()
362 .child(Label::new(LABEL))
363 .child(loading_icon)
364 }
365 Status::SigningIn { prompt: _ } => {
366 const LABEL: &str = "Signing in to Copilot...";
367 v_flex()
368 .gap_6()
369 .justify_center()
370 .items_center()
371 .child(Label::new(LABEL))
372 .child(loading_icon)
373 }
374 Status::Error(_) => {
375 const LABEL: &str = "Copilot had issues starting. Please try restarting it. If the issue persists, try reinstalling Copilot.";
376 v_flex()
377 .gap_6()
378 .child(Label::new(LABEL))
379 .child(svg().size_8().path(IconName::CopilotError.path()))
380 }
381 _ => {
382 const LABEL: &str =
383 "To use Zed's assistant with GitHub Copilot, you need to be logged in to GitHub. Note that your GitHub account must have an active Copilot Chat subscription.";
384 v_flex().gap_6().child(Label::new(LABEL)).child(
385 v_flex()
386 .gap_2()
387 .child(
388 Button::new("sign_in", "Sign In")
389 .icon_color(Color::Muted)
390 .icon(IconName::Github)
391 .icon_position(IconPosition::Start)
392 .icon_size(IconSize::Medium)
393 .style(ui::ButtonStyle::Filled)
394 .full_width()
395 .on_click(|_, window, cx| {
396 copilot::initiate_sign_in(window, cx)
397 }),
398 )
399 .child(
400 div().flex().w_full().items_center().child(
401 Label::new("Sign in to start using Github Copilot Chat.")
402 .color(Color::Muted)
403 .size(ui::LabelSize::Small),
404 ),
405 ),
406 )
407 }
408 },
409 None => v_flex().gap_6().child(Label::new(ERROR_LABEL)),
410 }
411 }
412 }
413}