copilot_chat.rs

  1use std::future;
  2use std::sync::Arc;
  3
  4use anyhow::{Result, anyhow};
  5use copilot::copilot_chat::{
  6    ChatMessage, CopilotChat, Model as CopilotChatModel, Request as CopilotChatRequest,
  7    Role as CopilotChatRole,
  8};
  9use copilot::{Copilot, Status};
 10use futures::future::BoxFuture;
 11use futures::stream::BoxStream;
 12use futures::{FutureExt, StreamExt};
 13use gpui::{
 14    Action, Animation, AnimationExt, AnyView, App, AsyncApp, Entity, Render, Subscription, Task,
 15    Transformation, percentage, svg,
 16};
 17use language_model::{
 18    AuthenticateError, LanguageModel, LanguageModelCompletionEvent, LanguageModelId,
 19    LanguageModelName, LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
 20    LanguageModelProviderState, LanguageModelRequest, RateLimiter, Role,
 21};
 22use settings::SettingsStore;
 23use std::time::Duration;
 24use strum::IntoEnumIterator;
 25use ui::prelude::*;
 26
 27use super::anthropic::count_anthropic_tokens;
 28use super::google::count_google_tokens;
 29use super::open_ai::count_open_ai_tokens;
 30
 31const PROVIDER_ID: &str = "copilot_chat";
 32const PROVIDER_NAME: &str = "GitHub Copilot Chat";
 33
 34#[derive(Default, Clone, Debug, PartialEq)]
 35pub struct CopilotChatSettings {}
 36
 37pub struct CopilotChatLanguageModelProvider {
 38    state: Entity<State>,
 39}
 40
 41pub struct State {
 42    _copilot_chat_subscription: Option<Subscription>,
 43    _settings_subscription: Subscription,
 44}
 45
 46impl State {
 47    fn is_authenticated(&self, cx: &App) -> bool {
 48        CopilotChat::global(cx)
 49            .map(|m| m.read(cx).is_authenticated())
 50            .unwrap_or(false)
 51    }
 52}
 53
 54impl CopilotChatLanguageModelProvider {
 55    pub fn new(cx: &mut App) -> Self {
 56        let state = cx.new(|cx| {
 57            let _copilot_chat_subscription = CopilotChat::global(cx)
 58                .map(|copilot_chat| cx.observe(&copilot_chat, |_, _, cx| cx.notify()));
 59            State {
 60                _copilot_chat_subscription,
 61                _settings_subscription: cx.observe_global::<SettingsStore>(|_, cx| {
 62                    cx.notify();
 63                }),
 64            }
 65        });
 66
 67        Self { state }
 68    }
 69}
 70
 71impl LanguageModelProviderState for CopilotChatLanguageModelProvider {
 72    type ObservableEntity = State;
 73
 74    fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
 75        Some(self.state.clone())
 76    }
 77}
 78
 79impl LanguageModelProvider for CopilotChatLanguageModelProvider {
 80    fn id(&self) -> LanguageModelProviderId {
 81        LanguageModelProviderId(PROVIDER_ID.into())
 82    }
 83
 84    fn name(&self) -> LanguageModelProviderName {
 85        LanguageModelProviderName(PROVIDER_NAME.into())
 86    }
 87
 88    fn icon(&self) -> IconName {
 89        IconName::Copilot
 90    }
 91
 92    fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
 93        let model = CopilotChatModel::default();
 94        Some(Arc::new(CopilotChatLanguageModel {
 95            model,
 96            request_limiter: RateLimiter::new(4),
 97        }) as Arc<dyn LanguageModel>)
 98    }
 99
