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