copilot_chat.rs

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