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