copilot_chat.rs

  1use std::path::PathBuf;
  2use std::sync::OnceLock;
  3use std::{sync::Arc, time::Duration};
  4
  5use anyhow::{anyhow, Result};
  6use chrono::DateTime;
  7use fs::Fs;
  8use futures::{io::BufReader, stream::BoxStream, AsyncBufReadExt, AsyncReadExt, StreamExt};
  9use gpui::{AppContext, AsyncAppContext, Global};
 10use http_client::{AsyncBody, HttpClient, HttpRequestExt, Method, Request as HttpRequest};
 11use paths::home_dir;
 12use serde::{Deserialize, Serialize};
 13use settings::watch_config_file;
 14use strum::EnumIter;
 15use ui::Context;
 16
 17pub const COPILOT_CHAT_COMPLETION_URL: &str = "https://api.githubcopilot.com/chat/completions";
 18pub const COPILOT_CHAT_AUTH_URL: &str = "https://api.github.com/copilot_internal/v2/token";
 19
 20#[derive(Clone, Copy, Serialize, Deserialize, Debug, Eq, PartialEq)]
 21#[serde(rename_all = "lowercase")]
 22pub enum Role {
 23    User,
 24    Assistant,
 25    System,
 26}
 27
 28#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
 29#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, EnumIter)]
 30pub enum Model {
 31    #[default]
 32    #[serde(alias = "gpt-4o", rename = "gpt-4o-2024-05-13")]
 33    Gpt4o,
 34    #[serde(alias = "gpt-4", rename = "gpt-4")]
 35    Gpt4,
 36    #[serde(alias = "gpt-3.5-turbo", rename = "gpt-3.5-turbo")]
 37    Gpt3_5Turbo,
 38    #[serde(alias = "o1-preview", rename = "o1-preview-2024-09-12")]
 39    O1Preview,
 40    #[serde(alias = "o1-mini", rename = "o1-mini-2024-09-12")]
 41    O1Mini,
 42    #[serde(alias = "claude-3-5-sonnet", rename = "claude-3.5-sonnet")]
 43    Claude3_5Sonnet,
 44}
 45
 46impl Model {
 47    pub fn uses_streaming(&self) -> bool {
 48        match self {
 49            Self::Gpt4o | Self::Gpt4 | Self::Gpt3_5Turbo | Self::Claude3_5Sonnet => true,
 50            Self::O1Mini | Self::O1Preview => false,
 51        }
 52    }
 53
 54    pub fn from_id(id: &str) -> Result<Self> {
 55        match id {
 56            "gpt-4o" => Ok(Self::Gpt4o),
 57            "gpt-4" => Ok(Self::Gpt4),
 58            "gpt-3.5-turbo" => Ok(Self::Gpt3_5Turbo),
 59            "o1-preview" => Ok(Self::O1Preview),
 60            "o1-mini" => Ok(Self::O1Mini),
 61            "claude-3-5-sonnet" => Ok(Self::Claude3_5Sonnet),
 62            _ => Err(anyhow!("Invalid model id: {}", id)),
 63        }
 64    }
 65
 66    pub fn id(&self) -> &'static str {
 67        match self {
 68            Self::Gpt3_5Turbo => "gpt-3.5-turbo",
 69            Self::Gpt4 => "gpt-4",
 70            Self::Gpt4o => "gpt-4o",
 71            Self::O1Mini => "o1-mini",
 72            Self::O1Preview => "o1-preview",
 73            Self::Claude3_5Sonnet => "claude-3-5-sonnet",
 74        }
 75    }
 76
 77    pub fn display_name(&self) -> &'static str {
 78        match self {
 79            Self::Gpt3_5Turbo => "GPT-3.5",
 80            Self::Gpt4 => "GPT-4",
 81            Self::Gpt4o => "GPT-4o",
 82            Self::O1Mini => "o1-mini",
 83            Self::O1Preview => "o1-preview",
 84            Self::Claude3_5Sonnet => "Claude 3.5 Sonnet",
 85        }
 86    }
 87
 88    pub fn max_token_count(&self) -> usize {
 89        match self {
 90            Self::Gpt4o => 64000,
 91            Self::Gpt4 => 32768,
 92            Self::Gpt3_5Turbo => 12288,
 93            Self::O1Mini => 20000,
 94            Self::O1Preview => 20000,
 95            Self::Claude3_5Sonnet => 200_000,
 96        }
 97    }
 98}
 99
