llmg-providers 0.3.0

Provider implementations for LLMG - LLM Gateway
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
//! GitHub Copilot API client for LLMG
//!
//! Implements the Provider trait for GitHub Copilot Chat API using OAuth device flow.
//!
//! Authentication Flow:
//! 1. Get device code from GitHub
//! 2. User visits verification URL and enters code
//! 3. Poll for access token
//! 4. Exchange access token for Copilot API key
//!
//! Environment variables:
//! - GITHUB_COPILOT_ACCESS_TOKEN: Cached OAuth access token
//! - GITHUB_COPILOT_API_KEY: Cached Copilot API key
//! - GITHUB_COPILOT_TOKEN_DIR: Directory to store tokens (default: ~/.config/llmg/github_copilot)

use eventsource_stream::Eventsource;
use futures::{StreamExt, TryStreamExt};
use llmg_core::{
    provider::{ChatCompletionStream, LlmError, Provider},
    streaming::{ChatCompletionChunk, ChoiceDelta, DeltaContent},
    types::{
        ChatCompletionRequest, ChatCompletionResponse, Choice, EmbeddingRequest, EmbeddingResponse,
        Message, Usage,
    },
};
use std::future::Future;
use std::pin::Pin;
// use serde::Deserialize; // removed unused import
use std::collections::HashMap;
use std::path::PathBuf;

/// GitHub Copilot OAuth constants
const GITHUB_CLIENT_ID: &str = "Iv1.b507a08c87ecfe98";
const GITHUB_DEVICE_CODE_URL: &str = "https://github.com/login/device/code";
const GITHUB_ACCESS_TOKEN_URL: &str = "https://github.com/login/oauth/access_token";
const GITHUB_COPILOT_TOKEN_URL: &str = "https://api.github.com/copilot_internal/v2/token";
const GITHUB_COPILOT_API_BASE: &str = "https://api.githubcopilot.com";

/// GitHub Copilot API client
#[derive(Debug, Clone)]
pub struct GitHubCopilotClient {
    http_client: reqwest::Client,
    api_key: String,
    access_token: String,
    editor_version: String,
    integration_id: String,
}

#[derive(Debug, serde::Deserialize)]
struct DeviceCodeResponse {
    device_code: String,
    user_code: String,
    verification_uri: String,
    expires_in: i32,
    interval: i32,
}

#[derive(Debug, serde::Deserialize)]
struct AccessTokenResponse {
    access_token: Option<String>,
    token_type: Option<String>,
    error: Option<String>,
    error_description: Option<String>,
}

#[derive(Debug, serde::Deserialize, serde::Serialize)]
struct CopilotApiKeyResponse {
    token: String,
    expires_at: i64,
    endpoints: Option<HashMap<String, String>>,
}

#[derive(Debug, serde::Serialize)]
struct CopilotChatRequest {
    messages: Vec<CopilotMessage>,
    model: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    temperature: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    top_p: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    stream: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    stop: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    max_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tools: Option<Vec<llmg_core::types::Tool>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_choice: Option<llmg_core::types::ToolChoice>,
}

#[derive(Debug, serde::Serialize)]
struct CopilotMessage {
    role: String,
    content: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_calls: Option<Vec<llmg_core::types::ToolCall>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    tool_call_id: Option<String>,
}

#[derive(Debug, serde::Deserialize)]
struct CopilotChatResponse {
    id: String,
    #[serde(default)]
    object: String,
    #[serde(default)]
    created: i64,
    model: String,
    choices: Vec<CopilotChoice>,
    usage: Option<CopilotUsage>,
}

#[derive(Debug, serde::Deserialize)]
struct CopilotChoice {
    index: i32,
    message: CopilotMessageResponse,
    #[serde(rename = "finish_reason")]
    finish_reason: Option<String>,
}

#[derive(Debug, serde::Deserialize)]
struct CopilotMessageResponse {
    role: String,
    content: String,
}

