-
Notifications
You must be signed in to change notification settings - Fork 3
feat: add GitHub Copilot provider with per-user token authentication #137
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
Merged
+559
−0
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
e9bac3b
fix: handle chatcompletions streaming tool calls with no text preambl…
ssncferreira 734ddda
chore: add newlines at fixture files
ssncferreira 61ea53a
fix: initiate SSE stream synchronously to prevent race condition and …
ssncferreira 8e62b06
chore: address comments
ssncferreira 84c49e6
feat: add GitHub Copilot provider with per-user token authentication
ssncferreira 8fec1c2
chore: address comments
ssncferreira ecd5e50
chore: address comments
ssncferreira d195932
Merge branch 'main' into ssncferreira/feat-copilot-provider
ssncferreira 2ef6458
chore: fix fmt
ssncferreira 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
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,192 @@ | ||
| package provider | ||
|
|
||
| import ( | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
| "net/http" | ||
| "os" | ||
| "strings" | ||
|
|
||
| "github.com/coder/aibridge/config" | ||
| "github.com/coder/aibridge/intercept" | ||
| "github.com/coder/aibridge/intercept/chatcompletions" | ||
| "github.com/coder/aibridge/intercept/responses" | ||
| "github.com/coder/aibridge/tracing" | ||
| "github.com/google/uuid" | ||
| "go.opentelemetry.io/otel/codes" | ||
| "go.opentelemetry.io/otel/trace" | ||
| ) | ||
|
|
||
| const ( | ||
| copilotBaseURL = "https://api.individual.githubcopilot.com" | ||
|
|
||
| // Copilot exposes an OpenAI-compatible API, including for Anthropic models. | ||
| routeCopilotChatCompletions = "/copilot/chat/completions" | ||
| routeCopilotResponses = "/copilot/responses" | ||
dannykopping marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ) | ||
|
|
||
| var copilotOpenErrorResponse = func() []byte { | ||
| return []byte(`{"error":{"message":"circuit breaker is open","type":"server_error","code":"service_unavailable"}}`) | ||
| } | ||
|
|
||
| // Headers that need to be forwarded to Copilot API. | ||
| // These were determined through manual testing as there is no reference | ||
| // of the headers in the official documentation. | ||
| // LiteLLM uses the same headers: | ||
| // https://docs.litellm.ai/docs/providers/github_copilot | ||
| var copilotForwardHeaders = []string{ | ||
| "Editor-Version", | ||
| "Copilot-Integration-Id", | ||
| } | ||
|
|
||
| // Copilot implements the Provider interface for GitHub Copilot. | ||
| // Unlike other providers, Copilot uses per-user API keys that are passed through | ||
| // the request headers rather than configured statically. | ||
| type Copilot struct { | ||
| cfg config.Copilot | ||
| circuitBreaker *config.CircuitBreaker | ||
| } | ||
|
|
||
| var _ Provider = &Copilot{} | ||
|
|
||
| func NewCopilot(cfg config.Copilot) *Copilot { | ||
| if cfg.BaseURL == "" { | ||
| cfg.BaseURL = copilotBaseURL | ||
| } | ||
| if cfg.APIDumpDir == "" { | ||
| cfg.APIDumpDir = os.Getenv("BRIDGE_DUMP_DIR") | ||
| } | ||
| if cfg.CircuitBreaker != nil { | ||
| cfg.CircuitBreaker.OpenErrorResponse = copilotOpenErrorResponse | ||
| } | ||
| return &Copilot{ | ||
| cfg: cfg, | ||
| circuitBreaker: cfg.CircuitBreaker, | ||
| } | ||
| } | ||
|
|
||
| func (p *Copilot) Name() string { | ||
| return config.ProviderCopilot | ||
| } | ||
|
|
||
| func (p *Copilot) BaseURL() string { | ||
| return p.cfg.BaseURL | ||
| } | ||
|
|
||
| func (p *Copilot) BridgedRoutes() []string { | ||
| return []string{ | ||
| routeCopilotChatCompletions, | ||
| routeCopilotResponses, | ||
| } | ||
| } | ||
|
|
||
| func (p *Copilot) PassthroughRoutes() []string { | ||
| return []string{ | ||
| "/models", | ||
| "/models/", | ||
| "/agents/", | ||
| "/mcp/", | ||
| } | ||
| } | ||
|
|
||
| func (p *Copilot) AuthHeader() string { | ||
| return "Authorization" | ||
| } | ||
|
|
||
| // InjectAuthHeader is a no-op for Copilot. | ||
| // Copilot uses per-user tokens passed in the original Authorization header, | ||
| // rather than a global key configured at the provider level. | ||
| // The original Authorization header flows through untouched from the client. | ||
| func (p *Copilot) InjectAuthHeader(_ *http.Header) {} | ||
|
|
||
| func (p *Copilot) CircuitBreakerConfig() *config.CircuitBreaker { | ||
| return p.circuitBreaker | ||
| } | ||
|
|
||
| func (p *Copilot) CreateInterceptor(_ http.ResponseWriter, r *http.Request, tracer trace.Tracer) (_ intercept.Interceptor, outErr error) { | ||
| _, span := tracer.Start(r.Context(), "Intercept.CreateInterceptor") | ||
| defer tracing.EndSpanErr(span, &outErr) | ||
|
|
||
| // Extract the per-user Copilot key from the Authorization header. | ||
| key := extractBearerToken(r.Header.Get("Authorization")) | ||
| if key == "" { | ||
| span.SetStatus(codes.Error, "missing authorization") | ||
| return nil, fmt.Errorf("missing Copilot authorization: Authorization header not found or invalid") | ||
| } | ||
|
|
||
| id := uuid.New() | ||
|
|
||
| // Build config for the interceptor using the per-request key. | ||
| // Copilot's API is OpenAI-compatible, so it uses the OpenAI interceptors | ||
| // that require a config.OpenAI. | ||
| cfg := config.OpenAI{ | ||
| BaseURL: p.cfg.BaseURL, | ||
| Key: key, | ||
| APIDumpDir: p.cfg.APIDumpDir, | ||
| CircuitBreaker: p.cfg.CircuitBreaker, | ||
| ExtraHeaders: extractCopilotHeaders(r), | ||
| } | ||
|
|
||
| var interceptor intercept.Interceptor | ||
|
|
||
| switch r.URL.Path { | ||
| case routeCopilotChatCompletions: | ||
| var req chatcompletions.ChatCompletionNewParamsWrapper | ||
| if err := json.NewDecoder(r.Body).Decode(&req); err != nil { | ||
| return nil, fmt.Errorf("unmarshal chat completions request body: %w", err) | ||
| } | ||
|
|
||
| if req.Stream { | ||
| interceptor = chatcompletions.NewStreamingInterceptor(id, &req, cfg, tracer) | ||
| } else { | ||
| interceptor = chatcompletions.NewBlockingInterceptor(id, &req, cfg, tracer) | ||
| } | ||
|
|
||
| case routeCopilotResponses: | ||
| payload, err := io.ReadAll(r.Body) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("read body: %w", err) | ||
| } | ||
| var req responses.ResponsesNewParamsWrapper | ||
| if err := json.Unmarshal(payload, &req); err != nil { | ||
| return nil, fmt.Errorf("unmarshal responses request body: %w", err) | ||
| } | ||
|
|
||
| if req.Stream { | ||
| interceptor = responses.NewStreamingInterceptor(id, &req, payload, cfg, req.Model, tracer) | ||
| } else { | ||
| interceptor = responses.NewBlockingInterceptor(id, &req, payload, cfg, req.Model, tracer) | ||
| } | ||
|
|
||
| default: | ||
| span.SetStatus(codes.Error, "unknown route: "+r.URL.Path) | ||
| return nil, UnknownRoute | ||
| } | ||
|
|
||
| span.SetAttributes(interceptor.TraceAttributes(r)...) | ||
| return interceptor, nil | ||
| } | ||
|
|
||
| // extractBearerToken extracts the token from a "Bearer <token>" authorization header. | ||
| func extractBearerToken(auth string) string { | ||
| if auth := strings.TrimSpace(auth); auth != "" { | ||
| fields := strings.Fields(auth) | ||
| if len(fields) == 2 && strings.EqualFold(fields[0], "Bearer") { | ||
| return fields[1] | ||
| } | ||
| } | ||
| return "" | ||
| } | ||
|
|
||
| // extractCopilotHeaders extracts headers required by the Copilot API from the | ||
| // incoming request. Copilot requires certain client headers to be forwarded. | ||
| func extractCopilotHeaders(r *http.Request) map[string]string { | ||
| headers := make(map[string]string, len(copilotForwardHeaders)) | ||
| for _, h := range copilotForwardHeaders { | ||
| if v := r.Header.Get(h); v != "" { | ||
| headers[h] = v | ||
| } | ||
| } | ||
| return headers | ||
| } | ||
Oops, something went wrong.
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.