forked from jmdaly/llm-github-copilot
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathllm_github_copilot.py
More file actions
1499 lines (1266 loc) · 60.3 KB
/
llm_github_copilot.py
File metadata and controls
1499 lines (1266 loc) · 60.3 KB
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
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import llm
import os
import json
import time
from pathlib import Path
import httpx
from datetime import datetime, timezone
from typing import Optional, Any, Generator, List
from pydantic import Field, field_validator
import click
import secrets
def _fetch_models_data(authenticator: "GitHubCopilotAuthenticator") -> dict:
"""
Helper function to fetch raw model data from the GitHub Copilot API.
This function makes an HTTP request to the GitHub Copilot API to retrieve
information about available models. It handles authentication and error reporting.
Args:
authenticator: The GitHubCopilotAuthenticator instance to use for authentication
Returns:
dict: The raw JSON response from the API containing model data
Raises:
Exception: If the API request fails for any reason
"""
try:
api_key = authenticator.get_api_key()
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"Accept": "application/json",
"editor-version": "vscode/1.85.1",
}
response = httpx.get(
"https://api.githubcopilot.com/models", headers=headers, timeout=30
)
response.raise_for_status()
return response.json()
except httpx.HTTPStatusError as e:
# Ensure the response body is read before accessing .text,
# in case of chunked error responses.
e.response.read()
error_body_text = e.response.text
print(
f"Error fetching models data (HTTP {e.response.status_code}): {error_body_text}"
)
raise
except httpx.RequestError as e:
print(f"Error fetching models data (Request Error): {str(e)}")
raise
except Exception as e:
# Catch potential errors from get_api_key() as well
print(f"Error fetching models data: {str(e)}")
raise
@llm.hookimpl
def register_models(register):
"""Register all GitHub Copilot models with the LLM CLI tool."""
# Register the default model first
default_model = GitHubCopilot()
register(default_model)
# Try to fetch available models without forcing authentication
try:
# Create an authenticator to fetch models
authenticator = GitHubCopilotAuthenticator()
# Only fetch models if we already have valid credentials
if authenticator.has_valid_credentials():
models = fetch_available_models(authenticator)
# Register all model variants
for model_id in models:
if model_id == default_model.model_id:
continue # Skip the default model as it's already registered
model = GitHubCopilot()
model.model_id = model_id
register(model)
except Exception as e:
print(f"Warning: Failed to fetch GitHub Copilot models: {str(e)}")
print("Falling back to default model only")
def fetch_available_models(authenticator: "GitHubCopilotAuthenticator") -> set[str]:
"""
Fetches available model IDs from the GitHub Copilot API.
This function retrieves the list of available models from the GitHub Copilot API
and formats them as LLM-compatible model IDs (e.g., "github_copilot/claude-3-7-sonnet").
Args:
authenticator: The GitHubCopilotAuthenticator instance to use for authentication
Returns:
set[str]: A set of available model IDs, always including at least "github_copilot"
Note:
If the API request fails, this function will return a minimal set containing
only the default "github_copilot" model ID.
"""
model_ids = {"github_copilot"} # Always include default model
try:
models_data = _fetch_models_data(authenticator)
# Process models from response - models are in the "data" field
for model in models_data.get("data", []):
model_id = model.get("id")
# Skip the model ID that the base 'github_copilot' maps to by default
if model_id and model_id != GitHubCopilot.DEFAULT_MODEL_MAPPING:
model_ids.add(f"github_copilot/{model_id}")
return model_ids
except Exception as e:
# Error is logged within _fetch_models_data
# Return a minimal set of known models as fallback
return {"github_copilot"}
class GitHubCopilotAuthenticator:
"""
Handles authentication with GitHub Copilot using device code flow.
"""
# GitHub API constants
GITHUB_CLIENT_ID = "Iv1.b507a08c87ecfe98" # GitHub Copilot client ID
GITHUB_DEVICE_CODE_URL = "https://github.com/login/device/code"
GITHUB_ACCESS_TOKEN_URL = "https://github.com/login/oauth/access_token"
GITHUB_API_KEY_URL = "https://api.github.com/copilot_internal/v2/token"
# Default headers for GitHub API
DEFAULT_HEADERS = {
"accept": "application/json",
"editor-version": "vscode/1.85.1",
"accept-encoding": "gzip,deflate,br",
"content-type": "application/json",
}
# Authentication constants
MAX_LOGIN_ATTEMPTS = 3
MAX_POLL_ATTEMPTS = 12
POLL_INTERVAL = 5 # seconds
# Key identifiers for LLM key storage
ACCESS_TOKEN_KEY = "github_copilot_access_token"
DEFAULT_KEYS_JSON_CONTENT = {"// Note": "This file stores secret API credentials. Do not share!"}
def __init__(self) -> None:
# Token storage paths for API key (still using file for this)
self.token_dir = Path(llm.user_dir())
self.token_dir.mkdir(parents=True, exist_ok=True)
self.api_key_file = self.token_dir / os.getenv(
"GITHUB_COPILOT_API_KEY_FILE", "github_copilot_api_key.json"
)
def has_valid_credentials(self) -> bool:
"""
Check if we have valid API credentials without triggering authentication.
This method checks for valid credentials in the following order:
1. Checks if a valid API key file exists with a non-expired token
2. Checks if a valid access token exists in the LLM key storage
Returns:
bool: True if valid credentials exist, False otherwise
Note:
This method does not attempt to refresh or obtain new credentials.
"""
# Order of checks:
# 1. Valid (non-expired, token exists and is non-empty) API key file
# 2. Environment variables for access token
# 3. LLM-stored access token (non-empty)
# Check 1: API Key File
try:
if self.api_key_file.exists():
api_key_info = json.loads(self.api_key_file.read_text())
# Ensure api_key_info is a dict, token exists and is not empty, and is not expired
if isinstance(api_key_info, dict) and \
api_key_info.get("token") and \
isinstance(api_key_info.get("token"), str) and \
api_key_info.get("token").strip() and \
api_key_info.get("expires_at", 0) > datetime.now().timestamp():
return True
except (FileNotFoundError, json.JSONDecodeError, KeyError, AttributeError, TypeError):
# Ignore errors related to API key file processing, proceed to next checks
pass
# Check 2: Environment Variables
for env_var in ["GH_COPILOT_TOKEN", "GITHUB_COPILOT_TOKEN"]:
env_token = os.environ.get(env_var)
if env_token and env_token.strip():
return True
# Check 3: LLM-stored Access Token
try:
access_token = llm.get_key(None, self.ACCESS_TOKEN_KEY)
if access_token and isinstance(access_token, str) and access_token.strip():
return True
except Exception: # Catching broad exception from llm.get_key if it fails
pass
return False
def _get_github_headers(self, access_token: Optional[str] = None) -> dict[str, str]:
"""
Generate standard GitHub headers for API requests.
Creates a dictionary of HTTP headers required for GitHub API requests,
optionally including an authorization header with the provided access token.
Args:
access_token: Optional GitHub access token to include in the headers
Returns:
dict[str, str]: Dictionary of HTTP headers for GitHub API requests
"""
headers = self.DEFAULT_HEADERS.copy()
if access_token:
headers["authorization"] = f"token {access_token}"
return headers
def get_access_token(self) -> str:
"""
Get GitHub access token, refreshing if necessary.
First checks for GH_COPILOT_KEY environment variable,
then falls back to the LLM key storage.
"""
# Check environment variables first
for env_var in ["GH_COPILOT_TOKEN", "GITHUB_COPILOT_TOKEN"]:
env_token = os.environ.get(env_var)
if env_token and env_token.strip():
return env_token.strip()
# Try to read existing token from LLM key storage
try:
access_token = llm.get_key(None, self.ACCESS_TOKEN_KEY)
if access_token:
return access_token
except Exception:
pass
# No valid token found, inform user they need to authenticate
raise Exception(
"GitHub Copilot authentication required. Run 'llm github_copilot auth login' to authenticate or set the GH_COPILOT_KEY environment variable."
)
def get_api_key(self) -> str:
"""
Get the API key, refreshing if necessary.
"""
try:
api_key_info = json.loads(self.api_key_file.read_text())
if api_key_info.get("expires_at", 0) > datetime.now().timestamp():
return api_key_info.get("token")
except (FileNotFoundError, json.JSONDecodeError, KeyError):
pass
# If we don't have a valid API key, check if we need to authenticate first
try:
access_token = llm.get_key("github_copilot", self.ACCESS_TOKEN_KEY)
except (TypeError, Exception):
access_token = None
if not access_token and not (
os.environ.get("GH_COPILOT_TOKEN") or os.environ.get("GITHUB_COPILOT_TOKEN")
):
raise Exception(
"GitHub Copilot authentication required. Run 'llm github_copilot auth login' first."
)
try:
api_key_info = self._refresh_api_key()
self.api_key_file.write_text(json.dumps(api_key_info), encoding="utf-8")
self.api_key_file.chmod(0o600)
return api_key_info.get("token")
except Exception as e:
raise Exception(f"Failed to get API key: {str(e)}")
def _get_device_code(self) -> dict[str, str]:
"""
Get a device code for GitHub authentication using the device flow.
This method initiates the GitHub device flow authentication process by
requesting a device code from the GitHub API. The device code is used
to associate the user's browser session with this application.
Returns:
dict[str, str]: A dictionary containing the device code, user code,
verification URI, and other information needed for
the authentication flow
Raises:
Exception: If the request fails or the response is missing required fields
"""
required_fields = ["device_code", "user_code", "verification_uri"]
try:
client = httpx.Client()
resp = client.post(
self.GITHUB_DEVICE_CODE_URL,
headers=self._get_github_headers(),
json={"client_id": self.GITHUB_CLIENT_ID, "scope": "read:user"},
timeout=30,
)
resp.raise_for_status()
resp_json = resp.json()
# Validate response contains required fields
if not all(field in resp_json for field in required_fields):
missing = [f for f in required_fields if f not in resp_json]
raise Exception(
f"Response missing required fields: {', '.join(missing)}"
)
return resp_json
except httpx.HTTPStatusError as e:
raise Exception(f"HTTP error {e.response.status_code}: {e.response.text}")
except httpx.RequestError as e:
raise Exception(f"Request error: {str(e)}")
except Exception as e:
raise Exception(f"Failed to get device code: {str(e)}")
def _poll_for_access_token(self, device_code: str) -> str:
"""
Poll for an access token after user authentication.
This method repeatedly polls the GitHub API to check if the user has
completed the authentication process in their browser. It continues
polling until either the user completes authentication, an error occurs,
or the maximum number of polling attempts is reached.
Args:
device_code: The device code obtained from _get_device_code()
Returns:
str: The GitHub access token if authentication is successful
Raises:
Exception: If polling times out or an error occurs during polling
"""
client = httpx.Client()
for attempt in range(self.MAX_POLL_ATTEMPTS):
try:
resp = client.post(
self.GITHUB_ACCESS_TOKEN_URL,
headers=self._get_github_headers(),
json={
"client_id": self.GITHUB_CLIENT_ID,
"device_code": device_code,
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
},
timeout=30,
)
resp.raise_for_status()
resp_json = resp.json()
if "access_token" in resp_json:
print("Authentication successful!")
return resp_json["access_token"]
elif (
"error" in resp_json
and resp_json.get("error") == "authorization_pending"
):
print(
f"Waiting for authorization... (attempt {attempt + 1}/{self.MAX_POLL_ATTEMPTS})"
)
else:
error_msg = resp_json.get(
"error_description", resp_json.get("error", "Unknown error")
)
print(f"Unexpected response: {error_msg}")
except httpx.HTTPStatusError as e:
raise Exception(
f"HTTP error {e.response.status_code}: {e.response.text}"
)
except httpx.RequestError as e:
raise Exception(f"Request error: {str(e)}")
except Exception as e:
raise Exception(f"Failed to get access token: {str(e)}")
time.sleep(self.POLL_INTERVAL)
raise Exception("Timed out waiting for user to authorize the device")
def _login(self) -> str:
"""
Login to GitHub Copilot using device code flow.
This method orchestrates the complete GitHub device flow authentication process:
1. Obtains a device code and user code
2. Displays instructions for the user to complete authentication in their browser
3. Polls for the access token until the user completes authentication
Returns:
str: The GitHub access token if authentication is successful
Raises:
Exception: If any step of the authentication process fails
"""
device_code_info = self._get_device_code()
device_code = device_code_info["device_code"]
user_code = device_code_info["user_code"]
verification_uri = device_code_info["verification_uri"]
click.echo("Fetching API key...")
print(
f"\nPlease visit {verification_uri} and enter code {user_code} to authenticate GitHub Copilot.\n"
)
return self._poll_for_access_token(device_code)
def _refresh_api_key(self, access_token_override: Optional[str] = None) -> dict[str, Any]:
"""
Refresh the API key using the access token.
Args:
access_token_override: If provided, use this access token instead of
calling get_access_token().
This method exchanges a GitHub access token for a GitHub Copilot API key
by making a request to the GitHub Copilot API. It includes retry logic
to handle transient failures.
Returns:
dict[str, Any]: A dictionary containing the API key and its expiration time
in the format {"token": "api_key", "expires_at": timestamp}
Raises:
Exception: If the API key cannot be refreshed after maximum retries
"""
access_token = access_token_override or self.get_access_token()
headers = self._get_github_headers(access_token)
max_retries = 3
for attempt in range(max_retries):
try:
client = httpx.Client()
response = client.get(
self.GITHUB_API_KEY_URL, headers=headers, timeout=30
)
response.raise_for_status()
response_json = response.json()
if "token" in response_json:
return response_json
else:
print(f"API key response missing token: {response_json}")
except httpx.HTTPStatusError as e:
print(f"HTTP error {e.response.status_code}: {e.response.text}")
except httpx.RequestError as e:
print(f"Request error: {str(e)}")
except Exception as e:
print(
f"Error refreshing API key (attempt {attempt + 1}/{max_retries}): {str(e)}"
)
if attempt < max_retries - 1:
time.sleep(1)
raise Exception("Failed to refresh API key after maximum retries")
def _get_github_user_info(self, access_token_override: Optional[str] = None) -> Optional[dict[str, Any]]:
"""
Fetch user information from GitHub API using the access token.
Args:
access_token_override: If provided, use this access token instead of
calling get_access_token().
Returns:
dict[str, Any]: Dictionary containing user information (e.g., login)
or None if fetching fails.
"""
try:
access_token = access_token_override or self.get_access_token()
headers = self._get_github_headers(access_token)
client = httpx.Client()
response = client.get(
"https://api.github.com/user", headers=headers, timeout=30
)
response.raise_for_status()
return response.json()
except Exception as e:
print(f"Warning: Failed to fetch GitHub user info: {str(e)}")
return None
class GitHubCopilot(llm.Model):
"""
GitHub Copilot model implementation for LLM.
"""
model_id = "github_copilot"
can_stream = True
# API base URL
API_BASE = "https://api.githubcopilot.com"
# Default system message
DEFAULT_SYSTEM_MESSAGE = "You are GitHub Copilot, an AI programming assistant."
# Default request timeout in seconds
DEFAULT_TIMEOUT = 120
NON_STREAMING_TIMEOUT = 180
# Default model mapping
DEFAULT_MODEL_MAPPING = "gpt-4o"
# Cache for model mappings
_model_mappings = None
# Cache for streaming models
_streaming_models = None
class Options(llm.Options):
"""
Options for the GitHub Copilot model.
"""
max_tokens: Optional[int] = Field(
description="Maximum number of tokens to generate", default=None
)
temperature: Optional[float] = Field(
description="Controls randomness in the output (0-1)",
default=None,
)
@field_validator("max_tokens")
def validate_max_tokens(cls, max_tokens):
if max_tokens is None:
return None
if max_tokens < 1:
raise ValueError("max_tokens must be >= 1")
return max_tokens
@field_validator("temperature")
def validate_temperature(cls, temperature):
if temperature is None:
return None
if not 0 <= temperature <= 1:
raise ValueError("temperature must be between 0 and 1")
return temperature
def __init__(self) -> None:
"""Initialize the GitHub Copilot model."""
self.authenticator = GitHubCopilotAuthenticator()
@classmethod
def get_model_mappings(cls) -> dict[str, str]:
"""
Get model mappings, fetching them if not already cached.
This method retrieves the mapping between LLM model IDs (e.g., "github_copilot/gpt-4o")
and the corresponding API model names (e.g., "gpt-4o"). It caches the results
to avoid unnecessary API calls.
Returns:
Dict mapping model IDs to API model names
Note:
If fetching the mappings fails, a default mapping will be returned
that includes only the default model.
"""
if cls._model_mappings is None:
try:
# Create a temporary authenticator to fetch models
authenticator = GitHubCopilotAuthenticator()
models_data = _fetch_models_data(authenticator) # Use helper
mappings = {"github_copilot": cls.DEFAULT_MODEL_MAPPING}
# Process models from response - models are in the "data" field
for model in models_data.get("data", []):
model_id = model.get("id")
if model_id:
# Add all models, including the default one
mappings[f"github_copilot/{model_id}"] = model_id
cls._model_mappings = mappings
except Exception as e:
# Error logged by _fetch_models_data
# Fallback to basic mappings
cls._model_mappings = {
"github_copilot": cls.DEFAULT_MODEL_MAPPING,
}
return cls._model_mappings
@classmethod
def get_streaming_models(cls) -> list[str]:
"""
Get the list of models that support streaming responses.
This method retrieves information about which models support streaming responses
from the GitHub Copilot API. It caches the results to avoid unnecessary API calls.
Returns:
list[str]: A list of API model names that support streaming
Note:
If fetching the streaming models fails, it will assume all models
support streaming as a fallback.
"""
if cls._streaming_models is None:
try:
# Create a temporary authenticator to fetch models
authenticator = GitHubCopilotAuthenticator()
models_data = _fetch_models_data(authenticator) # Use helper
streaming_models = []
# Process models from response - models are in the "data" field
for model in models_data.get("data", []):
model_id = model.get("id")
# Check if model supports streaming
capabilities = model.get("capabilities", {})
supports = capabilities.get("supports", {})
if supports.get("streaming", False) and model_id:
streaming_models.append(model_id)
# Always include default model mapping value
if cls.DEFAULT_MODEL_MAPPING not in streaming_models:
streaming_models.append(cls.DEFAULT_MODEL_MAPPING)
cls._streaming_models = streaming_models
except Exception as e:
# Error logged by _fetch_models_data
print(f"Failed to process streaming models data: {str(e)}")
# Fallback to assuming all models support streaming
mappings = cls.get_model_mappings()
cls._streaming_models = list(mappings.values())
return cls._streaming_models
def _get_model_for_api(self, model: str) -> str:
"""
Convert model name to API-compatible format.
Args:
model: The model identifier (e.g., "github_copilot/o1")
Returns:
The API model name (e.g., "o1")
"""
# Get model mappings
mappings = self.get_model_mappings()
# Strip provider prefix if present
if "/" in model:
_, model_name = model.split("/", 1)
if model_name in mappings.values():
return model_name
# Use the mapping or default to gpt-4o
return mappings.get(model, self.DEFAULT_MODEL_MAPPING)
def _non_streaming_request(
self,
prompt: llm.Prompt,
headers: dict[str, str],
payload: dict[str, Any],
model_name: str,
) -> Generator[str, None, None]:
"""
Handle a non-streaming request to the GitHub Copilot API.
This method sends a non-streaming request to the GitHub Copilot API
and processes the response. It handles various response formats and
error conditions.
Args:
prompt: The LLM prompt object
headers: HTTP headers for the request
payload: The request payload (will have stream=False set)
model_name: The API model name to use
Yields:
str: The generated text from the API response
Note:
In case of errors, this method yields an error message instead of raising
an exception to maintain compatibility with the streaming interface.
"""
try:
# Ensure stream is set to false
payload["stream"] = False
api_response = httpx.post(
f"{self.API_BASE}/chat/completions",
headers=headers,
json=payload,
timeout=self.NON_STREAMING_TIMEOUT,
)
api_response.raise_for_status()
# Try to parse JSON
try:
json_data = api_response.json()
if "choices" in json_data and json_data["choices"]:
choice = json_data["choices"][0]
# Handle different response formats
if "message" in choice and choice["message"]:
content = choice["message"].get("content", "")
if content:
yield content
return
elif "text" in choice:
content = choice.get("text", "")
if content:
yield content
return
elif "content" in choice:
content = choice.get("content", "")
if content:
yield content
return
# If we couldn't extract content through known paths, try to find it elsewhere
if "content" in json_data:
yield json_data["content"]
return
except json.JSONDecodeError as e:
print(f"JSON decode error: {str(e)}")
# If JSON parsing fails or no content found, return raw text
yield api_response.text
except httpx.HTTPStatusError as e:
# Ensure the response body is read before accessing .text
e.response.read()
error_body_text = e.response.text
error_text = f"HTTP error {e.response.status_code}: {error_body_text}"
print(error_text)
yield error_text
except httpx.RequestError as e:
error_text = f"Request error: {str(e)}"
print(error_text)
yield error_text
except Exception as e:
error_text = f"Error with request: {str(e)}"
print(error_text)
yield error_text
def execute(
self,
prompt: llm.Prompt,
stream: bool,
response: llm.Response,
conversation: Optional[llm.Conversation],
) -> Generator[str, None, None]:
"""
Execute a prompt against the GitHub Copilot API.
This is the main method that processes a prompt and returns a response.
It handles authentication, builds the request payload, determines whether
to use streaming or non-streaming mode, and processes the response.
Args:
prompt: The LLM prompt object containing the user's input
stream: Whether to stream the response (if supported by the model)
response: The LLM response object to populate
conversation: Optional conversation history to include in the request
Yields:
str: Chunks of the generated text from the API response
Note:
If authentication fails, this method yields an error message instead
of raising an exception.
"""
# Get API key
try:
api_key = self.authenticator.get_api_key()
except Exception as e:
error_message = str(e)
if "authentication required" in error_message.lower():
yield "GitHub Copilot authentication required. Run 'llm github_copilot auth login' to authenticate."
else:
yield f"Error getting GitHub Copilot API key: {error_message}"
return
# Get model name
model_name = self._get_model_for_api(self.model_id)
# Prepare the request with required headers
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"Accept": "application/json",
"editor-version": "vscode/1.85.1",
"Copilot-Integration-Id": "vscode-chat", # Use a recognized integration ID
}
# Build conversation messages
messages = self._build_conversation_messages(prompt, conversation)
# Get options
max_tokens = prompt.options.max_tokens or 8192
temperature = prompt.options.temperature or 0.1
# Prepare payload
payload = {
"model": model_name,
"messages": messages,
"max_tokens": max_tokens,
"temperature": temperature,
"stream": model_name in self.get_streaming_models(),
}
# Check if model supports streaming
supports_streaming = model_name in self.get_streaming_models()
# Check if model supports streaming
if supports_streaming and stream:
payload["stream"] = True
yield from self._handle_streaming_request(
prompt, headers, payload, model_name
)
else:
# Use non-streaming request for unsupported models or when streaming is disabled
payload["stream"] = False
yield from self._non_streaming_request(prompt, headers, payload, model_name)
def _build_conversation_messages(
self, prompt: llm.Prompt, conversation: Optional[llm.Conversation]
) -> list[dict[str, str]]:
"""
Build the messages array for the API request from the conversation history.
This method constructs the messages array required by the GitHub Copilot API
by extracting previous messages from the conversation history and adding
the current prompt. It also ensures a system message is included.
Args:
prompt: The current LLM prompt object
conversation: Optional conversation history
Returns:
list[dict[str, str]]: A list of message objects in the format required
by the GitHub Copilot API, each with 'role' and 'content'
"""
messages = []
# Extract messages from conversation history
if conversation and conversation.responses:
for prev_response in conversation.responses:
# Add user message
messages.append(
{"role": "user", "content": prev_response.prompt.prompt}
)
# Add assistant message
messages.append({"role": "assistant", "content": prev_response.text()})
# Add the current prompt and system message if needed
if messages:
# Add system message if not present
if not any(msg.get("role") == "system" for msg in messages):
messages.insert(
0,
{
"role": "system",
"content": self.DEFAULT_SYSTEM_MESSAGE,
},
)
# Add the current prompt
messages.append({"role": "user", "content": prompt.prompt})
else:
# First message in conversation
messages = [
{
"role": "system",
"content": self.DEFAULT_SYSTEM_MESSAGE,
},
{"role": "user", "content": prompt.prompt},
]
return messages
def _handle_streaming_request(
self,
prompt: llm.Prompt,
headers: dict[str, str],
payload: dict[str, Any],
model_name: str,
) -> Generator[str, None, None]:
"""
Handle a streaming request to the GitHub Copilot API.
This method sends a streaming request to the GitHub Copilot API and
processes the server-sent events (SSE) response. It parses each event
and extracts the generated text chunks.
Args:
prompt: The LLM prompt object
headers: HTTP headers for the request
payload: The request payload (will have stream=True set)
model_name: The API model name to use
Yields:
str: Chunks of the generated text from the streaming API response
Note:
If streaming fails, this method falls back to a non-streaming request
to ensure the user still gets a response.
"""
try:
with httpx.Client() as client:
with client.stream(
"POST",
f"{self.API_BASE}/chat/completions",
headers=headers,
json=payload,
timeout=self.DEFAULT_TIMEOUT,
) as response:
response.raise_for_status()
for line in response.iter_lines():
if not line:
continue
# Handle both bytes and string types
if isinstance(line, bytes):
line = line.decode("utf-8", errors="replace")
line = line.strip()
if line.startswith("data:"):
data = line[5:].strip()
if data == "[DONE]":
continue
try:
json_data = json.loads(data)
if "choices" in json_data and json_data["choices"]:
choice = json_data["choices"][0]
# Handle different response formats
if "delta" in choice:
content = choice["delta"].get("content", "")
if content:
yield content
elif "text" in choice:
content = choice.get("text", "")
if content:
yield content
elif "message" in choice:
content = choice["message"].get("content", "")
if content:
yield content
except json.JSONDecodeError:
# If not valid JSON, check if it's plain text content
if (
data
and not data.startswith("{")
and not data.startswith("[")
):
yield data
except httpx.HTTPStatusError as e:
# Read the response body before trying to access .text
# This is crucial for streaming responses that error out
e.response.read()
error_body_text = e.response.text
error_msg = f"HTTP error {e.response.status_code}: {error_body_text}"
print(error_msg)
# Print more detailed error information
print(f"Request headers: {headers}")
print(f"Request payload: {json.dumps(payload)}")
# Fall back to non-streaming on error
payload["stream"] = False
yield from self._non_streaming_request(prompt, headers, payload, model_name)
except httpx.RequestError as e:
print(f"Request error: {str(e)}")
# Fall back to non-streaming on error
payload["stream"] = False
yield from self._non_streaming_request(prompt, headers, payload, model_name)
except Exception as e:
print(f"Error with streaming request: {str(e)}")
# Fall back to non-streaming on error
payload["stream"] = False