#[derive(Debug, serde::Deserialize)]
struct CopilotUsage {
    #[serde(rename = "prompt_tokens")]
    prompt_tokens: u32,
    #[serde(default, rename = "completion_tokens")]
    completion_tokens: u32,
    #[serde(rename = "total_tokens")]
    total_tokens: u32,
}

#[derive(Debug, serde::Serialize)]
struct CopilotEmbeddingRequest {
    model: String,
    input: Vec<String>,
}

#[derive(Debug, serde::Deserialize)]
struct CopilotEmbeddingResponse {
    #[serde(default)]
    object: String,
    data: Vec<CopilotEmbeddingData>,
    #[serde(default)]
    model: String,
    usage: CopilotUsage,
}

#[derive(Debug, serde::Deserialize)]
struct CopilotEmbeddingData {
    object: String,
    index: u32,
    embedding: Vec<f32>,
}

impl GitHubCopilotClient {
    /// Create a new GitHub Copilot client with OAuth flow
    pub async fn new() -> Result<Self, LlmError> {
        let token_dir = Self::get_token_dir();
        std::fs::create_dir_all(&token_dir).map_err(|e| {
            LlmError::ProviderError(format!("Failed to create token directory: {}", e))
        })?;

        println!("Loading access token...");
        let access_token = match Self::load_cached_access_token(&token_dir).await {
            Ok(token) => token,
            Err(e) => {
                println!("load_cached_access_token failed with {:?}", e);
                return Err(e);
            }
        };
        println!("Access token loaded.");

        let mut client = Self {
            http_client: reqwest::Client::new(),
            api_key: String::new(),
            access_token,
            editor_version: "vscode/1.85.1".to_string(),
            integration_id: "vscode-chat".to_string(),
        };

        if let Ok(key) = Self::load_cached_api_key(&token_dir).await {
            client.api_key = key;
            println!("API key loaded from cache.");
        } else {
            println!("Refreshing API key...");
            match client.refresh_api_key().await {
                Ok(_) => println!("API key refreshed."),
                Err(e) => {
                    println!("refresh_api_key failed with {:?}", e);
                    return Err(e);
                }
            }
        }

        Ok(client)
    }

    /// Create with explicit API key (for testing or pre-authenticated scenarios)
    pub fn with_api_key(api_key: impl Into<String>, access_token: impl Into<String>) -> Self {
        Self {
            http_client: reqwest::Client::new(),
            api_key: api_key.into(),
            access_token: access_token.into(),
            editor_version: "vscode/1.85.1".to_string(),
            integration_id: "vscode-chat".to_string(),
        }
    }

