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 telemetry_id(&self) -> String {
184        format!("copilot_chat/{}", self.model.id())
185    }
186
187    fn max_token_count(&self) -> usize {
188        self.model.max_token_count()
189    }
190
191    fn count_tokens(
192        &self,
193        request: LanguageModelRequest,
194        cx: &App,
195    ) -> BoxFuture<'static, Result<usize>> {
196        match self.model {
197            CopilotChatModel::Claude3_5Sonnet => count_anthropic_tokens(request, cx),
198            CopilotChatModel::Claude3_7Sonnet => count_anthropic_tokens(request, cx),
199            CopilotChatModel::Claude3_7SonnetThinking => count_anthropic_tokens(request, cx),
200            CopilotChatModel::Gemini20Flash => count_google_tokens(request, cx),
201            _ => {
202                let model = match self.model {
203                    CopilotChatModel::Gpt4o => open_ai::Model::FourOmni,
204                    CopilotChatModel::Gpt4 => open_ai::Model::Four,
205                    CopilotChatModel::Gpt3_5Turbo => open_ai::Model::ThreePointFiveTurbo,
206                    CopilotChatModel::O1 | CopilotChatModel::O3Mini => open_ai::Model::Four,
207                    CopilotChatModel::Claude3_5Sonnet
208                    | CopilotChatModel::Claude3_7Sonnet
209                    | CopilotChatModel::Claude3_7SonnetThinking
210                    | CopilotChatModel::Gemini20Flash => {
211                        unreachable!()
212                    }
213                };
214                count_open_ai_tokens(request, model, cx)
215            }
216        }
217    }
218
219    fn stream_completion(
220        &self,
221        request: LanguageModelRequest,
222        cx: &AsyncApp,
223    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<LanguageModelCompletionEvent>>>> {
224        if let Some(message) = request.messages.last() {
225            if message.contents_empty() {
226                const EMPTY_PROMPT_MSG: &str =
227                    "Empty prompts aren't allowed. Please provide a non-empty prompt.";
228                return futures::future::ready(Err(anyhow::anyhow!(EMPTY_PROMPT_MSG))).boxed();
229            }
230
231            // Copilot Chat has a restriction that the final message must be from the user.
232            // While their API does return an error message for this, we can catch it earlier
233            // and provide a more helpful error message.
234            if !matches!(message.role, Role::User) {
235                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.";
236                return futures::future::ready(Err(anyhow::anyhow!(USER_ROLE_MSG))).boxed();
237            }
238        }
239
240        let copilot_request = self.to_copilot_chat_request(request);
241        let is_streaming = copilot_request.stream;
242
243        let request_limiter = self.request_limiter.clone();
244        let future = cx.spawn(async move |cx| {
245            let response = CopilotChat::stream_completion(copilot_request, cx.clone());
246            request_limiter.stream(async move {
247                let response = response.await?;
248                let stream = response
249                    .filter_map(move |response| async move {
250                        match response {
251                            Ok(result) => {
252                                let choice = result.choices.first();
253                                match choice {
254                                    Some(choice) if !is_streaming => {
255                                        match &choice.message {
256                                            Some(msg) => Some(Ok(msg.content.clone().unwrap_or_default())),
257                                            None => Some(Err(anyhow::anyhow!(
258                                                "The Copilot Chat API returned a response with no message content"
259                                            ))),
260                                        }
261                                    },
262                                    Some(choice) => {
263                                        match &choice.delta {
264                                            Some(delta) => Some(Ok(delta.content.clone().unwrap_or_default())),
265                                            None => Some(Err(anyhow::anyhow!(
266                                                "The Copilot Chat API returned a response with no delta content"
267                                            ))),
268                                        }
269                                    },
270                                    None => Some(Err(anyhow::anyhow!(
271                                        "The Copilot Chat API returned a response with no choices, but hadn't finished the message yet. Please try again."
272                                    ))),
273                                }
274                            }
275                            Err(err) => Some(Err(err)),
276                        }
277                    })
278                    .boxed();
279
280                Ok(stream)
281            }).await
282        });
283
284        async move {
285            Ok(future
286                .await?
287                .map(|result| result.map(LanguageModelCompletionEvent::Text))
288                .boxed())
289        }
290        .boxed()
291    }
292
293    fn use_any_tool(
294        &self,
295        _request: LanguageModelRequest,
296        _name: String,
297        _description: String,
298        _schema: serde_json::Value,
299        _cx: &AsyncApp,
300    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
301        future::ready(Err(anyhow!("not implemented"))).boxed()
302    }
303}
304
305impl CopilotChatLanguageModel {
306    pub fn to_copilot_chat_request(&self, request: LanguageModelRequest) -> CopilotChatRequest {
307        CopilotChatRequest::new(
308            self.model.clone(),
309            request
310                .messages
311                .into_iter()
312                .map(|msg| ChatMessage {
313                    role: match msg.role {
314                        Role::User => CopilotChatRole::User,
315                        Role::Assistant => CopilotChatRole::Assistant,
316                        Role::System => CopilotChatRole::System,
317                    },
318                    content: msg.string_contents(),
319                })
320                .collect(),
321        )
322    }
323}
324
325struct ConfigurationView {
326    copilot_status: Option<copilot::Status>,
327    state: Entity<State>,
328    _subscription: Option<Subscription>,
329}
330
331impl ConfigurationView {
332    pub fn new(state: Entity<State>, cx: &mut Context<Self>) -> Self {
333        let copilot = Copilot::global(cx);
334
335        Self {
336            copilot_status: copilot.as_ref().map(|copilot| copilot.read(cx).status()),
337            state,
338            _subscription: copilot.as_ref().map(|copilot| {
339                cx.observe(copilot, |this, model, cx| {
340                    this.copilot_status = Some(model.read(cx).status());
341                    cx.notify();
342                })
343            }),
344        }
345    }
346}
347
348impl Render for ConfigurationView {
349    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
350        if self.state.read(cx).is_authenticated(cx) {
351            const LABEL: &str = "Authorized.";
352            h_flex()
353                .justify_between()
354                .child(
355                    h_flex()
356                        .gap_1()
357                        .child(Icon::new(IconName::Check).color(Color::Success))
358                        .child(Label::new(LABEL)),
359                )
360                .child(
361                    Button::new("sign_out", "Sign Out")
362                        .style(ui::ButtonStyle::Filled)
363                        .on_click(|_, window, cx| {
364                            window.dispatch_action(copilot::SignOut.boxed_clone(), cx);
365                        }),
366                )
367        } else {
368            let loading_icon = svg()
369                .size_8()
370                .path(IconName::ArrowCircle.path())
371                .text_color(window.text_style().color)
372                .with_animation(
373                    "icon_circle_arrow",
374                    Animation::new(Duration::from_secs(2)).repeat(),
375                    |svg, delta| svg.with_transformation(Transformation::rotate(percentage(delta))),
376                );
377
378            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.";
379
380            match &self.copilot_status {
381                Some(status) => match status {
382                    Status::Starting { task: _ } => {
383                        const LABEL: &str = "Starting Copilot...";
384                        v_flex()
385                            .gap_6()
386                            .justify_center()
387                            .items_center()
388                            .child(Label::new(LABEL))
389                            .child(loading_icon)
390                    }
391                    Status::SigningIn { prompt: _ }
392                    | Status::SignedOut {
393                        awaiting_signing_in: true,
394                    } => {
395                        const LABEL: &str = "Signing in to Copilot...";
396                        v_flex()
397                            .gap_6()
398                            .justify_center()
399                            .items_center()
400                            .child(Label::new(LABEL))
401                            .child(loading_icon)
402                    }
403                    Status::Error(_) => {
404                        const LABEL: &str = "Copilot had issues starting. Please try restarting it. If the issue persists, try reinstalling Copilot.";
405                        v_flex()
406                            .gap_6()
407                            .child(Label::new(LABEL))
408                            .child(svg().size_8().path(IconName::CopilotError.path()))
409                    }
410                    _ => {
411                        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.";
412                        v_flex().gap_6().child(Label::new(LABEL)).child(
413                            v_flex()
414                                .gap_2()
415                                .child(
416                                    Button::new("sign_in", "Sign In")
417                                        .icon_color(Color::Muted)
418                                        .icon(IconName::Github)
419                                        .icon_position(IconPosition::Start)
420                                        .icon_size(IconSize::Medium)
421                                        .style(ui::ButtonStyle::Filled)
422                                        .full_width()
423                                        .on_click(|_, window, cx| {
424                                            copilot::initiate_sign_in(window, cx)
425                                        }),
426                                )
427                                .child(
428                                    div().flex().w_full().items_center().child(
429                                        Label::new("Sign in to start using Github Copilot Chat.")
430                                            .color(Color::Muted)
431                                            .size(ui::LabelSize::Small),
432                                    ),
433                                ),
434                        )
435                    }
436                },
437                None => v_flex().gap_6().child(Label::new(ERROR_LABEL)),
438            }
439        }
440    }
441}