100#[derive(Serialize, Deserialize)]
101pub struct Request {
102    pub intent: bool,
103    pub n: usize,
104    pub stream: bool,
105    pub temperature: f32,
106    pub model: Model,
107    pub messages: Vec<ChatMessage>,
108}
109
110impl Request {
111    pub fn new(model: Model, messages: Vec<ChatMessage>) -> Self {
112        Self {
113            intent: true,
114            n: 1,
115            stream: model.uses_streaming(),
116            temperature: 0.1,
117            model,
118            messages,
119        }
120    }
121}
122
123#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
124pub struct ChatMessage {
125    pub role: Role,
126    pub content: String,
127}
128
129#[derive(Deserialize, Debug)]
130#[serde(tag = "type", rename_all = "snake_case")]
131pub struct ResponseEvent {
132    pub choices: Vec<ResponseChoice>,
133    pub created: u64,
134    pub id: String,
135}
136
137#[derive(Debug, Deserialize)]
138pub struct ResponseChoice {
139    pub index: usize,
140    pub finish_reason: Option<String>,
141    pub delta: Option<ResponseDelta>,
142    pub message: Option<ResponseDelta>,
143}
144
145#[derive(Debug, Deserialize)]
146pub struct ResponseDelta {
147    pub content: Option<String>,
148    pub role: Option<Role>,
149}
150
151#[derive(Deserialize)]
152struct ApiTokenResponse {
153    token: String,
154    expires_at: i64,
155}
156
157#[derive(Clone)]
158struct ApiToken {
159    api_key: String,
160    expires_at: DateTime<chrono::Utc>,
161}
162
163impl ApiToken {
164    pub fn remaining_seconds(&self) -> i64 {
165        self.expires_at
166            .timestamp()
167            .saturating_sub(chrono::Utc::now().timestamp())
168    }
169}
170
171impl TryFrom<ApiTokenResponse> for ApiToken {
172    type Error = anyhow::Error;
173
174    fn try_from(response: ApiTokenResponse) -> Result<Self, Self::Error> {
175        let expires_at = DateTime::from_timestamp(response.expires_at, 0)
176            .ok_or_else(|| anyhow!("invalid expires_at"))?;
177
178        Ok(Self {
179            api_key: response.token,
180            expires_at,
181        })
182    }
183}
184
185struct GlobalCopilotChat(gpui::Model<CopilotChat>);
186
187impl Global for GlobalCopilotChat {}
188
189pub struct CopilotChat {
190    oauth_token: Option<String>,
191    api_token: Option<ApiToken>,
192    client: Arc<dyn HttpClient>,
193}
194
195pub fn init(fs: Arc<dyn Fs>, client: Arc<dyn HttpClient>, cx: &mut AppContext) {
196    let copilot_chat = cx.new_model(|cx| CopilotChat::new(fs, client, cx));
197    cx.set_global(GlobalCopilotChat(copilot_chat));
198}
199
200fn copilot_chat_config_path() -> &'static PathBuf {
201    static COPILOT_CHAT_CONFIG_DIR: OnceLock<PathBuf> = OnceLock::new();
202
203    COPILOT_CHAT_CONFIG_DIR.get_or_init(|| {
204        if cfg!(target_os = "windows") {
205            home_dir().join("AppData").join("Local")
206        } else {
207            home_dir().join(".config")
208        }
209        .join("github-copilot")
210        .join("hosts.json")
211    })
212}
213
214impl CopilotChat {
215    pub fn global(cx: &AppContext) -> Option<gpui::Model<Self>> {
216        cx.try_global::<GlobalCopilotChat>()
217            .map(|model| model.0.clone())
218    }
219
220    pub fn new(fs: Arc<dyn Fs>, client: Arc<dyn HttpClient>, cx: &AppContext) -> Self {
221        let mut config_file_rx = watch_config_file(
222            cx.background_executor(),
223            fs,
224            copilot_chat_config_path().clone(),
225        );
226
227        cx.spawn(|cx| async move {
228            while let Some(contents) = config_file_rx.next().await {
229                let oauth_token = extract_oauth_token(contents);
230
231                cx.update(|cx| {
232                    if let Some(this) = Self::global(cx).as_ref() {
233                        this.update(cx, |this, cx| {
234                            this.oauth_token = oauth_token;
235                            cx.notify();
236                        });
237                    }
238                })?;
239            }
240            anyhow::Ok(())
241        })
242        .detach_and_log_err(cx);
243
244        Self {
245            oauth_token: None,
246            api_token: None,
247            client,
248        }
249    }
250
251    pub fn is_authenticated(&self) -> bool {
252        self.oauth_token.is_some()
253    }
254
255    pub async fn stream_completion(
256        request: Request,
257        low_speed_timeout: Option<Duration>,
258        mut cx: AsyncAppContext,
259    ) -> Result<BoxStream<'static, Result<ResponseEvent>>> {
260        let Some(this) = cx.update(|cx| Self::global(cx)).ok().flatten() else {
261            return Err(anyhow!("Copilot chat is not enabled"));
262        };
263
264        let (oauth_token, api_token, client) = this.read_with(&cx, |this, _| {
265            (
266                this.oauth_token.clone(),
267                this.api_token.clone(),
268                this.client.clone(),
269            )
270        })?;
271
272        let oauth_token = oauth_token.ok_or_else(|| anyhow!("No OAuth token available"))?;
273
274        let token = match api_token {
275            Some(api_token) if api_token.remaining_seconds() > 5 * 60 => api_token.clone(),
276            _ => {
277                let token =
278                    request_api_token(&oauth_token, client.clone(), low_speed_timeout).await?;
279                this.update(&mut cx, |this, cx| {
280                    this.api_token = Some(token.clone());
281                    cx.notify();
282                })?;
283                token
284            }
285        };
286
287        stream_completion(client.clone(), token.api_key, request, low_speed_timeout).await
288    }
289}
290
291async fn request_api_token(
292    oauth_token: &str,
293    client: Arc<dyn HttpClient>,
294    low_speed_timeout: Option<Duration>,
295) -> Result<ApiToken> {
296    let mut request_builder = HttpRequest::builder()
297        .method(Method::GET)
298        .uri(COPILOT_CHAT_AUTH_URL)
299        .header("Authorization", format!("token {}", oauth_token))
300        .header("Accept", "application/json");
301
302    if let Some(low_speed_timeout) = low_speed_timeout {
303        request_builder = request_builder.read_timeout(low_speed_timeout);
304    }
305
306    let request = request_builder.body(AsyncBody::empty())?;
307
308    let mut response = client.send(request).await?;
309
310    if response.status().is_success() {
311        let mut body = Vec::new();
312        response.body_mut().read_to_end(&mut body).await?;
313
314        let body_str = std::str::from_utf8(&body)?;
315
316        let parsed: ApiTokenResponse = serde_json::from_str(body_str)?;
317        ApiToken::try_from(parsed)
318    } else {
319        let mut body = Vec::new();
320        response.body_mut().read_to_end(&mut body).await?;
321
322        let body_str = std::str::from_utf8(&body)?;
323
324        Err(anyhow!("Failed to request API token: {}", body_str))
325    }
326}
327
328fn extract_oauth_token(contents: String) -> Option<String> {
329    serde_json::from_str::<serde_json::Value>(&contents)
330        .map(|v| {
331            v["github.com"]["oauth_token"]
332                .as_str()
333                .map(|v| v.to_string())
334        })
335        .ok()
336        .flatten()
337}
338
339async fn stream_completion(
340    client: Arc<dyn HttpClient>,
341    api_key: String,
342    request: Request,
343    low_speed_timeout: Option<Duration>,
344) -> Result<BoxStream<'static, Result<ResponseEvent>>> {
345    let mut request_builder = HttpRequest::builder()
346        .method(Method::POST)
347        .uri(COPILOT_CHAT_COMPLETION_URL)
348        .header(
349            "Editor-Version",
350            format!(
351                "Zed/{}",
352                option_env!("CARGO_PKG_VERSION").unwrap_or("unknown")
353            ),
354        )
355        .header("Authorization", format!("Bearer {}", api_key))
356        .header("Content-Type", "application/json")
357        .header("Copilot-Integration-Id", "vscode-chat");
358
359    if let Some(low_speed_timeout) = low_speed_timeout {
360        request_builder = request_builder.read_timeout(low_speed_timeout);
361    }
362    let is_streaming = request.stream;
363
364    let request = request_builder.body(AsyncBody::from(serde_json::to_string(&request)?))?;
365    let mut response = client.send(request).await?;
366
367    if !response.status().is_success() {
368        let mut body = Vec::new();
369        response.body_mut().read_to_end(&mut body).await?;
370        let body_str = std::str::from_utf8(&body)?;
371        return Err(anyhow!(
372            "Failed to connect to API: {} {}",
373            response.status(),
374            body_str
375        ));
376    }
377
378    if is_streaming {
379        let reader = BufReader::new(response.into_body());
380        Ok(reader
381            .lines()
382            .filter_map(|line| async move {
383                match line {
384                    Ok(line) => {
385                        let line = line.strip_prefix("data: ")?;
386                        if line.starts_with("[DONE]") {
387                            return None;
388                        }
389
390                        match serde_json::from_str::<ResponseEvent>(line) {
391                            Ok(response) => {
392                                if response.choices.first().is_none()
393                                    || response.choices.first().unwrap().finish_reason.is_some()
394                                {
395                                    None
396                                } else {
397                                    Some(Ok(response))
398                                }
399                            }
400                            Err(error) => Some(Err(anyhow!(error))),
401                        }
402                    }
403                    Err(error) => Some(Err(anyhow!(error))),
404                }
405            })
406            .boxed())
407    } else {
408        let mut body = Vec::new();
409        response.body_mut().read_to_end(&mut body).await?;
410        let body_str = std::str::from_utf8(&body)?;
411        let response: ResponseEvent = serde_json::from_str(body_str)?;
412
413        Ok(futures::stream::once(async move { Ok(response) }).boxed())
414    }
415}