ai 0.7.2

Simple to use LLM library for Rust with streaming, tool calling, OAuth helpers, and a lightweight agent loop
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
use std::sync::Arc;

use crate::env_api_keys::{KnownProvider, get_env_api_key};
use crate::event_stream::AssistantEventStream;
use crate::oauth::{GitHubCopilotOAuthProvider, OAuthApiKey, OAuthCredentials};
use crate::provider::{LanguageModelApi, ModelBuilder, Provider, ProviderCapabilities};
use crate::providers::github_copilot_headers::copilot_static_headers;
use crate::providers::{
    anthropic, openai_completions, openai_embeddings, openai_responses, simple_options,
};
use crate::types::{
    Context, Model, ModelCompat, ModelInput, OpenAICompletionsCompat, OpenAIResponsesCompat,
    SimpleStreamOptions, StreamOptions,
};
use crate::{Error, Result};

const DEFAULT_PROVIDER_ID: KnownProvider = KnownProvider::GitHubCopilot;
const DEFAULT_BASE_URL: &str = "https://api.individual.githubcopilot.com";

#[derive(Clone)]
pub struct GitHubCopilot {
    provider_id: String,
    api_key: Option<String>,
    base_url: Option<String>,
    api: Option<GitHubCopilotApi>,
    http_client: Option<reqwest::Client>,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum GitHubCopilotApi {
    AnthropicMessages,
    OpenAiChatCompletions,
    #[default]
    OpenAiResponses,
}

impl GitHubCopilotApi {
    pub const fn id(self) -> &'static str {
        match self {
            Self::AnthropicMessages => "anthropic-messages",
            Self::OpenAiChatCompletions => "openai-completions",
            Self::OpenAiResponses => "openai-responses",
        }
    }
}

impl GitHubCopilot {
    pub fn builder() -> GitHubCopilotBuilder {
        GitHubCopilotBuilder::default()
    }

    pub fn from_env() -> Result<Self> {
        let api_key = get_env_api_key(DEFAULT_PROVIDER_ID)
            .filter(|key| !key.trim().is_empty())
            .ok_or_else(|| Error::MissingApiKey(DEFAULT_PROVIDER_ID.into()))?;
        Self::builder().api_key(api_key).build()
    }

    pub fn model(&self, id: &str) -> ModelBuilder {
        <Self as Provider>::model(self, id)
    }

    pub fn embedding_model(&self, id: &str) -> ModelBuilder {
        let runtime = Arc::new(openai_embeddings::OpenAiEmbeddingModelApi::new(
            self.api_key.clone(),
            false,
            self.http_client.clone(),
        ));
        ModelBuilder::new_embedding(&self.provider_id, id, runtime)
            .base_url(
                self.base_url
                    .clone()
                    .unwrap_or_else(|| DEFAULT_BASE_URL.to_string()),
            )
            .headers(copilot_static_headers())
            .input(vec![ModelInput::Text])
    }
}

impl Provider for GitHubCopilot {
    fn id(&self) -> &str {
        &self.provider_id
    }

    fn capabilities(&self) -> ProviderCapabilities {
        ProviderCapabilities {
            language_models: true,
            image_models: false,
            embedding_models: true,
        }
    }

    fn model(&self, id: &str) -> ModelBuilder {
        let api = self.api.unwrap_or_else(|| default_api_for_model(id));
        let runtime = Arc::new(GitHubCopilotLanguageModelApi {
            api,
            api_key: self.api_key.clone(),
            http_client: self.http_client.clone(),
        });
        let base_url = self
            .base_url
            .clone()
            .unwrap_or_else(|| DEFAULT_BASE_URL.to_string());
        let base_url = if api == GitHubCopilotApi::AnthropicMessages {
            anthropic_messages_base_url(&base_url)
        } else {
            base_url
        };
        let mut compat = ModelCompat::default();
        match api {
            GitHubCopilotApi::OpenAiResponses => {
                compat.openai_responses = OpenAIResponsesCompat {
                    supports_openai_grammar_tools: is_gpt_5_or_newer(id).then_some(true),
                    ..Default::default()
                };
            }
            GitHubCopilotApi::OpenAiChatCompletions => {
                compat.openai_completions = OpenAICompletionsCompat {
                    supports_store: Some(false),
                    supports_developer_role: Some(false),
                    supports_reasoning_effort: Some(false),
                    ..Default::default()
                };
            }
            GitHubCopilotApi::AnthropicMessages => {}
        }
        ModelBuilder::new(&self.provider_id, id, runtime)
            .base_url(base_url)
            .headers(copilot_static_headers())
            .input(vec![ModelInput::Text, ModelInput::Image])
            .context_window(1_000_000)
            .max_tokens(16_384)
            .compat(compat)
    }
}

