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