1use std::pin::Pin;
2use std::str::FromStr as _;
3use std::sync::Arc;
4
5use anyhow::{Result, anyhow};
6use collections::HashMap;
7use copilot::copilot_chat::{
8 ChatMessage, CopilotChat, Model as CopilotChatModel, Request as CopilotChatRequest,
9 ResponseEvent, Tool, ToolCall,
10};
11use copilot::{Copilot, Status};
12use futures::future::BoxFuture;
13use futures::stream::BoxStream;
14use futures::{FutureExt, Stream, StreamExt};
15use gpui::{
16 Action, Animation, AnimationExt, AnyView, App, AsyncApp, Entity, Render, Subscription, Task,
17 Transformation, percentage, svg,
18};
19use language_model::{
20 AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
21 LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
22 LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
23 LanguageModelRequestMessage, LanguageModelToolUse, MessageContent, RateLimiter, Role,
24 StopReason,
25};
26use settings::SettingsStore;
27use std::time::Duration;
28use strum::IntoEnumIterator;
29use ui::prelude::*;
30
31use super::anthropic::count_anthropic_tokens;
32use super::google::count_google_tokens;
33use super::open_ai::count_open_ai_tokens;
34
35const PROVIDER_ID: &str = "copilot_chat";
36const PROVIDER_NAME: &str = "GitHub Copilot Chat";
37
38#[derive(Default, Clone, Debug, PartialEq)]
39pub struct CopilotChatSettings {}
40
41pub struct CopilotChatLanguageModelProvider {
42 state: Entity<State>,
43}
44
45pub struct State {
46 _copilot_chat_subscription: Option<Subscription>,
47 _settings_subscription: Subscription,
48}
49
50impl State {
51 fn is_authenticated(&self, cx: &App) -> bool {
52 CopilotChat::global(cx)
53 .map(|m| m.read(cx).is_authenticated())
54 .unwrap_or(false)
55 }
56}
57
58impl CopilotChatLanguageModelProvider {
59 pub fn new(cx: &mut App) -> Self {
60 let state = cx.new(|cx| {
61 let _copilot_chat_subscription = CopilotChat::global(cx)
62 .map(|copilot_chat| cx.observe(&copilot_chat, |_, _, cx| cx.notify()));
63 State {
64 _copilot_chat_subscription,
65 _settings_subscription: cx.observe_global::<SettingsStore>(|_, cx| {
66 cx.notify();
67 }),
68 }
69 });
70
71 Self { state }
72 }
73
74 fn create_language_model(&self, model: CopilotChatModel) -> Arc<dyn LanguageModel> {
75 Arc::new(CopilotChatLanguageModel {
76 model,
77 request_limiter: RateLimiter::new(4),
78 })
79 }
80}
81
82impl LanguageModelProviderState for CopilotChatLanguageModelProvider {
83 type ObservableEntity = State;
84
85 fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
86 Some(self.state.clone())
87 }
88}
89
90impl LanguageModelProvider for CopilotChatLanguageModelProvider {
91 fn id(&self) -> LanguageModelProviderId {
92 LanguageModelProviderId(PROVIDER_ID.into())
93 }
94
95 fn name(&self) -> LanguageModelProviderName {
96 LanguageModelProviderName(PROVIDER_NAME.into())
97 }
98
99 fn icon(&self) -> IconName {
100 IconName::Copilot
101 }
102
103 fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
104 Some(self.create_language_model(CopilotChatModel::default()))
105 }
106
107 fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
108 Some(self.create_language_model(CopilotChatModel::default_fast()))
109 }
110
111 fn provided_models(&self, _cx: &App) -> Vec<Arc<dyn LanguageModel>> {
112 CopilotChatModel::iter()
113 .map(|model| self.create_language_model(model))
114 .collect()
115 }
116
117 fn is_authenticated(&self, cx: &App) -> bool {
118 self.state.read(cx).is_authenticated(cx)
119 }
120
121 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
122 if self.is_authenticated(cx) {
123 return Task::ready(Ok(()));
124 };
125
126 let Some(copilot) = Copilot::global(cx) else {
127 return Task::ready( Err(anyhow!(
128 "Copilot must be enabled for Copilot Chat to work. Please enable Copilot and try again."
129 ).into()));
130 };
131
132 let err = match copilot.read(cx).status() {
133 Status::Authorized => return Task::ready(Ok(())),
134 Status::Disabled => anyhow!(
135 "Copilot must be enabled for Copilot Chat to work. Please enable Copilot and try again."
136 ),
137 Status::Error(err) => anyhow!(format!(
138 "Received the following error while signing into Copilot: {err}"
139 )),
140 Status::Starting { task: _ } => anyhow!(
141 "Copilot is still starting, please wait for Copilot to start then try again"
142 ),
143 Status::Unauthorized => anyhow!(
144 "Unable to authorize with Copilot. Please make sure that you have an active Copilot and Copilot Chat subscription."
145 ),
146 Status::SignedOut { .. } => {
147 anyhow!("You have signed out of Copilot. Please sign in to Copilot and try again.")
148 }
149 Status::SigningIn { prompt: _ } => anyhow!("Still signing into Copilot..."),
150 };
151
152 Task::ready(Err(err.into()))
153 }
154
155 fn configuration_view(&self, _: &mut Window, cx: &mut App) -> AnyView {
156 let state = self.state.clone();
157 cx.new(|cx| ConfigurationView::new(state, cx)).into()
158 }
159
160 fn reset_credentials(&self, _cx: &mut App) -> Task<Result<()>> {
161 Task::ready(Err(anyhow!(
162 "Signing out of GitHub Copilot Chat is currently not supported."
163 )))
164 }
165}
166
167pub struct CopilotChatLanguageModel {
168 model: CopilotChatModel,
169 request_limiter: RateLimiter,
170}
171
172impl LanguageModel for CopilotChatLanguageModel {
173 fn id(&self) -> LanguageModelId {
174 LanguageModelId::from(self.model.id().to_string())
175 }
176
177 fn name(&self) -> LanguageModelName {
178 LanguageModelName::from(self.model.display_name().to_string())
179 }
180
181 fn provider_id(&self) -> LanguageModelProviderId {
182 LanguageModelProviderId(PROVIDER_ID.into())
183 }
184
185 fn provider_name(&self) -> LanguageModelProviderName {
186 LanguageModelProviderName(PROVIDER_NAME.into())
187 }
188
189 fn supports_tools(&self) -> bool {
190 match self.model {
191 CopilotChatModel::Gpt4o
192 | CopilotChatModel::Gpt4_1
193 | CopilotChatModel::O4Mini
194 | CopilotChatModel::Claude3_5Sonnet
195 | CopilotChatModel::Claude3_7Sonnet => true,
196 _ => false,
197 }
198 }
199
200 fn telemetry_id(&self) -> String {
201 format!("copilot_chat/{}", self.model.id())
202 }
203
204 fn max_token_count(&self) -> usize {
205 self.model.max_token_count()
206 }
207
208 fn count_tokens(
209 &self,
210 request: LanguageModelRequest,
211 cx: &App,
212 ) -> BoxFuture<'static, Result<usize>> {
213 match self.model {
214 CopilotChatModel::Claude3_5Sonnet => count_anthropic_tokens(request, cx),
215 CopilotChatModel::Claude3_7Sonnet => count_anthropic_tokens(request, cx),
216 CopilotChatModel::Claude3_7SonnetThinking => count_anthropic_tokens(request, cx),
217 CopilotChatModel::Gemini20Flash | CopilotChatModel::Gemini25Pro => {
218 count_google_tokens(request, cx)
219 }
220 _ => {
221 let model = match self.model {
222 CopilotChatModel::Gpt4o => open_ai::Model::FourOmni,
223 CopilotChatModel::Gpt4 => open_ai::Model::Four,
224 CopilotChatModel::Gpt4_1 => open_ai::Model::FourPointOne,
225 CopilotChatModel::Gpt3_5Turbo => open_ai::Model::ThreePointFiveTurbo,
226 CopilotChatModel::O1 => open_ai::Model::O1,
227 CopilotChatModel::O3Mini => open_ai::Model::O3Mini,
228 CopilotChatModel::O3 => open_ai::Model::O3,
229 CopilotChatModel::O4Mini => open_ai::Model::O4Mini,
230 CopilotChatModel::Claude3_5Sonnet
231 | CopilotChatModel::Claude3_7Sonnet
232 | CopilotChatModel::Claude3_7SonnetThinking
233 | CopilotChatModel::Gemini20Flash
234 | CopilotChatModel::Gemini25Pro => {
235 unreachable!()
236 }
237 };
238 count_open_ai_tokens(request, model, cx)
239 }
240 }
241 }
242
243 fn stream_completion(
244 &self,
245 request: LanguageModelRequest,
246 cx: &AsyncApp,
247 ) -> BoxFuture<
248 'static,
249 Result<
250 BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
251 >,
252 > {
253 if let Some(message) = request.messages.last() {
254 if message.contents_empty() {
255 const EMPTY_PROMPT_MSG: &str =
256 "Empty prompts aren't allowed. Please provide a non-empty prompt.";
257 return futures::future::ready(Err(anyhow::anyhow!(EMPTY_PROMPT_MSG))).boxed();
258 }
259
260 // Copilot Chat has a restriction that the final message must be from the user.
261 // While their API does return an error message for this, we can catch it earlier
262 // and provide a more helpful error message.
263 if !matches!(message.role, Role::User) {
264 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.";
265 return futures::future::ready(Err(anyhow::anyhow!(USER_ROLE_MSG))).boxed();
266 }
267 }
268
269 let copilot_request = match self.to_copilot_chat_request(request) {
270 Ok(request) => request,
271 Err(err) => return futures::future::ready(Err(err)).boxed(),
272 };
273 let is_streaming = copilot_request.stream;
274
275 let request_limiter = self.request_limiter.clone();
276 let future = cx.spawn(async move |cx| {
277 let request = CopilotChat::stream_completion(copilot_request, cx.clone());
278 request_limiter
279 .stream(async move {
280 let response = request.await?;
281 Ok(map_to_language_model_completion_events(
282 response,
283 is_streaming,
284 ))
285 })
286 .await
287 });
288 async move { Ok(future.await?.boxed()) }.boxed()
289 }
290}
291
292pub fn map_to_language_model_completion_events(
293 events: Pin<Box<dyn Send + Stream<Item = Result<ResponseEvent>>>>,
294 is_streaming: bool,
295) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
296 #[derive(Default)]
297 struct RawToolCall {
298 id: String,
299 name: String,
300 arguments: String,
301 }
302
303 struct State {
304 events: Pin<Box<dyn Send + Stream<Item = Result<ResponseEvent>>>>,
305 tool_calls_by_index: HashMap<usize, RawToolCall>,
306 }
307
308 futures::stream::unfold(
309 State {
310 events,
311 tool_calls_by_index: HashMap::default(),
312 },
313 move |mut state| async move {
314 if let Some(event) = state.events.next().await {
315 match event {
316 Ok(event) => {
317 let Some(choice) = event.choices.first() else {
318 return Some((
319 vec![Err(anyhow!("Response contained no choices").into())],
320 state,
321 ));
322 };
323
324 let delta = if is_streaming {
325 choice.delta.as_ref()
326 } else {
327 choice.message.as_ref()
328 };
329
330 let Some(delta) = delta else {
331 return Some((
332 vec![Err(anyhow!("Response contained no delta").into())],
333 state,
334 ));
335 };
336
337 let mut events = Vec::new();
338 if let Some(content) = delta.content.clone() {
339 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
340 }
341
342 for tool_call in &delta.tool_calls {
343 let entry = state
344 .tool_calls_by_index
345 .entry(tool_call.index)
346 .or_default();
347
348 if let Some(tool_id) = tool_call.id.clone() {
349 entry.id = tool_id;
350 }
351
352 if let Some(function) = tool_call.function.as_ref() {
353 if let Some(name) = function.name.clone() {
354 entry.name = name;
355 }
356
357 if let Some(arguments) = function.arguments.clone() {
358 entry.arguments.push_str(&arguments);
359 }
360 }
361 }
362
363 match choice.finish_reason.as_deref() {
364 Some("stop") => {
365 events.push(Ok(LanguageModelCompletionEvent::Stop(
366 StopReason::EndTurn,
367 )));
368 }
369 Some("tool_calls") => {
370 events.extend(state.tool_calls_by_index.drain().map(
371 |(_, tool_call)| match serde_json::Value::from_str(
372 &tool_call.arguments,
373 ) {
374 Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
375 LanguageModelToolUse {
376 id: tool_call.id.clone().into(),
377 name: tool_call.name.as_str().into(),
378 is_input_complete: true,
379 input,
380 raw_input: tool_call.arguments.clone(),
381 },
382 )),
383 Err(error) => {
384 Err(LanguageModelCompletionError::BadInputJson {
385 id: tool_call.id.into(),
386 tool_name: tool_call.name.as_str().into(),
387 raw_input: tool_call.arguments.into(),
388 json_parse_error: error.to_string(),
389 })
390 }
391 },
392 ));
393
394 events.push(Ok(LanguageModelCompletionEvent::Stop(
395 StopReason::ToolUse,
396 )));
397 }
398 Some(stop_reason) => {
399 log::error!("Unexpected Copilot Chat stop_reason: {stop_reason:?}");
400 events.push(Ok(LanguageModelCompletionEvent::Stop(
401 StopReason::EndTurn,
402 )));
403 }
404 None => {}
405 }
406
407 return Some((events, state));
408 }
409 Err(err) => return Some((vec![Err(anyhow!(err).into())], state)),
410 }
411 }
412
413 None
414 },
415 )
416 .flat_map(futures::stream::iter)
417}
418
419impl CopilotChatLanguageModel {
420 pub fn to_copilot_chat_request(
421 &self,
422 request: LanguageModelRequest,
423 ) -> Result<CopilotChatRequest> {
424 let model = self.model.clone();
425
426 let mut request_messages: Vec<LanguageModelRequestMessage> = Vec::new();
427 for message in request.messages {
428 if let Some(last_message) = request_messages.last_mut() {
429 if last_message.role == message.role {
430 last_message.content.extend(message.content);
431 } else {
432 request_messages.push(message);
433 }
434 } else {
435 request_messages.push(message);
436 }
437 }
438
439 let mut tool_called = false;
440 let mut messages: Vec<ChatMessage> = Vec::new();
441 for message in request_messages {
442 let text_content = {
443 let mut buffer = String::new();
444 for string in message.content.iter().filter_map(|content| match content {
445 MessageContent::Text(text) | MessageContent::Thinking { text, .. } => {
446 Some(text.as_str())
447 }
448 MessageContent::ToolUse(_)
449 | MessageContent::RedactedThinking(_)
450 | MessageContent::ToolResult(_)
451 | MessageContent::Image(_) => None,
452 }) {
453 buffer.push_str(string);
454 }
455
456 buffer
457 };
458
459 match message.role {
460 Role::User => {
461 for content in &message.content {
462 if let MessageContent::ToolResult(tool_result) = content {
463 messages.push(ChatMessage::Tool {
464 tool_call_id: tool_result.tool_use_id.to_string(),
465 content: tool_result.content.to_string(),
466 });
467 }
468 }
469
470 if !text_content.is_empty() {
471 messages.push(ChatMessage::User {
472 content: text_content,
473 });
474 }
475 }
476 Role::Assistant => {
477 let mut tool_calls = Vec::new();
478 for content in &message.content {
479 if let MessageContent::ToolUse(tool_use) = content {
480 tool_called = true;
481 tool_calls.push(ToolCall {
482 id: tool_use.id.to_string(),
483 content: copilot::copilot_chat::ToolCallContent::Function {
484 function: copilot::copilot_chat::FunctionContent {
485 name: tool_use.name.to_string(),
486 arguments: serde_json::to_string(&tool_use.input)?,
487 },
488 },
489 });
490 }
491 }
492
493 messages.push(ChatMessage::Assistant {
494 content: if text_content.is_empty() {
495 None
496 } else {
497 Some(text_content)
498 },
499 tool_calls,
500 });
501 }
502 Role::System => messages.push(ChatMessage::System {
503 content: message.string_contents(),
504 }),
505 }
506 }
507
508 let mut tools = request
509 .tools
510 .iter()
511 .map(|tool| Tool::Function {
512 function: copilot::copilot_chat::Function {
513 name: tool.name.clone(),
514 description: tool.description.clone(),
515 parameters: tool.input_schema.clone(),
516 },
517 })
518 .collect::<Vec<_>>();
519
520 // The API will return a Bad Request (with no error message) when tools
521 // were used previously in the conversation but no tools are provided as
522 // part of this request. Inserting a dummy tool seems to circumvent this
523 // error.
524 if tool_called && tools.is_empty() {
525 tools.push(Tool::Function {
526 function: copilot::copilot_chat::Function {
527 name: "noop".to_string(),
528 description: "No operation".to_string(),
529 parameters: serde_json::json!({}),
530 },
531 });
532 }
533
534 Ok(CopilotChatRequest {
535 intent: true,
536 n: 1,
537 stream: model.uses_streaming(),
538 temperature: 0.1,
539 model,
540 messages,
541 tools,
542 tool_choice: None,
543 })
544 }
545}
546
547struct ConfigurationView {
548 copilot_status: Option<copilot::Status>,
549 state: Entity<State>,
550 _subscription: Option<Subscription>,
551}
552
553impl ConfigurationView {
554 pub fn new(state: Entity<State>, cx: &mut Context<Self>) -> Self {
555 let copilot = Copilot::global(cx);
556
557 Self {
558 copilot_status: copilot.as_ref().map(|copilot| copilot.read(cx).status()),
559 state,
560 _subscription: copilot.as_ref().map(|copilot| {
561 cx.observe(copilot, |this, model, cx| {
562 this.copilot_status = Some(model.read(cx).status());
563 cx.notify();
564 })
565 }),
566 }
567 }
568}
569
570impl Render for ConfigurationView {
571 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
572 if self.state.read(cx).is_authenticated(cx) {
573 h_flex()
574 .mt_1()
575 .p_1()
576 .justify_between()
577 .rounded_md()
578 .border_1()
579 .border_color(cx.theme().colors().border)
580 .bg(cx.theme().colors().background)
581 .child(
582 h_flex()
583 .gap_1()
584 .child(Icon::new(IconName::Check).color(Color::Success))
585 .child(Label::new("Authorized")),
586 )
587 .child(
588 Button::new("sign_out", "Sign Out")
589 .label_size(LabelSize::Small)
590 .on_click(|_, window, cx| {
591 window.dispatch_action(copilot::SignOut.boxed_clone(), cx);
592 }),
593 )
594 } else {
595 let loading_icon = Icon::new(IconName::ArrowCircle).with_animation(
596 "arrow-circle",
597 Animation::new(Duration::from_secs(4)).repeat(),
598 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
599 );
600
601 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.";
602
603 match &self.copilot_status {
604 Some(status) => match status {
605 Status::Starting { task: _ } => h_flex()
606 .gap_2()
607 .child(loading_icon)
608 .child(Label::new("Starting Copilot…")),
609 Status::SigningIn { prompt: _ }
610 | Status::SignedOut {
611 awaiting_signing_in: true,
612 } => h_flex()
613 .gap_2()
614 .child(loading_icon)
615 .child(Label::new("Signing into Copilot…")),
616 Status::Error(_) => {
617 const LABEL: &str = "Copilot had issues starting. Please try restarting it. If the issue persists, try reinstalling Copilot.";
618 v_flex()
619 .gap_6()
620 .child(Label::new(LABEL))
621 .child(svg().size_8().path(IconName::CopilotError.path()))
622 }
623 _ => {
624 const LABEL: &str = "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.";
625 v_flex().gap_2().child(Label::new(LABEL)).child(
626 Button::new("sign_in", "Sign in to use GitHub Copilot")
627 .icon_color(Color::Muted)
628 .icon(IconName::Github)
629 .icon_position(IconPosition::Start)
630 .icon_size(IconSize::Medium)
631 .full_width()
632 .on_click(|_, window, cx| copilot::initiate_sign_in(window, cx)),
633 )
634 }
635 },
636 None => v_flex().gap_6().child(Label::new(ERROR_LABEL)),
637 }
638 }
639 }
640}