fn is_gpt_5_or_newer(id: &str) -> bool {
    id.strip_prefix("gpt-")
        .and_then(|suffix| suffix.split(['.', '-']).next())
        .and_then(|major| major.parse::<u32>().ok())
        .is_some_and(|major| major >= 5)
}

/// Copilot serves Claude 4.x and 5.x through the Anthropic Messages API, and
/// Grok, GPT-5, `oswe`, and MAI models only through `/responses`. Everything
/// else goes through Chat Completions. Used when the catalog carries no
/// explicit `api` for a model.
fn default_api_for_model(id: &str) -> GitHubCopilotApi {
    if is_copilot_claude(id) {
        GitHubCopilotApi::AnthropicMessages
    } else if needs_responses_api(id) {
        GitHubCopilotApi::OpenAiResponses
    } else {
        GitHubCopilotApi::OpenAiChatCompletions
    }
}

/// Matches `claude-{haiku,sonnet,opus}-{4,5}` and its dotted or dashed
/// revisions, the families Copilot serves over the Anthropic Messages API.
fn is_copilot_claude(id: &str) -> bool {
    let Some(rest) = id.strip_prefix("claude-") else {
        return false;
    };
    let rest = ["haiku-", "sonnet-", "opus-"]
        .iter()
        .find_map(|family| rest.strip_prefix(family));
    let Some(rest) = rest else {
        return false;
    };
    let mut chars = rest.chars();
    if !matches!(chars.next(), Some('4' | '5')) {
        return false;
    }
    matches!(chars.next(), None | Some('.') | Some('-'))
}

fn needs_responses_api(id: &str) -> bool {
    id.starts_with("grok-")
        || id.starts_with("gpt-5")
        || id.starts_with("oswe")
        || id.starts_with("mai-")
}

/// Copilot exposes the Anthropic Messages API under `/v1/messages`, while
/// [`anthropic`] appends `/messages` to the configured base URL. Add the
/// version segment so Copilot Claude requests do not 404.
fn anthropic_messages_base_url(base_url: &str) -> String {
    let trimmed = base_url.trim_end_matches('/');
    if trimmed.ends_with("/v1") {
        return trimmed.to_string();
    }
    format!("{trimmed}/v1")
}

#[derive(Default)]
pub struct GitHubCopilotBuilder {
    provider_id: Option<String>,
    api_key: Option<String>,
    base_url: Option<String>,
    api: Option<GitHubCopilotApi>,
    http_client: Option<reqwest::Client>,
}

impl GitHubCopilotBuilder {
    pub fn provider_id(mut self, provider_id: impl Into<String>) -> Self {
        self.provider_id = Some(provider_id.into());
        self
    }

    pub fn api_key(mut self, api_key: impl Into<String>) -> Self {
        self.api_key = Some(api_key.into());
        self
    }

    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = Some(base_url.into());
        self
    }

    pub fn api(mut self, api: GitHubCopilotApi) -> Self {
        self.api = Some(api);
        self
    }

    pub fn anthropic_messages(mut self) -> Self {
        self.api = Some(GitHubCopilotApi::AnthropicMessages);
        self
    }

    pub fn chat_completions(mut self) -> Self {
        self.api = Some(GitHubCopilotApi::OpenAiChatCompletions);
        self
    }

    pub fn responses(mut self) -> Self {
        self.api = Some(GitHubCopilotApi::OpenAiResponses);
        self
    }

    pub fn http_client(mut self, http_client: reqwest::Client) -> Self {
        self.http_client = Some(http_client);
        self
    }

    pub fn build(self) -> Result<GitHubCopilot> {
        Ok(GitHubCopilot {
            provider_id: self
                .provider_id
                .unwrap_or_else(|| DEFAULT_PROVIDER_ID.into()),
            api_key: self.api_key,
            base_url: self.base_url,
            api: self.api,
            http_client: self.http_client,
        })
    }
}

