copilot_chat.rs

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