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