    fn get_token_dir() -> PathBuf {
        std::env::var("GITHUB_COPILOT_TOKEN_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|_| {
                dirs::config_dir()
                    .unwrap_or_else(|| PathBuf::from("."))
                    .join("llmg/github_copilot")
            })
    }

    async fn load_cached_access_token(token_dir: &std::path::Path) -> Result<String, LlmError> {
        let access_token_path = token_dir.join("access-token");

        if let Ok(token) = std::fs::read_to_string(&access_token_path) {
            let token = token.trim();
            if !token.is_empty() {
                return Ok(token.to_string());
            }
        }

        Self::perform_oauth_flow(token_dir).await
    }

    async fn load_cached_api_key(token_dir: &std::path::Path) -> Result<String, LlmError> {
        let api_key_path = token_dir.join("api-key.json");

        if let Ok(content) = std::fs::read_to_string(&api_key_path) {
            if let Ok(api_key_info) = serde_json::from_str::<CopilotApiKeyResponse>(&content) {
                let now = std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_secs() as i64;

                if api_key_info.expires_at > now {
                    return Ok(api_key_info.token);
                }
            }
        }

        Err(LlmError::AuthError)
    }

    async fn perform_oauth_flow(token_dir: &std::path::Path) -> Result<String, LlmError> {
        let device_code_resp = Self::get_device_code().await?;

        eprintln!("\n🔐 GitHub Copilot Authentication Required");
        eprintln!("Please visit: {}", device_code_resp.verification_uri);
        eprintln!("And enter code: {}\n", device_code_resp.user_code);

        let access_token = Self::poll_for_access_token(
            &device_code_resp.device_code,
            device_code_resp.interval as u64,
        )
        .await?;

        let access_token_path = token_dir.join("access-token");
        std::fs::write(&access_token_path, &access_token)
            .map_err(|e| LlmError::ProviderError(format!("Failed to cache access token: {}", e)))?;

        Ok(access_token)
    }

    async fn get_device_code() -> Result<DeviceCodeResponse, LlmError> {
        let client = reqwest::Client::new();

        let resp = client
            .post(GITHUB_DEVICE_CODE_URL)
            .header("Accept", "application/json")
            .header("User-Agent", "GithubCopilot/1.155.0")
            .json(&serde_json::json!({
                "client_id": GITHUB_CLIENT_ID,
                "scope": "read:user"
            }))
            .send()
            .await
            .map_err(|e| LlmError::HttpError(format!("Failed to get device code: {}", e)))?;

        if !resp.status().is_success() {
            return Err(LlmError::ApiError {
                status: resp.status().as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }

        resp.json::<DeviceCodeResponse>()
            .await
            .map_err(|e| LlmError::HttpError(e.to_string()))
    }

    async fn poll_for_access_token(device_code: &str, interval: u64) -> Result<String, LlmError> {
        let client = reqwest::Client::new();
        let max_attempts = 60;

        for attempt in 0..max_attempts {
            tokio::time::sleep(tokio::time::Duration::from_secs(interval)).await;

            let resp = client
                .post(GITHUB_ACCESS_TOKEN_URL)
                .header("Accept", "application/json")
                .header("User-Agent", "GithubCopilot/1.155.0")
                .json(&serde_json::json!({
                    "client_id": GITHUB_CLIENT_ID,
                    "device_code": device_code,
                    "grant_type": "urn:ietf:params:oauth:grant-type:device_code"
                }))
                .send()
                .await
                .map_err(|e| LlmError::HttpError(format!("Failed to poll for token: {}", e)))?;

            if !resp.status().is_success() {
                continue;
            }

            let token_resp = resp
                .json::<AccessTokenResponse>()
                .await
                .map_err(|e| LlmError::HttpError(e.to_string()))?;

            if let Some(token) = token_resp.access_token {
                eprintln!("✅ Authentication successful!");
                return Ok(token);
            }

            if let Some(error) = token_resp.error {
                if error != "authorization_pending" {
                    return Err(LlmError::AuthError);
                }
            }

            if attempt % 6 == 0 {
                eprintln!(
                    "⏳ Waiting for authorization... (attempt {}/{})",
                    attempt + 1,
                    max_attempts
                );
            }
        }

        Err(LlmError::AuthError)
    }

    async fn refresh_api_key(&mut self) -> Result<(), LlmError> {
        let client = reqwest::Client::new();

        let resp = client
            .get(GITHUB_COPILOT_TOKEN_URL)
            .header("Authorization", format!("token {}", self.access_token))
            .header("Accept", "application/json")
            .header("User-Agent", "GithubCopilot/1.155.0")
            .send()
            .await
            .map_err(|e| LlmError::HttpError(format!("Failed to refresh API key: {}", e)))?;

        if !resp.status().is_success() {
            if resp.status().as_u16() == 401 {
                let token_dir = Self::get_token_dir();
                self.access_token = Self::perform_oauth_flow(&token_dir).await?;
                return Box::pin(self.refresh_api_key()).await;
            }

            return Err(LlmError::ApiError {
                status: resp.status().as_u16(),
                message: resp.text().await.unwrap_or_default(),
            });
        }

        let api_key_info = resp
            .json::<CopilotApiKeyResponse>()
            .await
            .map_err(|e| LlmError::HttpError(e.to_string()))?;

        self.api_key = api_key_info.token.clone();

        let token_dir = Self::get_token_dir();
        let api_key_path = token_dir.join("api-key.json");
        std::fs::write(&api_key_path, serde_json::to_string(&api_key_info).unwrap())
            .map_err(|e| LlmError::ProviderError(format!("Failed to cache API key: {}", e)))?;

        Ok(())
    }

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

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

    fn convert_request(&self, request: ChatCompletionRequest) -> CopilotChatRequest {
        let messages: Vec<CopilotMessage> = request
            .messages
            .into_iter()
            .map(|msg| match msg {
                Message::System { content, .. } => CopilotMessage {
                    role: "system".to_string(),
                    content,
                    tool_calls: None,
                    tool_call_id: None,
                },
                Message::User { content, .. } => CopilotMessage {
                    role: "user".to_string(),
                    content,
                    tool_calls: None,
                    tool_call_id: None,
                },
                Message::Assistant {
                    content,
                    tool_calls,
                    ..
                } => CopilotMessage {
                    role: "assistant".to_string(),
                    content: content.unwrap_or_default(),
                    tool_calls,
                    tool_call_id: None,
                },
                Message::Tool {
                    content,
                    tool_call_id,
                } => CopilotMessage {
                    role: "tool".to_string(),
                    content,
                    tool_calls: None,
                    tool_call_id: Some(tool_call_id),
                },
            })
            .collect();

        CopilotChatRequest {
            messages,
            model: request.model,
            temperature: request.temperature,
            top_p: request.top_p,
            stream: request.stream,
            stop: request.stop,
            max_tokens: request.max_tokens,
            tools: request.tools,
            tool_choice: request.tool_choice,
        }
    }

    fn convert_response(&self, response: CopilotChatResponse) -> ChatCompletionResponse {
        ChatCompletionResponse {
            id: response.id,
            object: response.object,
            created: response.created,
            model: response.model,
            choices: response
                .choices
                .into_iter()
                .map(|c| Choice {
                    index: c.index as u32,
                    message: Message::Assistant {
                        content: Some(c.message.content),
                        refusal: None,
                        tool_calls: None,
                    },
                    finish_reason: c.finish_reason,
                })
                .collect(),
            usage: response.usage.map(|u| Usage {
                prompt_tokens: u.prompt_tokens,
                completion_tokens: u.completion_tokens,
                total_tokens: u.total_tokens,
            }),
        }
    }

    async fn make_request(
        &mut self,
        request: ChatCompletionRequest,
    ) -> Result<ChatCompletionResponse, LlmError> {
        if self.api_key.is_empty() {
            self.refresh_api_key().await?;
        }

        let url = format!("{}/chat/completions", GITHUB_COPILOT_API_BASE);
        let copilot_req = self.convert_request(request.clone());

        let initiator = if request
            .messages
            .iter()
            .any(|m| matches!(m, Message::Assistant { .. } | Message::Tool { .. }))
        {
            "agent"
        } else {
            "user"
        };

        let request_id = uuid::Uuid::new_v4().to_string();
        let resp = self
            .http_client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            .header("editor-version", "vscode/1.95.0")
            .header("editor-plugin-version", "copilot-chat/0.26.7")
            .header("Copilot-Integration-Id", "vscode-chat")
            .header("User-Agent", "GitHubCopilotChat/0.26.7")
            .header("openai-intent", "conversation-panel")
            .header("x-github-api-version", "2025-04-01")
            .header("x-request-id", &request_id)
            .header("x-vscode-user-agent-library-version", "electron-fetch")
            .header("X-Initiator", initiator)
            .json(&copilot_req)
            .send()
            .await
            .map_err(|e| LlmError::HttpError(e.to_string()))?;

        if resp.status().as_u16() == 401 {
            self.refresh_api_key().await?;
            return Box::pin(async move { self.make_request(request).await }).await;
        }

        if !resp.status().is_success() {
            let status = resp.status().as_u16();
            let text = resp.text().await.unwrap_or_default();

            if status == 429 {
                return Err(LlmError::RateLimitError);
            }

            return Err(LlmError::ApiError {
                status,
                message: text,
            });
        }

        let text = resp
            .text()
            .await
            .map_err(|e| LlmError::HttpError(e.to_string()))?;
        let copilot_resp: CopilotChatResponse = serde_json::from_str(&text)
            .map_err(|e| LlmError::HttpError(format!("error decoding response body: {}", e)))?;

        Ok(self.convert_response(copilot_resp))
    }

    async fn make_stream_request(
        &mut self,
        request: ChatCompletionRequest,
    ) -> Result<ChatCompletionStream, LlmError> {
        if self.api_key.is_empty() {
            self.refresh_api_key().await?;
        }

        let url = format!("{}/chat/completions", GITHUB_COPILOT_API_BASE);
        let mut copilot_req = self.convert_request(request.clone());
        copilot_req.stream = Some(true);

        let initiator = if request
            .messages
            .iter()
            .any(|m| matches!(m, Message::Assistant { .. } | Message::Tool { .. }))
        {
            "agent"
        } else {
            "user"
        };

        let request_id = uuid::Uuid::new_v4().to_string();
        let resp = self
            .http_client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            .header("editor-version", "vscode/1.95.0")
            .header("editor-plugin-version", "copilot-chat/0.26.7")
            .header("Copilot-Integration-Id", "vscode-chat")
            .header("User-Agent", "GitHubCopilotChat/0.26.7")
            .header("openai-intent", "conversation-panel")
            .header("x-github-api-version", "2025-04-01")
            .header("x-request-id", &request_id)
            .header("x-vscode-user-agent-library-version", "electron-fetch")
            .header("X-Initiator", initiator)
            .json(&copilot_req)
            .send()
            .await
            .map_err(|e| LlmError::HttpError(e.to_string()))?;

        if resp.status().as_u16() == 401 {
            self.refresh_api_key().await?;
            return Box::pin(async move { self.make_stream_request(request).await }).await;
        }

        if !resp.status().is_success() {
            let status = resp.status().as_u16();
            let text = resp.text().await.unwrap_or_default();

            if status == 429 {
                return Err(LlmError::RateLimitError);
            }

            return Err(LlmError::ApiError {
                status,
                message: text,
            });
        }

        let chunk_id = ChatCompletionChunk::generate_id();
        let model = copilot_req.model.clone();

        let stream = resp
            .bytes_stream()
            .eventsource()
            .map_err(|e| LlmError::HttpError(e.to_string()))
            .then(move |event_result| {
                let chunk_id = chunk_id.clone();
                let model = model.clone();
                async move {
                    match event_result {
                        Ok(event) => parse_copilot_sse_data(&event.data, &chunk_id, &model),
                        Err(e) => Err(LlmError::HttpError(e.to_string())),
                    }
                }
            })
            .try_filter_map(|chunk| async move { Ok(chunk) });

        Ok(Box::pin(stream) as ChatCompletionStream)
    }

    async fn make_embedding_request(
        &mut self,
        request: EmbeddingRequest,
    ) -> Result<EmbeddingResponse, LlmError> {
        if self.api_key.is_empty() {
            self.refresh_api_key().await?;
        }

        let url = format!("{}/embeddings", GITHUB_COPILOT_API_BASE);
        let copilot_req = CopilotEmbeddingRequest {
            model: request.model.clone(),
            input: vec![request.input.clone()],
        };

        let request_id = uuid::Uuid::new_v4().to_string();
        let resp = self
            .http_client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            .header("editor-version", "vscode/1.95.0")
            .header("editor-plugin-version", "copilot-chat/0.26.7")
            .header("Copilot-Integration-Id", "vscode-chat")
            .header("User-Agent", "GitHubCopilotChat/0.26.7")
            .header("openai-intent", "conversation-panel")
            .header("x-github-api-version", "2025-04-01")
            .header("x-request-id", &request_id)
            .header("x-vscode-user-agent-library-version", "electron-fetch")
            .header("X-Initiator", "user")
            .json(&copilot_req)
            .send()
            .await
            .map_err(|e| LlmError::HttpError(e.to_string()))?;

        if resp.status().as_u16() == 401 {
            self.refresh_api_key().await?;
            return Box::pin(async move { self.make_embedding_request(request).await }).await;
        }

        if !resp.status().is_success() {
            let status = resp.status().as_u16();
            let text = resp.text().await.unwrap_or_default();

            if status == 429 {
                return Err(LlmError::RateLimitError);
            }

            return Err(LlmError::ApiError {
                status,
                message: text,
            });
        }

        let text = resp
            .text()
            .await
            .map_err(|e| LlmError::HttpError(e.to_string()))?;
        let copilot_resp: CopilotEmbeddingResponse = serde_json::from_str(&text)
            .map_err(|e| LlmError::HttpError(format!("error decoding response body: {}", e)))?;

        Ok(EmbeddingResponse {
            id: uuid::Uuid::new_v4().to_string(),
            object: if copilot_resp.object.is_empty() {
                "list".to_string()
            } else {
                copilot_resp.object
            },
            data: copilot_resp
                .data
                .into_iter()
                .map(|d| llmg_core::types::Embedding {
                    index: d.index,
                    object: d.object,
                    embedding: d.embedding,
                })
                .collect(),
            model: copilot_resp.model,
            usage: Usage {
                prompt_tokens: copilot_resp.usage.prompt_tokens,
                completion_tokens: copilot_resp.usage.completion_tokens,
                total_tokens: copilot_resp.usage.total_tokens,
            },
        })
    }

    pub fn get_models() -> Vec<String> {
        vec![
            "gpt-4".to_string(),
            "gpt-4o".to_string(),
            "gpt-4o-mini".to_string(),
            "gpt-3.5-turbo".to_string(),
            "o1-preview".to_string(),
            "o1-mini".to_string(),
            "claude-3-5-sonnet".to_string(),
            "text-embedding-3-small".to_string(),
        ]
    }
}

#[async_trait::async_trait]
impl Provider for GitHubCopilotClient {
    async fn chat_completion(
        &self,
        request: ChatCompletionRequest,
    ) -> Result<ChatCompletionResponse, LlmError> {
        let mut client = self.clone();
        client.make_request(request).await
    }

    fn chat_completion_stream(
        &self,
        request: ChatCompletionRequest,
    ) -> Pin<Box<dyn Future<Output = Result<ChatCompletionStream, LlmError>> + Send + '_>> {
        let mut client = self.clone();
        Box::pin(async move { client.make_stream_request(request).await })
    }

    async fn embeddings(&self, request: EmbeddingRequest) -> Result<EmbeddingResponse, LlmError> {
        let mut client = self.clone();
        client.make_embedding_request(request).await
    }
    fn provider_name(&self) -> &'static str {
        "github_copilot"
    }
}

