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