#[derive(Clone)]
struct GitHubCopilotLanguageModelApi {
    api: GitHubCopilotApi,
    api_key: Option<String>,
    http_client: Option<reqwest::Client>,
}

impl GitHubCopilotLanguageModelApi {
    fn with_api_key(&self, mut options: StreamOptions) -> StreamOptions {
        if options
            .api_key
            .as_deref()
            .is_none_or(|api_key| api_key.trim().is_empty())
        {
            options.api_key = self.api_key.clone();
        }
        if options.http_client.is_none() {
            options.http_client = self.http_client.clone();
        }
        options
    }

    fn with_api_key_simple(&self, mut options: SimpleStreamOptions) -> SimpleStreamOptions {
        options.stream = self.with_api_key(options.stream);
        options
    }
}

impl LanguageModelApi for GitHubCopilotLanguageModelApi {
    fn id(&self) -> &str {
        self.api.id()
    }

    fn stream(
        &self,
        model: Model,
        context: Context,
        options: StreamOptions,
    ) -> Result<AssistantEventStream> {
        let options = self.with_api_key(options);
        match self.api {
            GitHubCopilotApi::AnthropicMessages => Ok(anthropic::stream_anthropic(
                model,
                context,
                simple_options::anthropic_options_from_stream_options(options),
            )),
            GitHubCopilotApi::OpenAiChatCompletions => {
                Ok(openai_completions::stream_openai_completions(
                    model,
                    context,
                    simple_options::openai_completions_options_from_stream_options(options),
                ))
            }
            GitHubCopilotApi::OpenAiResponses => Ok(openai_responses::stream_openai_responses(
                model,
                context,
                simple_options::openai_responses_options_from_stream_options(options),
            )),
        }
    }

    fn stream_simple(
        &self,
        model: Model,
        context: Context,
        options: SimpleStreamOptions,
    ) -> Result<AssistantEventStream> {
        let options = self.with_api_key_simple(options);
        match self.api {
            GitHubCopilotApi::AnthropicMessages => {
                anthropic::stream_simple_anthropic(model, context, options)
            }
            GitHubCopilotApi::OpenAiChatCompletions => {
                openai_completions::stream_simple_openai_completions(model, context, options)
            }
            GitHubCopilotApi::OpenAiResponses => {
                openai_responses::stream_simple_openai_responses(model, context, options)
            }
        }
    }
}

pub fn builder() -> GitHubCopilotBuilder {
    GitHubCopilot::builder()
}

pub fn from_env() -> Result<GitHubCopilot> {
    GitHubCopilot::from_env()
}

pub fn oauth() -> GitHubCopilotOAuthProvider {
    crate::oauth::github_copilot_oauth_provider()
}

pub fn base_url(token: Option<&str>, enterprise_domain: Option<&str>) -> String {
    crate::oauth::get_github_copilot_base_url(token, enterprise_domain)
}

pub fn base_url_for_credentials(credentials: &OAuthCredentials) -> String {
    base_url(
        Some(&credentials.access),
        crate::oauth::github_copilot_enterprise_domain(credentials),
    )
}

