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