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 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::Claude3_5Sonnet
192 | CopilotChatModel::Claude3_7Sonnet
193 | CopilotChatModel::Claude3_7SonnetThinking => true,
194 _ => false,
195 }
196 }
197
198 fn telemetry_id(&self) -> String {
199 format!("copilot_chat/{}", self.model.id())
200 }
201
202 fn max_token_count(&self) -> usize {
203 self.model.max_token_count()
204 }
205
206 fn count_tokens(
207 &self,
208 request: LanguageModelRequest,
209 cx: &App,
210 ) -> BoxFuture<'static, Result<usize>> {
211 match self.model {
212 CopilotChatModel::Claude3_5Sonnet => count_anthropic_tokens(request, cx),
213 CopilotChatModel::Claude3_7Sonnet => count_anthropic_tokens(request, cx),
214 CopilotChatModel::Claude3_7SonnetThinking => count_anthropic_tokens(request, cx),
215 CopilotChatModel::Gemini20Flash | CopilotChatModel::Gemini25Pro => {
216 count_google_tokens(request, cx)
217 }
218 _ => {
219 let model = match self.model {
220 CopilotChatModel::Gpt4o => open_ai::Model::FourOmni,
221 CopilotChatModel::Gpt4 => open_ai::Model::Four,
222 CopilotChatModel::Gpt4_1 => open_ai::Model::FourPointOne,
223 CopilotChatModel::Gpt3_5Turbo => open_ai::Model::ThreePointFiveTurbo,
224 CopilotChatModel::O1 => open_ai::Model::O1,
225 CopilotChatModel::O3Mini => open_ai::Model::O3Mini,
226 CopilotChatModel::O3 => open_ai::Model::O3,
227 CopilotChatModel::O4Mini => open_ai::Model::O4Mini,
228 CopilotChatModel::Claude3_5Sonnet
229 | CopilotChatModel::Claude3_7Sonnet
230 | CopilotChatModel::Claude3_7SonnetThinking
231 | CopilotChatModel::Gemini20Flash
232 | CopilotChatModel::Gemini25Pro => {
233 unreachable!()
234 }
235 };
236 count_open_ai_tokens(request, model, cx)
237 }
238 }
239 }
240
241 fn stream_completion(
242 &self,
243 request: LanguageModelRequest,
244 cx: &AsyncApp,
245 ) -> BoxFuture<'static, Result<BoxStream<'static, Result<LanguageModelCompletionEvent>>>> {
246 if let Some(message) = request.messages.last() {
247 if message.contents_empty() {
248 const EMPTY_PROMPT_MSG: &str =
249 "Empty prompts aren't allowed. Please provide a non-empty prompt.";
250 return futures::future::ready(Err(anyhow::anyhow!(EMPTY_PROMPT_MSG))).boxed();
251 }
252
253 // Copilot Chat has a restriction that the final message must be from the user.
254 // While their API does return an error message for this, we can catch it earlier
255 // and provide a more helpful error message.
256 if !matches!(message.role, Role::User) {
257 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.";
258 return futures::future::ready(Err(anyhow::anyhow!(USER_ROLE_MSG))).boxed();
259 }
260 }
261
262 let copilot_request = match self.to_copilot_chat_request(request) {
263 Ok(request) => request,
264 Err(err) => return futures::future::ready(Err(err)).boxed(),
265 };
266 let is_streaming = copilot_request.stream;
267
268 let request_limiter = self.request_limiter.clone();
269 let future = cx.spawn(async move |cx| {
270 let request = CopilotChat::stream_completion(copilot_request, cx.clone());
271 request_limiter
272 .stream(async move {
273 let response = request.await?;
274 Ok(map_to_language_model_completion_events(
275 response,
276 is_streaming,
277 ))
278 })
279 .await
280 });
281 async move { Ok(future.await?.boxed()) }.boxed()
282 }
283}
284
285pub fn map_to_language_model_completion_events(
286 events: Pin<Box<dyn Send + Stream<Item = Result<ResponseEvent>>>>,
287 is_streaming: bool,
288) -> impl Stream<Item = Result<LanguageModelCompletionEvent>> {
289 #[derive(Default)]
290 struct RawToolCall {
291 id: String,
292 name: String,
293 arguments: String,
294 }
295
296 struct State {
297 events: Pin<Box<dyn Send + Stream<Item = Result<ResponseEvent>>>>,
298 tool_calls_by_index: HashMap<usize, RawToolCall>,
299 }
300
301 futures::stream::unfold(
302 State {
303 events,
304 tool_calls_by_index: HashMap::default(),
305 },
306 move |mut state| async move {
307 if let Some(event) = state.events.next().await {
308 match event {
309 Ok(event) => {
310 let Some(choice) = event.choices.first() else {
311 return Some((
312 vec![Err(anyhow!("Response contained no choices"))],
313 state,
314 ));
315 };
316
317 let delta = if is_streaming {
318 choice.delta.as_ref()
319 } else {
320 choice.message.as_ref()
321 };
322
323 let Some(delta) = delta else {
324 return Some((
325 vec![Err(anyhow!("Response contained no delta"))],
326 state,
327 ));
328 };
329
330 let mut events = Vec::new();
331 if let Some(content) = delta.content.clone() {
332 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
333 }
334
335 for tool_call in &delta.tool_calls {
336 let entry = state
337 .tool_calls_by_index
338 .entry(tool_call.index)
339 .or_default();
340
341 if let Some(tool_id) = tool_call.id.clone() {
342 entry.id = tool_id;
343 }
344
345 if let Some(function) = tool_call.function.as_ref() {
346 if let Some(name) = function.name.clone() {
347 entry.name = name;
348 }
349
350 if let Some(arguments) = function.arguments.clone() {
351 entry.arguments.push_str(&arguments);
352 }
353 }
354 }
355
356 match choice.finish_reason.as_deref() {
357 Some("stop") => {
358 events.push(Ok(LanguageModelCompletionEvent::Stop(
359 StopReason::EndTurn,
360 )));
361 }
362 Some("tool_calls") => {
363 events.extend(state.tool_calls_by_index.drain().map(
364 |(_, tool_call)| {
365 maybe!({
366 Ok(LanguageModelCompletionEvent::ToolUse(
367 LanguageModelToolUse {
368 id: tool_call.id.into(),
369 name: tool_call.name.as_str().into(),
370 input: serde_json::Value::from_str(
371 &tool_call.arguments,
372 )?,
373 },
374 ))
375 })
376 },
377 ));
378
379 events.push(Ok(LanguageModelCompletionEvent::Stop(
380 StopReason::ToolUse,
381 )));
382 }
383 Some(stop_reason) => {
384 log::error!("Unexpected Copilot Chat stop_reason: {stop_reason:?}");
385 events.push(Ok(LanguageModelCompletionEvent::Stop(
386 StopReason::EndTurn,
387 )));
388 }
389 None => {}
390 }
391
392 return Some((events, state));
393 }
394 Err(err) => return Some((vec![Err(err)], state)),
395 }
396 }
397
398 None
399 },
400 )
401 .flat_map(futures::stream::iter)
402}
403
404impl CopilotChatLanguageModel {
405 pub fn to_copilot_chat_request(
406 &self,
407 request: LanguageModelRequest,
408 ) -> Result<CopilotChatRequest> {
409 let model = self.model.clone();
410
411 let mut request_messages: Vec<LanguageModelRequestMessage> = Vec::new();
412 for message in request.messages {
413 if let Some(last_message) = request_messages.last_mut() {
414 if last_message.role == message.role {
415 last_message.content.extend(message.content);
416 } else {
417 request_messages.push(message);
418 }
419 } else {
420 request_messages.push(message);
421 }
422 }
423
424 let mut messages: Vec<ChatMessage> = Vec::new();
425 for message in request_messages {
426 let text_content = {
427 let mut buffer = String::new();
428 for string in message.content.iter().filter_map(|content| match content {
429 MessageContent::Text(text) | MessageContent::Thinking { text, .. } => {
430 Some(text.as_str())
431 }
432 MessageContent::ToolUse(_)
433 | MessageContent::RedactedThinking(_)
434 | MessageContent::ToolResult(_)
435 | MessageContent::Image(_) => None,
436 }) {
437 buffer.push_str(string);
438 }
439
440 buffer
441 };
442
443 match message.role {
444 Role::User => {
445 for content in &message.content {
446 if let MessageContent::ToolResult(tool_result) = content {
447 messages.push(ChatMessage::Tool {
448 tool_call_id: tool_result.tool_use_id.to_string(),
449 content: tool_result.content.to_string(),
450 });
451 }
452 }
453
454 messages.push(ChatMessage::User {
455 content: text_content,
456 });
457 }
458 Role::Assistant => {
459 let mut tool_calls = Vec::new();
460 for content in &message.content {
461 if let MessageContent::ToolUse(tool_use) = content {
462 tool_calls.push(ToolCall {
463 id: tool_use.id.to_string(),
464 content: copilot::copilot_chat::ToolCallContent::Function {
465 function: copilot::copilot_chat::FunctionContent {
466 name: tool_use.name.to_string(),
467 arguments: serde_json::to_string(&tool_use.input)?,
468 },
469 },
470 });
471 }
472 }
473
474 messages.push(ChatMessage::Assistant {
475 content: if text_content.is_empty() {
476 None
477 } else {
478 Some(text_content)
479 },
480 tool_calls,
481 });
482 }
483 Role::System => messages.push(ChatMessage::System {
484 content: message.string_contents(),
485 }),
486 }
487 }
488
489 let tools = request
490 .tools
491 .iter()
492 .map(|tool| Tool::Function {
493 function: copilot::copilot_chat::Function {
494 name: tool.name.clone(),
495 description: tool.description.clone(),
496 parameters: tool.input_schema.clone(),
497 },
498 })
499 .collect();
500
501 Ok(CopilotChatRequest {
502 intent: true,
503 n: 1,
504 stream: model.uses_streaming(),
505 temperature: 0.1,
506 model,
507 messages,
508 tools,
509 tool_choice: None,
510 })
511 }
512}
513
514struct ConfigurationView {
515 copilot_status: Option<copilot::Status>,
516 state: Entity<State>,
517 _subscription: Option<Subscription>,
518}
519
520impl ConfigurationView {
521 pub fn new(state: Entity<State>, cx: &mut Context<Self>) -> Self {
522 let copilot = Copilot::global(cx);
523
524 Self {
525 copilot_status: copilot.as_ref().map(|copilot| copilot.read(cx).status()),
526 state,
527 _subscription: copilot.as_ref().map(|copilot| {
528 cx.observe(copilot, |this, model, cx| {
529 this.copilot_status = Some(model.read(cx).status());
530 cx.notify();
531 })
532 }),
533 }
534 }
535}
536
537impl Render for ConfigurationView {
538 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
539 if self.state.read(cx).is_authenticated(cx) {
540 h_flex()
541 .mt_1()
542 .p_1()
543 .justify_between()
544 .rounded_md()
545 .border_1()
546 .border_color(cx.theme().colors().border)
547 .bg(cx.theme().colors().background)
548 .child(
549 h_flex()
550 .gap_1()
551 .child(Icon::new(IconName::Check).color(Color::Success))
552 .child(Label::new("Authorized")),
553 )
554 .child(
555 Button::new("sign_out", "Sign Out")
556 .label_size(LabelSize::Small)
557 .on_click(|_, window, cx| {
558 window.dispatch_action(copilot::SignOut.boxed_clone(), cx);
559 }),
560 )
561 } else {
562 let loading_icon = Icon::new(IconName::ArrowCircle).with_animation(
563 "arrow-circle",
564 Animation::new(Duration::from_secs(4)).repeat(),
565 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
566 );
567
568 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.";
569
570 match &self.copilot_status {
571 Some(status) => match status {
572 Status::Starting { task: _ } => h_flex()
573 .gap_2()
574 .child(loading_icon)
575 .child(Label::new("Starting Copilot…")),
576 Status::SigningIn { prompt: _ }
577 | Status::SignedOut {
578 awaiting_signing_in: true,
579 } => h_flex()
580 .gap_2()
581 .child(loading_icon)
582 .child(Label::new("Signing into Copilot…")),
583 Status::Error(_) => {
584 const LABEL: &str = "Copilot had issues starting. Please try restarting it. If the issue persists, try reinstalling Copilot.";
585 v_flex()
586 .gap_6()
587 .child(Label::new(LABEL))
588 .child(svg().size_8().path(IconName::CopilotError.path()))
589 }
590 _ => {
591 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.";
592 v_flex().gap_2().child(Label::new(LABEL)).child(
593 Button::new("sign_in", "Sign in to use GitHub Copilot")
594 .icon_color(Color::Muted)
595 .icon(IconName::Github)
596 .icon_position(IconPosition::Start)
597 .icon_size(IconSize::Medium)
598 .full_width()
599 .on_click(|_, window, cx| copilot::initiate_sign_in(window, cx)),
600 )
601 }
602 },
603 None => v_flex().gap_6().child(Label::new(ERROR_LABEL)),
604 }
605 }
606 }
607}