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(async move |cx| {
233 let response = CopilotChat::stream_completion(copilot_request, cx.clone());
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
268 Ok(stream)
269 }).await
270 });
271
272 async move {
273 Ok(future
274 .await?
275 .map(|result| result.map(LanguageModelCompletionEvent::Text))
276 .boxed())
277 }
278 .boxed()
279 }
280
281 fn use_any_tool(
282 &self,
283 _request: LanguageModelRequest,
284 _name: String,
285 _description: String,
286 _schema: serde_json::Value,
287 _cx: &AsyncApp,
288 ) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
289 future::ready(Err(anyhow!("not implemented"))).boxed()
290 }
291}
292
293impl CopilotChatLanguageModel {
294 pub fn to_copilot_chat_request(&self, request: LanguageModelRequest) -> CopilotChatRequest {
295 CopilotChatRequest::new(
296 self.model.clone(),
297 request
298 .messages
299 .into_iter()
300 .map(|msg| ChatMessage {
301 role: match msg.role {
302 Role::User => CopilotChatRole::User,
303 Role::Assistant => CopilotChatRole::Assistant,
304 Role::System => CopilotChatRole::System,
305 },
306 content: msg.string_contents(),
307 })
308 .collect(),
309 )
310 }
311}
312
313struct ConfigurationView {
314 copilot_status: Option<copilot::Status>,
315 state: Entity<State>,
316 _subscription: Option<Subscription>,
317}
318
319impl ConfigurationView {
320 pub fn new(state: Entity<State>, cx: &mut Context<Self>) -> Self {
321 let copilot = Copilot::global(cx);
322
323 Self {
324 copilot_status: copilot.as_ref().map(|copilot| copilot.read(cx).status()),
325 state,
326 _subscription: copilot.as_ref().map(|copilot| {
327 cx.observe(copilot, |this, model, cx| {
328 this.copilot_status = Some(model.read(cx).status());
329 cx.notify();
330 })
331 }),
332 }
333 }
334}
335
336impl Render for ConfigurationView {
337 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
338 if self.state.read(cx).is_authenticated(cx) {
339 const LABEL: &str = "Authorized.";
340 h_flex()
341 .justify_between()
342 .child(
343 h_flex()
344 .gap_1()
345 .child(Icon::new(IconName::Check).color(Color::Success))
346 .child(Label::new(LABEL)),
347 )
348 .child(
349 Button::new("sign_out", "Sign Out")
350 .style(ui::ButtonStyle::Filled)
351 .on_click(|_, window, cx| {
352 window.dispatch_action(copilot::SignOut.boxed_clone(), cx);
353 }),
354 )
355 } else {
356 let loading_icon = svg()
357 .size_8()
358 .path(IconName::ArrowCircle.path())
359 .text_color(window.text_style().color)
360 .with_animation(
361 "icon_circle_arrow",
362 Animation::new(Duration::from_secs(2)).repeat(),
363 |svg, delta| svg.with_transformation(Transformation::rotate(percentage(delta))),
364 );
365
366 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.";
367
368 match &self.copilot_status {
369 Some(status) => match status {
370 Status::Starting { task: _ } => {
371 const LABEL: &str = "Starting Copilot...";
372 v_flex()
373 .gap_6()
374 .justify_center()
375 .items_center()
376 .child(Label::new(LABEL))
377 .child(loading_icon)
378 }
379 Status::SigningIn { prompt: _ }
380 | Status::SignedOut {
381 awaiting_signing_in: true,
382 } => {
383 const LABEL: &str = "Signing in to Copilot...";
384 v_flex()
385 .gap_6()
386 .justify_center()
387 .items_center()
388 .child(Label::new(LABEL))
389 .child(loading_icon)
390 }
391 Status::Error(_) => {
392 const LABEL: &str = "Copilot had issues starting. Please try restarting it. If the issue persists, try reinstalling Copilot.";
393 v_flex()
394 .gap_6()
395 .child(Label::new(LABEL))
396 .child(svg().size_8().path(IconName::CopilotError.path()))
397 }
398 _ => {
399 const LABEL: &str =
400 "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.";
401 v_flex().gap_6().child(Label::new(LABEL)).child(
402 v_flex()
403 .gap_2()
404 .child(
405 Button::new("sign_in", "Sign In")
406 .icon_color(Color::Muted)
407 .icon(IconName::Github)
408 .icon_position(IconPosition::Start)
409 .icon_size(IconSize::Medium)
410 .style(ui::ButtonStyle::Filled)
411 .full_width()
412 .on_click(|_, window, cx| {
413 copilot::initiate_sign_in(window, cx)
414 }),
415 )
416 .child(
417 div().flex().w_full().items_center().child(
418 Label::new("Sign in to start using Github Copilot Chat.")
419 .color(Color::Muted)
420 .size(ui::LabelSize::Small),
421 ),
422 ),
423 )
424 }
425 },
426 None => v_flex().gap_6().child(Label::new(ERROR_LABEL)),
427 }
428 }
429 }
430}