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, AppContext, AsyncAppContext, Model, Render,
 15    Subscription, Task, Transformation,
 16};
 17use settings::{Settings, SettingsStore};
 18use std::time::Duration;
 19use strum::IntoEnumIterator;
 20use ui::{
 21    div, h_flex, v_flex, Button, ButtonCommon, Clickable, Color, Context, FixedWidth, IconName,
 22    IconPosition, IconSize, Indicator, IntoElement, Label, LabelCommon, ParentElement, Styled,
 23    ViewContext, VisualContext, WindowContext,
 24};
 25
 26use crate::settings::AllLanguageModelSettings;
 27use crate::LanguageModelProviderState;
 28use crate::{
 29    LanguageModel, LanguageModelId, LanguageModelName, LanguageModelProvider,
 30    LanguageModelProviderId, LanguageModelProviderName, LanguageModelRequest, RateLimiter, Role,
 31};
 32
 33use super::open_ai::count_open_ai_tokens;
 34
 35const PROVIDER_ID: &str = "copilot_chat";
 36const PROVIDER_NAME: &str = "GitHub Copilot Chat";
 37
 38#[derive(Default, Clone, Debug, PartialEq)]
 39pub struct CopilotChatSettings {
 40    pub low_speed_timeout: Option<Duration>,
 41}
 42
 43pub struct CopilotChatLanguageModelProvider {
 44    state: Model<State>,
 45}
 46
 47pub struct State {
 48    _copilot_chat_subscription: Option<Subscription>,
 49    _settings_subscription: Subscription,
 50}
 51
 52impl State {
 53    fn is_authenticated(&self, cx: &AppContext) -> bool {
 54        CopilotChat::global(cx)
 55            .map(|m| m.read(cx).is_authenticated())
 56            .unwrap_or(false)
 57    }
 58}
 59
 60impl CopilotChatLanguageModelProvider {
 61    pub fn new(cx: &mut AppContext) -> Self {
 62        let state = cx.new_model(|cx| {
 63            let _copilot_chat_subscription = CopilotChat::global(cx)
 64                .map(|copilot_chat| cx.observe(&copilot_chat, |_, _, cx| cx.notify()));
 65            State {
 66                _copilot_chat_subscription,
 67                _settings_subscription: cx.observe_global::<SettingsStore>(|_, cx| {
 68                    cx.notify();
 69                }),
 70            }
 71        });
 72
 73        Self { state }
 74    }
 75}
 76
 77impl LanguageModelProviderState for CopilotChatLanguageModelProvider {
 78    type ObservableEntity = State;
 79
 80    fn observable_entity(&self) -> Option<gpui::Model<Self::ObservableEntity>> {
 81        Some(self.state.clone())
 82    }
 83}
 84
 85impl LanguageModelProvider for CopilotChatLanguageModelProvider {
 86    fn id(&self) -> LanguageModelProviderId {
 87        LanguageModelProviderId(PROVIDER_ID.into())
 88    }
 89
 90    fn name(&self) -> LanguageModelProviderName {
 91        LanguageModelProviderName(PROVIDER_NAME.into())
 92    }
 93
 94    fn icon(&self) -> IconName {
 95        IconName::Copilot
 96    }
 97
 98    fn provided_models(&self, _cx: &AppContext) -> Vec<Arc<dyn LanguageModel>> {
 99        CopilotChatModel::iter()
100            .map(|model| {
101                Arc::new(CopilotChatLanguageModel {
102                    model,
103                    request_limiter: RateLimiter::new(4),
104                }) as Arc<dyn LanguageModel>
105            })
106            .collect()
107    }
108
109    fn is_authenticated(&self, cx: &AppContext) -> bool {
110        self.state.read(cx).is_authenticated(cx)
111    }
112
113    fn authenticate(&self, cx: &mut AppContext) -> Task<Result<()>> {
114        let result = if self.is_authenticated(cx) {
115            Ok(())
116        } else if let Some(copilot) = Copilot::global(cx) {
117            let error_msg = match copilot.read(cx).status() {
118                Status::Disabled => anyhow::anyhow!("Copilot must be enabled for Copilot Chat to work. Please enable Copilot and try again."),
119                Status::Error(e) => anyhow::anyhow!(format!("Received the following error while signing into Copilot: {e}")),
120                Status::Starting { task: _ } => anyhow::anyhow!("Copilot is still starting, please wait for Copilot to start then try again"),
121                Status::Unauthorized => anyhow::anyhow!("Unable to authorize with Copilot. Please make sure that you have an active Copilot and Copilot Chat subscription."),
122                Status::Authorized => return Task::ready(Ok(())),
123                Status::SignedOut => anyhow::anyhow!("You have signed out of Copilot. Please sign in to Copilot and try again."),
124                Status::SigningIn { prompt: _ } => anyhow::anyhow!("Still signing into Copilot..."),
125            };
126            Err(error_msg)
127        } else {
128            Err(anyhow::anyhow!(
129                "Copilot must be enabled for Copilot Chat to work. Please enable Copilot and try again."
130            ))
131        };
132        Task::ready(result)
133    }
134
135    fn configuration_view(&self, cx: &mut WindowContext) -> AnyView {
136        let state = self.state.clone();
137        cx.new_view(|cx| ConfigurationView::new(state, cx)).into()
138    }
139
140    fn reset_credentials(&self, _cx: &mut AppContext) -> Task<Result<()>> {
141        Task::ready(Err(anyhow!(
142            "Signing out of GitHub Copilot Chat is currently not supported."
143        )))
144    }
145}
146
147pub struct CopilotChatLanguageModel {
148    model: CopilotChatModel,
149    request_limiter: RateLimiter,
150}
151
152impl LanguageModel for CopilotChatLanguageModel {
153    fn id(&self) -> LanguageModelId {
154        LanguageModelId::from(self.model.id().to_string())
155    }
156
157    fn name(&self) -> LanguageModelName {
158        LanguageModelName::from(self.model.display_name().to_string())
159    }
160
161    fn provider_id(&self) -> LanguageModelProviderId {
162        LanguageModelProviderId(PROVIDER_ID.into())
163    }
164
165    fn provider_name(&self) -> LanguageModelProviderName {
166        LanguageModelProviderName(PROVIDER_NAME.into())
167    }
168
169    fn telemetry_id(&self) -> String {
170        format!("copilot_chat/{}", self.model.id())
171    }
172
173    fn max_token_count(&self) -> usize {
174        self.model.max_token_count()
175    }
176
177    fn count_tokens(
178        &self,
179        request: LanguageModelRequest,
180        cx: &AppContext,
181    ) -> BoxFuture<'static, Result<usize>> {
182        let model = match self.model {
183            CopilotChatModel::Gpt4 => open_ai::Model::Four,
184            CopilotChatModel::Gpt3_5Turbo => open_ai::Model::ThreePointFiveTurbo,
185        };
186
187        count_open_ai_tokens(request, model, cx)
188    }
189
190    fn stream_completion(
191        &self,
192        request: LanguageModelRequest,
193        cx: &AsyncAppContext,
194    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
195        if let Some(message) = request.messages.last() {
196            if message.content.trim().is_empty() {
197                const EMPTY_PROMPT_MSG: &str =
198                    "Empty prompts aren't allowed. Please provide a non-empty prompt.";
199                return futures::future::ready(Err(anyhow::anyhow!(EMPTY_PROMPT_MSG))).boxed();
200            }
201
202            // Copilot Chat has a restriction that the final message must be from the user.
203            // While their API does return an error message for this, we can catch it earlier
204            // and provide a more helpful error message.
205            if !matches!(message.role, Role::User) {
206                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.";
207                return futures::future::ready(Err(anyhow::anyhow!(USER_ROLE_MSG))).boxed();
208            }
209        }
210
211        let request = self.to_copilot_chat_request(request);
212        let Ok(low_speed_timeout) = cx.update(|cx| {
213            AllLanguageModelSettings::get_global(cx)
214                .copilot_chat
215                .low_speed_timeout
216        }) else {
217            return futures::future::ready(Err(anyhow::anyhow!("App state dropped"))).boxed();
218        };
219
220        let request_limiter = self.request_limiter.clone();
221        let future = cx.spawn(|cx| async move {
222            let response = CopilotChat::stream_completion(request, low_speed_timeout, cx);
223            request_limiter.stream(async move {
224                let response = response.await?;
225                let stream = response
226                    .filter_map(|response| async move {
227                        match response {
228                            Ok(result) => {
229                                let choice = result.choices.first();
230                                match choice {
231                                    Some(choice) => Some(Ok(choice.delta.content.clone().unwrap_or_default())),
232                                    None => Some(Err(anyhow::anyhow!(
233                                        "The Copilot Chat API returned a response with no choices, but hadn't finished the message yet. Please try again."
234                                    ))),
235                                }
236                            }
237                            Err(err) => Some(Err(err)),
238                        }
239                    })
240                    .boxed();
241                Ok(stream)
242            }).await
243        });
244
245        async move { Ok(future.await?.boxed()) }.boxed()
246    }
247
248    fn use_any_tool(
249        &self,
250        _request: LanguageModelRequest,
251        _name: String,
252        _description: String,
253        _schema: serde_json::Value,
254        _cx: &AsyncAppContext,
255    ) -> BoxFuture<'static, Result<serde_json::Value>> {
256        future::ready(Err(anyhow!("not implemented"))).boxed()
257    }
258}
259
260impl CopilotChatLanguageModel {
261    pub fn to_copilot_chat_request(&self, request: LanguageModelRequest) -> CopilotChatRequest {
262        CopilotChatRequest::new(
263            self.model.clone(),
264            request
265                .messages
266                .into_iter()
267                .map(|msg| ChatMessage {
268                    role: match msg.role {
269                        Role::User => CopilotChatRole::User,
270                        Role::Assistant => CopilotChatRole::Assistant,
271                        Role::System => CopilotChatRole::System,
272                    },
273                    content: msg.content,
274                })
275                .collect(),
276        )
277    }
278}
279
280struct ConfigurationView {
281    copilot_status: Option<copilot::Status>,
282    state: Model<State>,
283    _subscription: Option<Subscription>,
284}
285
286impl ConfigurationView {
287    pub fn new(state: Model<State>, cx: &mut ViewContext<Self>) -> Self {
288        let copilot = Copilot::global(cx);
289
290        Self {
291            copilot_status: copilot.as_ref().map(|copilot| copilot.read(cx).status()),
292            state,
293            _subscription: copilot.as_ref().map(|copilot| {
294                cx.observe(copilot, |this, model, cx| {
295                    this.copilot_status = Some(model.read(cx).status());
296                    cx.notify();
297                })
298            }),
299        }
300    }
301}
302
303impl Render for ConfigurationView {
304    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
305        if self.state.read(cx).is_authenticated(cx) {
306            const LABEL: &str = "Authorized.";
307            h_flex()
308                .gap_2()
309                .child(Indicator::dot().color(Color::Success))
310                .child(Label::new(LABEL))
311        } else {
312            let loading_icon = svg()
313                .size_8()
314                .path(IconName::ArrowCircle.path())
315                .text_color(cx.text_style().color)
316                .with_animation(
317                    "icon_circle_arrow",
318                    Animation::new(Duration::from_secs(2)).repeat(),
319                    |svg, delta| svg.with_transformation(Transformation::rotate(percentage(delta))),
320                );
321
322            const ERROR_LABEL: &str = "Copilot Chat requires the Copilot plugin to be available and running. Please ensure Copilot is running and try again, or use a different Assistant provider.";
323
324            match &self.copilot_status {
325                Some(status) => match status {
326                    Status::Disabled => v_flex().gap_6().p_4().child(Label::new(ERROR_LABEL)),
327                    Status::Starting { task: _ } => {
328                        const LABEL: &str = "Starting Copilot...";
329                        v_flex()
330                            .gap_6()
331                            .justify_center()
332                            .items_center()
333                            .child(Label::new(LABEL))
334                            .child(loading_icon)
335                    }
336                    Status::SigningIn { prompt: _ } => {
337                        const LABEL: &str = "Signing in to Copilot...";
338                        v_flex()
339                            .gap_6()
340                            .justify_center()
341                            .items_center()
342                            .child(Label::new(LABEL))
343                            .child(loading_icon)
344                    }
345                    Status::Error(_) => {
346                        const LABEL: &str = "Copilot had issues starting. Please try restarting it. If the issue persists, try reinstalling Copilot.";
347                        v_flex()
348                            .gap_6()
349                            .child(Label::new(LABEL))
350                            .child(svg().size_8().path(IconName::CopilotError.path()))
351                    }
352                    _ => {
353                        const LABEL: &str =
354                    "To use the assistant panel or inline assistant, you must login to GitHub Copilot. Your GitHub account must have an active Copilot Chat subscription.";
355                        v_flex().gap_6().child(Label::new(LABEL)).child(
356                            v_flex()
357                                .gap_2()
358                                .child(
359                                    Button::new("sign_in", "Sign In")
360                                        .icon_color(Color::Muted)
361                                        .icon(IconName::Github)
362                                        .icon_position(IconPosition::Start)
363                                        .icon_size(IconSize::Medium)
364                                        .style(ui::ButtonStyle::Filled)
365                                        .full_width()
366                                        .on_click(|_, cx| {
367                                            inline_completion_button::initiate_sign_in(cx)
368                                        }),
369                                )
370                                .child(
371                                    div().flex().w_full().items_center().child(
372                                        Label::new("Sign in to start using Github Copilot Chat.")
373                                            .color(Color::Muted)
374                                            .size(ui::LabelSize::Small),
375                                    ),
376                                ),
377                        )
378                    }
379                },
380                None => v_flex().gap_6().child(Label::new(ERROR_LABEL)),
381            }
382        }
383    }
384}