fn parse_copilot_sse_data(
    data: &str,
    chunk_id: &str,
    model: &str,
) -> Result<Option<ChatCompletionChunk>, LlmError> {
    let data = data.trim();
    if data.is_empty() || data == "[DONE]" {
        return Ok(None);
    }

    let parsed: serde_json::Value =
        serde_json::from_str(data).map_err(LlmError::SerializationError)?;

    let choices = parsed
        .get("choices")
        .and_then(|c| c.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|choice| {
                    let index = choice.get("index").and_then(|i| i.as_u64()).unwrap_or(0) as u32;
                    let delta = choice.get("delta")?;
                    let finish_reason = choice
                        .get("finish_reason")
                        .and_then(|f| f.as_str())
                        .map(|s| s.to_string());

                    let role = delta
                        .get("role")
                        .and_then(|r| r.as_str())
                        .map(|s| s.to_string());
                    let content = delta
                        .get("content")
                        .and_then(|c| c.as_str())
                        .map(|s| s.to_string());
                    let tool_calls = delta
                        .get("tool_calls")
                        .and_then(|t| serde_json::from_value(t.clone()).ok());

                    Some(ChoiceDelta {
                        index,
                        delta: DeltaContent {
                            role,
                            content,
                            tool_calls,
                        },
                        finish_reason,
                    })
                })
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();

    if choices.is_empty() {
        return Ok(None);
    }

    Ok(Some(ChatCompletionChunk {
        id: chunk_id.to_string(),
        object: "chat.completion.chunk".to_string(),
        created: chrono::Utc::now().timestamp(),
        model: model.to_string(),
        choices,
        usage: None,
    }))
}

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

    #[test]
    fn test_copilot_client_with_api_key() {
        let client = GitHubCopilotClient::with_api_key("test-api-key", "test-access-token");
        assert_eq!(client.provider_name(), "github_copilot");
    }

    #[test]
    fn test_request_conversion() {
        let client = GitHubCopilotClient::with_api_key("test-key", "test-token");

        let request = ChatCompletionRequest {
            model: "gpt-4".to_string(),
            messages: vec![
                Message::System {
                    content: "You are a helpful coding assistant".to_string(),
                    name: None,
                },
                Message::User {
                    content: "Write a Python function".to_string(),
                    name: None,
                },
            ],
            temperature: Some(0.7),
            max_tokens: Some(1000),
            stream: None,
            top_p: None,
            frequency_penalty: None,
            presence_penalty: None,
            stop: None,
            user: None,
            tools: None,
            tool_choice: None,
        };

        let copilot_req = client.convert_request(request);

        assert_eq!(copilot_req.model, "gpt-4");
        assert_eq!(copilot_req.messages.len(), 2);
        assert_eq!(copilot_req.messages[0].role, "system");
        assert_eq!(copilot_req.messages[1].role, "user");
    }

    #[test]
    fn test_tool_calling_conversion() {
        let client = GitHubCopilotClient::with_api_key("test-key", "test-token");

        let tool = llmg_core::types::Tool {
            r#type: "function".to_string(),
            function: llmg_core::types::FunctionDefinition {
                name: "get_weather".to_string(),
                description: Some("Get the weather".to_string()),
                parameters: serde_json::json!({"type": "object", "properties": {"location": {"type": "string"}}}),
            },
        };

        let request = ChatCompletionRequest {
            model: "gpt-4".to_string(),
            messages: vec![Message::User {
                content: "Weather?".to_string(),
                name: None,
            }],
            temperature: None,
            max_tokens: None,
            stream: None,
            top_p: None,
            frequency_penalty: None,
            presence_penalty: None,
            stop: None,
            user: None,
            tools: Some(vec![tool]),
            tool_choice: Some(llmg_core::types::ToolChoice::String("auto".to_string())),
        };

        let copilot_req = client.convert_request(request);

        assert!(copilot_req.tools.is_some());
        assert_eq!(copilot_req.tools.unwrap().len(), 1);
        assert!(copilot_req.tool_choice.is_some());
    }

    #[test]
    fn test_parse_copilot_sse_data_tool_calls() {
        let raw_sse = r#"{"id":"chatcmpl-123","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_abc","type":"function","function":{"name":"get_weather","arguments":"{\"location\":\"Boston\"}"}}]},"finish_reason":null}]}"#;
        let chunk = parse_copilot_sse_data(raw_sse, "chatcmpl-123", "gpt-4")
            .unwrap()
            .unwrap();

        assert_eq!(chunk.choices.len(), 1);
        let choice = &chunk.choices[0];
        assert!(choice.delta.tool_calls.is_some());

        let tool_calls = choice.delta.tool_calls.as_ref().unwrap();
        assert_eq!(tool_calls.len(), 1);
        assert_eq!(tool_calls[0].id.as_deref(), Some("call_abc"));
        assert_eq!(
            tool_calls[0]
                .function
                .as_ref()
                .and_then(|f| f.name.as_deref()),
            Some("get_weather")
        );
    }
}