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, 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                                                    is_input_complete: true,
371                                                    input: serde_json::Value::from_str(
372                                                        &tool_call.arguments,
373                                                    )?,
374                                                },
375                                            ))
376                                        })
377                                    },
378                                ));
379
380                                events.push(Ok(LanguageModelCompletionEvent::Stop(
381                                    StopReason::ToolUse,
382                                )));
383                            }
384                            Some(stop_reason) => {
385                                log::error!("Unexpected Copilot Chat stop_reason: {stop_reason:?}");
386                                events.push(Ok(LanguageModelCompletionEvent::Stop(
387                                    StopReason::EndTurn,
388                                )));
389                            }
390                            None => {}
391                        }
392
393                        return Some((events, state));
394                    }
395                    Err(err) => return Some((vec![Err(err)], state)),
396                }
397            }
398
399            None
400        },
401    )
402    .flat_map(futures::stream::iter)
403}
404
405impl CopilotChatLanguageModel {
406    pub fn to_copilot_chat_request(
407        &self,
408        request: LanguageModelRequest,
409    ) -> Result<CopilotChatRequest> {
410        let model = self.model.clone();
411
412        let mut request_messages: Vec<LanguageModelRequestMessage> = Vec::new();
413        for message in request.messages {
414            if let Some(last_message) = request_messages.last_mut() {
415                if last_message.role == message.role {
416                    last_message.content.extend(message.content);
417                } else {
418                    request_messages.push(message);
419                }
420            } else {
421                request_messages.push(message);
422            }
423        }
424
425        let mut messages: Vec<ChatMessage> = Vec::new();
426        for message in request_messages {
427            let text_content = {
428                let mut buffer = String::new();
429                for string in message.content.iter().filter_map(|content| match content {
430                    MessageContent::Text(text) | MessageContent::Thinking { text, .. } => {
431                        Some(text.as_str())
432                    }
433                    MessageContent::ToolUse(_)
434                    | MessageContent::RedactedThinking(_)
435                    | MessageContent::ToolResult(_)
436                    | MessageContent::Image(_) => None,
437                }) {
438                    buffer.push_str(string);
439                }
440
441                buffer
442            };
443
444            match message.role {
445                Role::User => {
446                    for content in &message.content {
447                        if let MessageContent::ToolResult(tool_result) = content {
448                            messages.push(ChatMessage::Tool {
449                                tool_call_id: tool_result.tool_use_id.to_string(),
450                                content: tool_result.content.to_string(),
451                            });
452                        }
453                    }
454
455                    messages.push(ChatMessage::User {
456                        content: text_content,
457                    });
458                }
459                Role::Assistant => {
460                    let mut tool_calls = Vec::new();
461                    for content in &message.content {
462                        if let MessageContent::ToolUse(tool_use) = content {
463                            tool_calls.push(ToolCall {
464                                id: tool_use.id.to_string(),
465                                content: copilot::copilot_chat::ToolCallContent::Function {
466                                    function: copilot::copilot_chat::FunctionContent {
467                                        name: tool_use.name.to_string(),
468                                        arguments: serde_json::to_string(&tool_use.input)?,
469                                    },
470                                },
471                            });
472                        }
473                    }
474
475                    messages.push(ChatMessage::Assistant {
476                        content: if text_content.is_empty() {
477                            None
478                        } else {
479                            Some(text_content)
480                        },
481                        tool_calls,
482                    });
483                }
484                Role::System => messages.push(ChatMessage::System {
485                    content: message.string_contents(),
486                }),
487            }
488        }
489
490        let tools = request
491            .tools
492            .iter()
493            .map(|tool| Tool::Function {
494                function: copilot::copilot_chat::Function {
495                    name: tool.name.clone(),
496                    description: tool.description.clone(),
497                    parameters: tool.input_schema.clone(),
498                },
499            })
500            .collect();
501
502        Ok(CopilotChatRequest {
503            intent: true,
504            n: 1,
505            stream: model.uses_streaming(),
506            temperature: 0.1,
507            model,
508            messages,
509            tools,
510            tool_choice: None,
511        })
512    }
513}
514
515struct ConfigurationView {
516    copilot_status: Option<copilot::Status>,
517    state: Entity<State>,
518    _subscription: Option<Subscription>,
519}
520
521impl ConfigurationView {
522    pub fn new(state: Entity<State>, cx: &mut Context<Self>) -> Self {
523        let copilot = Copilot::global(cx);
524
525        Self {
526            copilot_status: copilot.as_ref().map(|copilot| copilot.read(cx).status()),
527            state,
528            _subscription: copilot.as_ref().map(|copilot| {
529                cx.observe(copilot, |this, model, cx| {
530                    this.copilot_status = Some(model.read(cx).status());
531                    cx.notify();
532                })
533            }),
534        }
535    }
536}
537
538impl Render for ConfigurationView {
539    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
540        if self.state.read(cx).is_authenticated(cx) {
541            h_flex()
542                .mt_1()
543                .p_1()
544                .justify_between()
545                .rounded_md()
546                .border_1()
547                .border_color(cx.theme().colors().border)
548                .bg(cx.theme().colors().background)
549                .child(
550                    h_flex()
551                        .gap_1()
552                        .child(Icon::new(IconName::Check).color(Color::Success))
553                        .child(Label::new("Authorized")),
554                )
555                .child(
556                    Button::new("sign_out", "Sign Out")
557                        .label_size(LabelSize::Small)
558                        .on_click(|_, window, cx| {
559                            window.dispatch_action(copilot::SignOut.boxed_clone(), cx);
560                        }),
561                )
562        } else {
563            let loading_icon = Icon::new(IconName::ArrowCircle).with_animation(
564                "arrow-circle",
565                Animation::new(Duration::from_secs(4)).repeat(),
566                |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
567            );
568
569            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.";
570
571            match &self.copilot_status {
572                Some(status) => match status {
573                    Status::Starting { task: _ } => h_flex()
574                        .gap_2()
575                        .child(loading_icon)
576                        .child(Label::new("Starting Copilot…")),
577                    Status::SigningIn { prompt: _ }
578                    | Status::SignedOut {
579                        awaiting_signing_in: true,
580                    } => h_flex()
581                        .gap_2()
582                        .child(loading_icon)
583                        .child(Label::new("Signing into Copilot…")),
584                    Status::Error(_) => {
585                        const LABEL: &str = "Copilot had issues starting. Please try restarting it. If the issue persists, try reinstalling Copilot.";
586                        v_flex()
587                            .gap_6()
588                            .child(Label::new(LABEL))
589                            .child(svg().size_8().path(IconName::CopilotError.path()))
590                    }
591                    _ => {
592                        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.";
593                        v_flex().gap_2().child(Label::new(LABEL)).child(
594                            Button::new("sign_in", "Sign in to use GitHub Copilot")
595                                .icon_color(Color::Muted)
596                                .icon(IconName::Github)
597                                .icon_position(IconPosition::Start)
598                                .icon_size(IconSize::Medium)
599                                .full_width()
600                                .on_click(|_, window, cx| copilot::initiate_sign_in(window, cx)),
601                        )
602                    }
603                },
604                None => v_flex().gap_6().child(Label::new(ERROR_LABEL)),
605            }
606        }
607    }
608}