-
Notifications
You must be signed in to change notification settings - Fork 171
feat: add GitHub Copilot provider support and related configurations #458
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
d0uub
wants to merge
3
commits into
glowingjade:main
Choose a base branch
from
d0uub:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,162 @@ | ||
| window?.localStorage?.removeItem?.('copilot.session'); | ||
| import { requestUrl } from 'obsidian' | ||
| import { ChatModel } from '../../types/chat-model.types' | ||
| import { | ||
| LLMOptions, | ||
| LLMRequestNonStreaming, | ||
| LLMRequestStreaming, | ||
| } from '../../types/llm/request' | ||
| import { | ||
| LLMResponseNonStreaming, | ||
| LLMResponseStreaming, | ||
| } from '../../types/llm/response' | ||
| import { LLMProvider } from '../../types/provider.types' | ||
|
|
||
| import { BaseLLMProvider } from './base' | ||
| import { | ||
| LLMAPIKeyInvalidException, | ||
| LLMAPIKeyNotSetException, | ||
| } from './exception' | ||
|
|
||
| export class CopilotProvider extends BaseLLMProvider<Extract<LLMProvider, { type: 'copilot' }>> { | ||
| private apiKey: string | ||
|
|
||
| constructor(provider: Extract<LLMProvider, { type: 'copilot' }>) { | ||
| super(provider) | ||
| this.apiKey = provider.apiKey ?? '' | ||
| } | ||
|
|
||
| private async getCopilotToken(): Promise<string> { | ||
| const now = Math.floor(Date.now() / 1000); | ||
| const HK_TIMEZONE_OFFSET = 28800; // 8 hours in seconds | ||
| const getSession = () => { | ||
| const raw = window?.localStorage?.getItem?.('copilot.session'); | ||
| return raw ? JSON.parse(raw) : { token: null, exp: null }; | ||
| }; | ||
| const isValid = (token: string | null, exp: number | null) => token && exp && exp > now + HK_TIMEZONE_OFFSET; | ||
| const { token: cachedToken, exp: cachedExp } = getSession(); | ||
| if (isValid(cachedToken, cachedExp)) return cachedToken; | ||
|
|
||
| if (!this.apiKey) throw new LLMAPIKeyNotSetException('Copilot API key (GitHub token) is not set.') | ||
| let headers: Record<string, string> = { | ||
| accept: 'application/json', | ||
| 'content-type': 'application/json', | ||
| authorization: `token ${this.apiKey}`, | ||
| } | ||
| const resp = await requestUrl({url: 'https://api.github.com/copilot_internal/v2/token',method: 'GET',headers,}) | ||
| if (resp.status === 401 || resp.status === 403) throw new LLMAPIKeyInvalidException('Invalid token') | ||
| const data = await resp.json | ||
| const newToken = data.token ?? data.access_token ?? undefined | ||
| const newExp = (data.exp && Number.isFinite(data.exp)) ? data.exp : now + 3600 | ||
| if (!newToken) throw new Error('Failed to obtain Copilot session token from GitHub') | ||
| window?.localStorage?.setItem?.('copilot.session', JSON.stringify({ token: newToken, exp: newExp })) | ||
| return newToken | ||
| } | ||
d0uub marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| private getHeaders(sessionToken: string): Record<string, string> { | ||
| return { | ||
| accept: 'application/json', | ||
| 'editor-version': 'vscode/1.97.2', | ||
| 'editor-plugin-version': 'copilot.vim/1.16.0', | ||
| 'content-type': 'application/json', | ||
| 'user-agent': 'GithubCopilot/1.155.0', | ||
| 'accept-encoding': 'gzip,deflate,br', | ||
| authorization: `Bearer ${sessionToken}`, | ||
| } | ||
| } | ||
|
|
||
| async generateResponse( | ||
| model: ChatModel, | ||
| request: LLMRequestNonStreaming, | ||
| options?: LLMOptions, | ||
| ): Promise<LLMResponseNonStreaming> { | ||
| if (model.providerType !== 'copilot') { | ||
| throw new Error('Model is not a Copilot model') | ||
| } | ||
| let sessionToken = await this.getCopilotToken(); | ||
| const payload: Record<string, unknown> = { | ||
| model: request.model, | ||
| messages: request.messages.map((m) => ({ role: m.role, content: m.content })), | ||
| temperature: request.temperature, | ||
| top_p: request.top_p, | ||
| stream: false, | ||
| }; | ||
| let headers = this.getHeaders(sessionToken); | ||
| headers['copilot-vision-request'] = 'true'; | ||
| let resp = await requestUrl({url: 'https://api.githubcopilot.com/chat/completions',method: 'POST',headers,body: JSON.stringify(payload)}); | ||
| if (resp.status === 401) { | ||
| window?.localStorage?.removeItem?.('copilot.session'); | ||
| sessionToken = await this.getCopilotToken(); | ||
| headers.authorization = `Bearer ${sessionToken}` | ||
| resp = await requestUrl({url: 'https://api.githubcopilot.com/chat/completions',method: 'POST',headers,body: JSON.stringify(payload)}); | ||
| } | ||
| if (resp.status === 401 || resp.status === 403) { | ||
| window?.localStorage?.removeItem?.('copilot.session'); | ||
| throw new Error('Invalid token') | ||
| } | ||
| if (!(resp.status >= 200 && resp.status < 300)) { | ||
| throw new Error(`Copilot API error: HTTP ${resp.status} - ${resp.text}`) | ||
| } | ||
|
|
||
| let data: any; | ||
| try { | ||
| data = JSON.parse(resp.text); | ||
| } catch (e) { | ||
| throw new Error(`Copilot returned non-JSON response (HTTP ${resp.status}): ${resp.text}`); | ||
| } | ||
| const choices = (data.choices ?? data.results ?? []).map((c: any) => ({ | ||
| finish_reason: c.finish_reason ?? null, | ||
| message: { content: c.message?.content ?? c.message ?? c.output ?? null, role: c.message?.role ?? 'assistant' }, | ||
| })); | ||
| return { | ||
| id: data.id ?? '', | ||
| choices, | ||
| created: data.created ?? undefined, | ||
| model: data.model ?? model.model, | ||
| object: 'chat.completion', | ||
| system_fingerprint: data.system_fingerprint, | ||
| usage: data.usage, | ||
| }; | ||
| } | ||
|
|
||
| async streamResponse( | ||
| model: ChatModel, | ||
| request: LLMRequestStreaming, | ||
| options?: LLMOptions, | ||
| ): Promise<AsyncIterable<LLMResponseStreaming>> { | ||
| if (model.providerType !== 'copilot') { | ||
| throw new Error('Model is not a Copilot model'); | ||
| } | ||
| // Convert request to non-streaming | ||
| const nonStreamingRequest: LLMRequestNonStreaming = {...request,stream: false}; | ||
| const response = await this.generateResponse(model, nonStreamingRequest, options); | ||
| async function* streamGenerator(): AsyncIterable<LLMResponseStreaming> { | ||
| for (const choice of response.choices) { | ||
| yield { | ||
| id: response.id ?? '', | ||
| model: response.model ?? model.model, | ||
| choices: [ | ||
| { | ||
| finish_reason: choice.finish_reason ?? null, | ||
| delta: { | ||
| content: choice.message?.content ?? '', | ||
| role: choice.message?.role ?? 'assistant', | ||
| }, | ||
| }, | ||
| ], | ||
| object: 'chat.completion.chunk', | ||
| usage: response.usage, | ||
| } as LLMResponseStreaming; | ||
| } | ||
| } | ||
| return streamGenerator(); | ||
| } | ||
|
|
||
| async getEmbedding(_model: string, _text: string): Promise<number[]> { | ||
| throw new Error( | ||
| `Provider copilot does not support embeddings. Please use a different provider.`, | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| export default CopilotProvider | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.