pub async fn get_oauth_api_key(credentials: &OAuthCredentials) -> Result<OAuthApiKey> {
    let credentials = if crate::utils::time::now_millis() >= credentials.expires {
        oauth().refresh_token(credentials).await?
    } else {
        credentials.clone()
    };
    let api_key = oauth().get_api_key(&credentials);
    Ok(OAuthApiKey {
        new_credentials: credentials,
        api_key,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn selects_the_api_pi_assigns_to_each_copilot_model() {
        for id in [
            "claude-sonnet-5",
            "claude-opus-4.8",
            "claude-haiku-4.5",
            "claude-sonnet-4",
        ] {
            assert_eq!(
                default_api_for_model(id),
                GitHubCopilotApi::AnthropicMessages,
                "{id} should use the Anthropic Messages API"
            );
        }
        for id in [
            "gpt-5.6-sol",
            "grok-4.5",
            "oswe-preview",
            "mai-code-1-flash",
        ] {
            assert_eq!(
                default_api_for_model(id),
                GitHubCopilotApi::OpenAiResponses,
                "{id} should use the Responses API"
            );
        }
        for id in [
            "gpt-4.1",
            "gemini-3.7-flash",
            "claude-sonnet-3.7",
            "o3-mini",
        ] {
            assert_eq!(
                default_api_for_model(id),
                GitHubCopilotApi::OpenAiChatCompletions,
                "{id} should use Chat Completions"
            );
        }
    }

    #[test]
    fn claude_models_target_the_copilot_anthropic_version_path() {
        let provider = builder()
            .api_key("test-token")
            .base_url("https://api.enterprise.githubcopilot.com")
            .build()
            .expect("provider");
        let claude = provider.model("claude-sonnet-5").build().expect("model");
        let gpt = provider.model("gpt-5.6-sol").build().expect("model");

        assert_eq!(claude.api_id(), "anthropic-messages");
        assert_eq!(
            claude.base_url, "https://api.enterprise.githubcopilot.com/v1",
            "Copilot serves Anthropic Messages under /v1/messages"
        );
        assert_eq!(gpt.api_id(), "openai-responses");
        assert_eq!(gpt.base_url, "https://api.enterprise.githubcopilot.com");
    }

    #[test]
    fn explicit_api_selection_still_wins() {
        let provider = builder()
            .api_key("test-token")
            .base_url("https://api.enterprise.githubcopilot.com")
            .chat_completions()
            .build()
            .expect("provider");
        let claude = provider.model("claude-sonnet-5").build().expect("model");

        assert_eq!(claude.api_id(), "openai-completions");
        assert_eq!(claude.compat.openai_completions.supports_store, Some(false));
        assert_eq!(
            claude.compat.openai_completions.supports_developer_role,
            Some(false)
        );
        assert_eq!(
            claude.compat.openai_completions.supports_reasoning_effort,
            Some(false)
        );
    }

    #[test]
    fn anthropic_base_url_is_not_double_versioned() {
        assert_eq!(
            anthropic_messages_base_url("https://api.example.com/v1"),
            "https://api.example.com/v1"
        );
        assert_eq!(
            anthropic_messages_base_url("https://api.example.com/"),
            "https://api.example.com/v1"
        );
    }

    #[test]
    fn responses_gpt_5_models_enable_pi_grammar_tools() {
        let provider = builder().api_key("test-token").build().expect("provider");
        let gpt_5 = provider.model("gpt-5.4").build().expect("model");
        let gpt_4 = provider.model("gpt-4.1").build().expect("model");

        assert_eq!(
            gpt_5.compat.openai_responses.supports_openai_grammar_tools,
            Some(true)
        );
        assert_eq!(
            gpt_4.compat.openai_responses.supports_openai_grammar_tools,
            None
        );
    }

    #[test]
    fn default_model_routing_applies_without_catalog_metadata() {
        let provider = builder().api_key("test-token").build().expect("provider");
        let model = provider.model("claude-opus-4.5").build().expect("model");

        assert_eq!(model.provider_id(), "github-copilot");
        assert_eq!(model.api_id(), "anthropic-messages");
        assert_eq!(model.base_url, format!("{DEFAULT_BASE_URL}/v1"));
        assert_eq!(
            model.headers.get("Editor-Version").map(String::as_str),
            Some("vscode/1.107.0")
        );
        assert_eq!(
            model
                .headers
                .get("Copilot-Integration-Id")
                .map(String::as_str),
            Some("vscode-chat")
        );
    }

    #[test]
    fn explicit_api_supports_unknown_model_ids() {
        let provider = builder()
            .api_key("test-token")
            .chat_completions()
            .base_url("https://copilot.example")
            .build()
            .expect("provider");
        let model = provider.model("future-model").build().expect("model");

        assert_eq!(model.id(), "future-model");
        assert_eq!(model.api_id(), "openai-completions");
        assert_eq!(model.base_url, "https://copilot.example");
    }

    #[test]
    fn embedding_model_uses_openai_embeddings_api() {
        let provider = builder()
            .api_key("test-token")
            .base_url("https://copilot.example")
            .build()
            .expect("provider");
        let model = provider
            .embedding_model("text-embedding-3-small")
            .build_embedding()
            .expect("model");

        assert_eq!(model.api_id(), "openai-embeddings");
        assert_eq!(model.base_url, "https://copilot.example");
        assert_eq!(model.input, vec![ModelInput::Text]);
    }
}