100    fn provided_models(&self, _cx: &App) -> Vec<Arc<dyn LanguageModel>> {
101        CopilotChatModel::iter()
102            .map(|model| {
103                Arc::new(CopilotChatLanguageModel {
104                    model,
105                    request_limiter: RateLimiter::new(4),
106                }) as Arc<dyn LanguageModel>
107            })
108            .collect()
109    }
110
111    fn is_authenticated(&self, cx: &App) -> bool {
112        self.state.read(cx).is_authenticated(cx)
113    }
114
115    fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
116        if self.is_authenticated(cx) {
117            return Task::ready(Ok(()));
118        };
119
120        let Some(copilot) = Copilot::global(cx) else {
121            return Task::ready( Err(anyhow!(
122                "Copilot must be enabled for Copilot Chat to work. Please enable Copilot and try again."
123            ).into()));
124        };
125
126        let err = match copilot.read(cx).status() {
127            Status::Authorized => return Task::ready(Ok(())),
128            Status::Disabled => anyhow!(
129                "Copilot must be enabled for Copilot Chat to work. Please enable Copilot and try again."
130            ),
131            Status::Error(err) => anyhow!(format!(
132                "Received the following error while signing into Copilot: {err}"
133            )),
134            Status::Starting { task: _ } => anyhow!(
135                "Copilot is still starting, please wait for Copilot to start then try again"
136            ),
137            Status::Unauthorized => anyhow!(
138                "Unable to authorize with Copilot. Please make sure that you have an active Copilot and Copilot Chat subscription."
139            ),
140            Status::SignedOut { .. } => {
141                anyhow!("You have signed out of Copilot. Please sign in to Copilot and try again.")
142            }
143            Status::SigningIn { prompt: _ } => anyhow!("Still signing into Copilot..."),
144        };
145
146        Task::ready(Err(err.into()))
147    }
148
149    fn configuration_view(&self, _: &mut Window, cx: &mut App) -> AnyView {
150        let state = self.state.clone();
151        cx.new(|cx| ConfigurationView::new(state, cx)).into()
152    }
153
154    fn reset_credentials(&self, _cx: &mut App) -> Task<Result<()>> {
155        Task::ready(Err(anyhow!(
156            "Signing out of GitHub Copilot Chat is currently not supported."
157        )))
158    }
159}
160
161pub struct CopilotChatLanguageModel {
162    model: CopilotChatModel,
163    request_limiter: RateLimiter,
164}
165
166impl LanguageModel for CopilotChatLanguageModel {
167    fn id(&self) -> LanguageModelId {
168        LanguageModelId::from(self.model.id().to_string())
169    }
170
171    fn name(&self) -> LanguageModelName {
172        LanguageModelName::from(self.model.display_name().to_string())
173    }
174
175    fn provider_id(&self) -> LanguageModelProviderId {
176        LanguageModelProviderId(PROVIDER_ID.into())
177    }
178
179    fn provider_name(&self) -> LanguageModelProviderName {
180        LanguageModelProviderName(PROVIDER_NAME.into())
181    }
182
183    fn supports_tools(&self) -> bool {
184        false
185    }
186
187    fn telemetry_id(&self) -> String {
188        format!("copilot_chat/{}", self.model.id())
189    }
190
191    fn max_token_count(&self) -> usize {
192        self.model.max_token_count()
193    }
194
195    fn count_tokens(
196        &self,
197        request: LanguageModelRequest,
198        cx: &App,
199    ) -> BoxFuture<'static, Result<usize>> {
200        match self.model {
201            CopilotChatModel::Claude3_5Sonnet => count_anthropic_tokens(request, cx),
202            CopilotChatModel::Claude3_7Sonnet => count_anthropic_tokens(request, cx),
203            CopilotChatModel::Claude3_7SonnetThinking => count_anthropic_tokens(request, cx),
204            CopilotChatModel::Gemini20Flash => count_google_tokens(request, cx),
205            _ => {
206                let model = match self.model {
207                    CopilotChatModel::Gpt4o => open_ai::Model::FourOmni,
208                    CopilotChatModel::Gpt4 => open_ai::Model::Four,
209                    CopilotChatModel::Gpt3_5Turbo => open_ai::Model::ThreePointFiveTurbo,
210                    CopilotChatModel::O1 | CopilotChatModel::O3Mini => open_ai::Model::Four,
211                    CopilotChatModel::Claude3_5Sonnet
212                    | CopilotChatModel::Claude3_7Sonnet
213                    | CopilotChatModel::Claude3_7SonnetThinking
214                    | CopilotChatModel::Gemini20Flash => {
215                        unreachable!()
216                    }
217                };
218                count_open_ai_tokens(request, model, cx)
219            }
220        }
221    }
222
223    fn stream_completion(
224        &self,
225        request: LanguageModelRequest,
226        cx: &AsyncApp,
227    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<LanguageModelCompletionEvent>>>> {
228        if let Some(message) = request.messages.last() {
229            if message.contents_empty() {
230                const EMPTY_PROMPT_MSG: &str =
231                    "Empty prompts aren't allowed. Please provide a non-empty prompt.";
232                return futures::future::ready(Err(anyhow::anyhow!(EMPTY_PROMPT_MSG))).boxed();
233            }
234
235            // Copilot Chat has a restriction that the final message must be from the user.
236            // While their API does return an error message for this, we can catch it earlier
237            // and provide a more helpful error message.
238            if !matches!(message.role, Role::User) {
239                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.";
240                return futures::future::ready(Err(anyhow::anyhow!(USER_ROLE_MSG))).boxed();
241            }
242        }
243
244        let copilot_request = self.to_copilot_chat_request(request);
245        let is_streaming = copilot_request.stream;
246
247        let request_limiter = self.request_limiter.clone();
248        let future = cx.spawn(async move |cx| {
249            let response = CopilotChat::stream_completion(copilot_request, cx.clone());
250            request_limiter.stream(async move {
251                let response = response.await?;
252                let stream = response
253                    .filter_map(move |response| async move {
254                        match response {
255                            Ok(result) => {
256                                let choice = result.choices.first();
257                                match choice {
258                                    Some(choice) if !is_streaming => {
259                                        match &choice.message {
260                                            Some(msg) => Some(Ok(msg.content.clone().unwrap_or_default())),
261                                            None => Some(Err(anyhow::anyhow!(
262                                                "The Copilot Chat API returned a response with no message content"
263                                            ))),
264                                        }
265                                    },
266                                    Some(choice) => {
267                                        match &choice.delta {
268                                            Some(delta) => Some(Ok(delta.content.clone().unwrap_or_default())),
269                                            None => Some(Err(anyhow::anyhow!(
270                                                "The Copilot Chat API returned a response with no delta content"
271                                            ))),
272                                        }
273                                    },
274                                    None => Some(Err(anyhow::anyhow!(
275                                        "The Copilot Chat API returned a response with no choices, but hadn't finished the message yet. Please try again."
276                                    ))),
277                                }
278                            }
279                            Err(err) => Some(Err(err)),
280                        }
281                    })
282                    .boxed();
283
284                Ok(stream)
285            }).await
286        });
287
288        async move {
289            Ok(future
290                .await?
291                .map(|result| result.map(LanguageModelCompletionEvent::Text))
292                .boxed())
293        }
294        .boxed()
295    }
296
297    fn use_any_tool(
298        &self,
299        _request: LanguageModelRequest,
300        _name: String,
301        _description: String,
302        _schema: serde_json::Value,
303        _cx: &AsyncApp,
304    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
305        future::ready(Err(anyhow!("not implemented"))).boxed()
306    }
307}
308
309impl CopilotChatLanguageModel {
310    pub fn to_copilot_chat_request(&self, request: LanguageModelRequest) -> CopilotChatRequest {
311        CopilotChatRequest::new(
312            self.model.clone(),
313            request
314                .messages
315                .into_iter()
316                .map(|msg| ChatMessage {
317                    role: match msg.role {
318                        Role::User => CopilotChatRole::User,
319                        Role::Assistant => CopilotChatRole::Assistant,
320                        Role::System => CopilotChatRole::System,
321                    },
322                    content: msg.string_contents(),
323                })
324                .collect(),
325        )
326    }
327}
328
329struct ConfigurationView {
330    copilot_status: Option<copilot::Status>,
331    state: Entity<State>,
332    _subscription: Option<Subscription>,
333}
334
335impl ConfigurationView {
336    pub fn new(state: Entity<State>, cx: &mut Context<Self>) -> Self {
337        let copilot = Copilot::global(cx);
338
339        Self {
340            copilot_status: copilot.as_ref().map(|copilot| copilot.read(cx).status()),
341            state,
342            _subscription: copilot.as_ref().map(|copilot| {
343                cx.observe(copilot, |this, model, cx| {
344                    this.copilot_status = Some(model.read(cx).status());
345                    cx.notify();
346                })
347            }),
348        }
349    }
350}
351
352impl Render for ConfigurationView {
353    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
354        if self.state.read(cx).is_authenticated(cx) {
355            const LABEL: &str = "Authorized.";
356            h_flex()
357                .justify_between()
358                .child(
359                    h_flex()
360                        .gap_1()
361                        .child(Icon::new(IconName::Check).color(Color::Success))
362                        .child(Label::new(LABEL)),
363                )
364                .child(
365                    Button::new("sign_out", "Sign Out")
366                        .style(ui::ButtonStyle::Filled)
367                        .on_click(|_, window, cx| {
368                            window.dispatch_action(copilot::SignOut.boxed_clone(), cx);
369                        }),
370                )
371        } else {
372            let loading_icon = svg()
373                .size_8()
374                .path(IconName::ArrowCircle.path())
375                .text_color(window.text_style().color)
376                .with_animation(
377                    "icon_circle_arrow",
378                    Animation::new(Duration::from_secs(2)).repeat(),
379                    |svg, delta| svg.with_transformation(Transformation::rotate(percentage(delta))),
380                );
381
382            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.";
383
384            match &self.copilot_status {
385                Some(status) => match status {
386                    Status::Starting { task: _ } => {
387                        const LABEL: &str = "Starting Copilot...";
388                        v_flex()
389                            .gap_6()
390                            .justify_center()
391                            .items_center()
392                            .child(Label::new(LABEL))
393                            .child(loading_icon)
394                    }
395                    Status::SigningIn { prompt: _ }
396                    | Status::SignedOut {
397                        awaiting_signing_in: true,
398                    } => {
399                        const LABEL: &str = "Signing in to Copilot...";
400                        v_flex()
401                            .gap_6()
402                            .justify_center()
403                            .items_center()
404                            .child(Label::new(LABEL))
405                            .child(loading_icon)
406                    }
407                    Status::Error(_) => {
408                        const LABEL: &str = "Copilot had issues starting. Please try restarting it. If the issue persists, try reinstalling Copilot.";
409                        v_flex()
410                            .gap_6()
411                            .child(Label::new(LABEL))
412                            .child(svg().size_8().path(IconName::CopilotError.path()))
413                    }
414                    _ => {
415                        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.";
416                        v_flex().gap_6().child(Label::new(LABEL)).child(
417                            v_flex()
418                                .gap_2()
419                                .child(
420                                    Button::new("sign_in", "Sign In")
421                                        .icon_color(Color::Muted)
422                                        .icon(IconName::Github)
423                                        .icon_position(IconPosition::Start)
424                                        .icon_size(IconSize::Medium)
425                                        .style(ui::ButtonStyle::Filled)
426                                        .full_width()
427                                        .on_click(|_, window, cx| {
428                                            copilot::initiate_sign_in(window, cx)
429                                        }),
430                                )
431                                .child(
432                                    div().flex().w_full().items_center().child(
433                                        Label::new("Sign in to start using Github Copilot Chat.")
434                                            .color(Color::Muted)
435                                            .size(ui::LabelSize::Small),
436                                    ),
437                                ),
438                        )
439                    }
440                },
441                None => v_flex().gap_6().child(Label::new(ERROR_LABEL)),
442            }
443        }
444    }
445}