From 5b5db951ff4c2ac84d0129609aac10226a5a3c8d Mon Sep 17 00:00:00 2001 From: G-XD Date: Sat, 13 Jun 2026 20:05:06 +0800 Subject: [PATCH 1/6] fix: load-test script build paths and provider config (#4358) * fix: load-test script build paths and provider config * fix: ensure ui placeholder exists even when ui dir is empty Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> Signed-off-by: G-XD --------- Signed-off-by: G-XD Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --- .github/workflows/scripts/load-test.sh | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/.github/workflows/scripts/load-test.sh b/.github/workflows/scripts/load-test.sh index 541bb82b05c..4d4a8caff62 100755 --- a/.github/workflows/scripts/load-test.sh +++ b/.github/workflows/scripts/load-test.sh @@ -169,7 +169,13 @@ build_bifrost_http() { fi log_info "Building bifrost-http..." - cd "${TRANSPORTS_DIR}" + cd "${BIFROST_HTTP_DIR}" + + # Ensure ui directory exists for //go:embed all:ui (load test does not need the real UI assets) + mkdir -p "${BIFROST_HTTP_DIR}/ui" + if [ ! -f "${BIFROST_HTTP_DIR}/ui/.gitkeep" ]; then + echo "placeholder" > "${BIFROST_HTTP_DIR}/ui/.gitkeep" + fi if go build -o ${REPO_ROOT}/tmp/bifrost-http .; then log_success "bifrost-http built successfully" @@ -190,8 +196,9 @@ setup_mocker() { cd "${WORK_DIR}" else log_info "Cloning bifrost-benchmarking repository..." - cd "${WORK_DIR}" + cd "${REPO_ROOT}/.." git clone --depth 1 https://github.com/maximhq/bifrost-benchmarking.git + cd "${WORK_DIR}" fi log_success "Mocker setup complete" @@ -242,7 +249,8 @@ create_config() { { "name": "mocker-key", "value": "Bearer mocker-key", - "weight": 1 + "weight": 1, + "models": ["*"] } ], "network_config": { @@ -252,14 +260,6 @@ create_config() { "concurrency_and_buffer_size": { "concurrency": 20000, "buffer_size": 40000 - }, - "custom_provider_config": { - "base_provider_type": "openai", - "allowed_requests": { - "list_models": false, - "chat_completion": true, - "chat_completion_stream": true - } } } } @@ -848,3 +848,4 @@ main() { } main "$@" + From e98c49133c391d48b93e2e9a782e1442877d1b29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Webagil=20-=20K=C3=A9vin=20PAULMIER?= <9626689+webagil-kevin@users.noreply.github.com> Date: Sat, 13 Jun 2026 15:00:20 +0200 Subject: [PATCH 2/6] fix(compat): preserve max_output_tokens on Responses requests (#4362) compat.should_drop_params dropped max_output_tokens from /v1/responses because the chat-named model-parameter catalog lists max_tokens, not max_output_tokens. Keep it when the chat token cap is supported, mirroring the existing max_completion_tokens rule. Adds the first unit tests for the compat plugin. Fixes #4354 Co-authored-by: Akshay Deo --- plugins/compat/dropparams.go | 7 +- plugins/compat/dropparams_test.go | 172 ++++++++++++++++++++++++++++++ 2 files changed, 178 insertions(+), 1 deletion(-) create mode 100644 plugins/compat/dropparams_test.go diff --git a/plugins/compat/dropparams.go b/plugins/compat/dropparams.go index c87f7aa034d..7c18e69ff72 100644 --- a/plugins/compat/dropparams.go +++ b/plugins/compat/dropparams.go @@ -128,7 +128,12 @@ func dropUnsupportedParams(ctx *schemas.BifrostContext, req *schemas.BifrostRequ if req.ResponsesRequest != nil && req.ResponsesRequest.Params != nil { params := req.ResponsesRequest.Params - if params.MaxOutputTokens != nil && !isSupported["max_output_tokens"] { + // max_output_tokens is the Responses-API equivalent of chat max_tokens / max_completion_tokens. + // so if any of those token-cap spellings is supported, we let max_output_tokens pass through. + if params.MaxOutputTokens != nil && + !isSupported["max_output_tokens"] && + !isSupported["max_tokens"] && + !isSupported["max_completion_tokens"] { params.MaxOutputTokens = nil dropped = append(dropped, "max_output_tokens") } diff --git a/plugins/compat/dropparams_test.go b/plugins/compat/dropparams_test.go new file mode 100644 index 00000000000..748d1556e6f --- /dev/null +++ b/plugins/compat/dropparams_test.go @@ -0,0 +1,172 @@ +package compat + +import ( + "context" + "slices" + "testing" + "time" + + "github.com/maximhq/bifrost/core/schemas" +) + +func newTestContext() *schemas.BifrostContext { + return schemas.NewBifrostContext(context.Background(), time.Time{}) +} + +func newResponsesRequest(provider schemas.ModelProvider, model string, params *schemas.ResponsesParameters) *schemas.BifrostRequest { + return &schemas.BifrostRequest{ + RequestType: schemas.ResponsesRequest, + ResponsesRequest: &schemas.BifrostResponsesRequest{Provider: provider, Model: model, Params: params}, + } +} + +// TestDropUnsupportedParams_MaxOutputTokens verifies that the Responses-API +// max_output_tokens cap is preserved whenever the (chat-named) model parameter +// catalog authorizes the token cap under any spelling +// (max_output_tokens / max_tokens / max_completion_tokens), and dropped only +// when none of them is supported. +func TestDropUnsupportedParams_MaxOutputTokens(t *testing.T) { + tests := []struct { + name string + provider schemas.ModelProvider + model string + supported []string + wantPreserved bool + }{ + { + name: "openai gpt-4o-mini lists chat max_tokens only", + provider: schemas.OpenAI, + model: "gpt-4o-mini", + supported: []string{"temperature", "top_p", "max_tokens", "stop", "tools"}, + wantPreserved: true, + }, + { + name: "openai o4-mini lists max_completion_tokens", + provider: schemas.OpenAI, + model: "o4-mini", + supported: []string{"temperature", "max_completion_tokens"}, + wantPreserved: true, + }, + { + name: "model lists max_output_tokens explicitly", + provider: schemas.OpenAI, + model: "gpt-oss-120b", + supported: []string{"temperature", "max_output_tokens"}, + wantPreserved: true, + }, + { + name: "anthropic claude lists max_tokens", + provider: schemas.Anthropic, + model: "claude-sonnet-4", + supported: []string{"temperature", "max_tokens", "top_p"}, + wantPreserved: true, + }, + { + name: "vertex gemini lists max_tokens", + provider: schemas.Vertex, + model: "gemini-2.5-pro", + supported: []string{"temperature", "max_tokens"}, + wantPreserved: true, + }, + { + name: "no token cap supported drops max_output_tokens", + provider: schemas.OpenAI, + model: "no-token-cap-model", + supported: []string{"temperature", "top_p"}, + wantPreserved: false, + }, + { + name: "unknown model with empty catalog drops max_output_tokens", + provider: schemas.OpenAI, + model: "unknown-model", + supported: []string{}, + wantPreserved: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req := newResponsesRequest(tt.provider, tt.model, &schemas.ResponsesParameters{ + MaxOutputTokens: schemas.Ptr(16), + Temperature: schemas.Ptr(0.5), + }) + + dropped := dropUnsupportedParams(newTestContext(), req, tt.supported) + got := req.ResponsesRequest.Params.MaxOutputTokens + + if tt.wantPreserved { + if got == nil { + t.Fatalf("max_output_tokens = dropped, want preserved (supported=%v)", tt.supported) + } + if *got != 16 { + t.Errorf("max_output_tokens = %d, want 16", *got) + } + if slices.Contains(dropped, "max_output_tokens") { + t.Errorf("max_output_tokens reported in dropped=%v, want absent", dropped) + } + return + } + + if got != nil { + t.Fatalf("max_output_tokens = %d, want dropped (supported=%v)", *got, tt.supported) + } + if !slices.Contains(dropped, "max_output_tokens") { + t.Errorf("max_output_tokens not reported in dropped=%v, want present", dropped) + } + }) + } +} + +// TestDropUnsupportedParams_MaxOutputTokensSurgical verifies the fix is +// surgical: within one Responses request, max_output_tokens is preserved (chat +// token cap supported) while an unsupported sibling (top_p) is still dropped. +func TestDropUnsupportedParams_MaxOutputTokensSurgical(t *testing.T) { + req := newResponsesRequest(schemas.OpenAI, "gpt-4o-mini", &schemas.ResponsesParameters{ + MaxOutputTokens: schemas.Ptr(16), + TopP: schemas.Ptr(0.9), + Temperature: schemas.Ptr(0.5), + }) + + dropped := dropUnsupportedParams(newTestContext(), req, []string{"max_tokens", "temperature"}) + + p := req.ResponsesRequest.Params + if p.MaxOutputTokens == nil { + t.Errorf("max_output_tokens = dropped, want preserved") + } + if p.TopP != nil { + t.Errorf("top_p = preserved, want dropped") + } + if p.Temperature == nil { + t.Errorf("temperature = dropped, want preserved") + } + if !slices.Contains(dropped, "top_p") { + t.Errorf("top_p not reported in dropped=%v, want present", dropped) + } +} + +// TestDropUnsupportedParams_ChatMaxCompletionTokensUnchanged guards the +// pre-existing chat-branch behaviour that the Responses fix mirrors. +func TestDropUnsupportedParams_ChatMaxCompletionTokensUnchanged(t *testing.T) { + newChat := func() *schemas.BifrostRequest { + return &schemas.BifrostRequest{ + RequestType: schemas.ChatCompletionRequest, + ChatRequest: &schemas.BifrostChatRequest{ + Provider: schemas.OpenAI, + Model: "gpt-4o-mini", + Params: &schemas.ChatParameters{MaxCompletionTokens: schemas.Ptr(16)}, + }, + } + } + + keep := newChat() + dropUnsupportedParams(newTestContext(), keep, []string{"max_tokens"}) + if keep.ChatRequest.Params.MaxCompletionTokens == nil { + t.Errorf("max_completion_tokens = dropped, want preserved (max_tokens supported)") + } + + drop := newChat() + dropUnsupportedParams(newTestContext(), drop, []string{"temperature"}) + if drop.ChatRequest.Params.MaxCompletionTokens != nil { + t.Errorf("max_completion_tokens = preserved, want dropped (no token cap supported)") + } +} From a35a4c87870c8525a978272a9828e8c153854aa6 Mon Sep 17 00:00:00 2001 From: Pratham Mishra <99235987+Pratham-Mishra04@users.noreply.github.com> Date: Sat, 13 Jun 2026 19:40:39 +0530 Subject: [PATCH 3/6] fix: commit routing-pinned key ID to reserved `BifrostContextKeyAPIKeyID` after `PreRequestHook` unblock (#4359) ## Summary Routing rules that pin a specific API key by ID were silently broken. During `PreRequestHook` execution, core blocks writes to reserved context keys (including `BifrostContextKeyAPIKeyID`) to prevent plugins from overriding caller-supplied values. The governance plugin was writing the routing-rule key pin directly to that reserved key, so the write was dropped and the pin never took effect. ## Changes - Introduced a new non-reserved context key `BifrostContextKeyRoutingPinnedAPIKeyID` that the governance plugin writes its routing-rule key pin to during the blocked `PreRequestHook` phase. - After all `PreRequestHook`s complete and the restricted-write block is lifted, core's `RunPreRequestHooks` commits the routing pin from `BifrostContextKeyRoutingPinnedAPIKeyID` into the reserved `BifrostContextKeyAPIKeyID`. A non-empty routing pin overrides any caller-supplied pin, since the routing rule represents authoritative server-side policy. - The `defer ctx.UnblockRestrictedWrites()` was replaced with an explicit call after the plugin loop, so the commit step runs after the block is lifted rather than after the function returns. - Updated the governance plugin's `applyRoutingRules` to write to the new non-reserved key instead of the reserved one. - Updated tests in both `core/bifrost_test.go` and `plugins/governance/routing_test.go` to exercise the real propagation path, including the restricted-write block and plugin scope, and to assert the pin lands on the correct context key. ## Type of change - [x] Bug fix ## Affected areas - [x] Core (Go) - [x] Plugins ## How to test ```sh go test ./core/... ./plugins/governance/... ``` The new `TestRunPreRequestHooks_CommitsRoutingPinnedKey` test covers three cases: 1. A routing pin is committed to the reserved `BifrostContextKeyAPIKeyID`. 2. A routing pin overrides a caller-supplied `BifrostContextKeyAPIKeyID`. 3. A caller-supplied `BifrostContextKeyAPIKeyID` is preserved when no routing pin is set. The updated `TestEvaluateRoutingRules_MultiTargetDeterministicWithPinnedKey` test exercises the full propagation path through `applyRoutingRules` under the same restricted-write block that production uses. ## Breaking changes - [ ] Yes - [x] No ## Security considerations The routing pin is written to a dedicated non-reserved key and committed to the reserved key exclusively by core after the plugin phase completes. This preserves the invariant that only core is the authoritative writer of `BifrostContextKeyAPIKeyID`, preventing plugins from directly overriding key selection outside of the sanctioned routing-rule mechanism. ## Checklist - [ ] I read `docs/contributing/README.md` and followed the guidelines - [x] I added/updated tests where appropriate - [ ] I updated documentation where needed - [x] I verified builds succeed (Go and UI) - [ ] I verified the CI pipeline passes locally if applicable ## Summary by CodeRabbit ## Release Notes * **New Features** * Routing plugins can now pin specific API keys that take precedence over caller-supplied selections through dedicated routing-pinned key handling in the pre-request hook phase. * **Tests** * Added tests to verify routing-pinned API key commitment, precedence handling, and proper context propagation through key selection logic. --- core/bifrost.go | 15 ++++++- core/bifrost_test.go | 70 ++++++++++++++++++++++++++++++ core/schemas/bifrost.go | 11 ++--- plugins/governance/main.go | 8 +++- plugins/governance/routing_test.go | 38 +++++++++++++--- 5 files changed, 127 insertions(+), 15 deletions(-) diff --git a/core/bifrost.go b/core/bifrost.go index 2c53f83d7fa..3d88c7b427c 100644 --- a/core/bifrost.go +++ b/core/bifrost.go @@ -6852,7 +6852,6 @@ func (p *PluginPipeline) RunPreRequestHooks(ctx *schemas.BifrostContext, req *sc return } ctx.BlockRestrictedWrites() - defer ctx.UnblockRestrictedWrites() for _, plugin := range p.llmPlugins { pluginName := plugin.GetName() p.logger.Debug("running pre-request hook for plugin %s", pluginName) @@ -6876,6 +6875,20 @@ func (p *PluginPipeline) RunPreRequestHooks(ctx *schemas.BifrostContext, req *sc } p.tracer.EndSpan(handle, schemas.SpanStatusOk, "") } + ctx.UnblockRestrictedWrites() + + // Commit the routing-rule key pin. A matched routing rule writes the pinned key ID to the + // non-reserved BifrostContextKeyRoutingPinnedAPIKeyID during the blocked phase above — a + // direct write to the reserved BifrostContextKeyAPIKeyID would have been silently dropped. + // Core is the sole writer of the reserved key, so normalize the routing pin into it here, + // after unblocking, so key selection reads a single canonical pin. A non-empty routing pin + // overrides a caller-supplied pin: the routing rule is authoritative server-side policy and + // has typically already rewritten provider/model for this request. + if pin, ok := ctx.Value(schemas.BifrostContextKeyRoutingPinnedAPIKeyID).(string); ok { + if pin = strings.TrimSpace(pin); pin != "" { + ctx.SetValue(schemas.BifrostContextKeyAPIKeyID, pin) + } + } } // RunPostLLMHooks executes PostHooks in reverse order for the plugins whose PreLLMHook ran. diff --git a/core/bifrost_test.go b/core/bifrost_test.go index 5023684c7d0..e7d53c21754 100644 --- a/core/bifrost_test.go +++ b/core/bifrost_test.go @@ -2756,3 +2756,73 @@ func TestFilterKeysByID(t *testing.T) { } }) } + +// fakeRoutingPlugin is a minimal LLMPlugin whose PreRequestHook writes a routing key pin to the +// non-reserved BifrostContextKeyRoutingPinnedAPIKeyID, mirroring what the governance routing +// engine does. It exists to exercise the commit step in PluginPipeline.RunPreRequestHooks. +type fakeRoutingPlugin struct { + name string + pinKeyID string // written to BifrostContextKeyRoutingPinnedAPIKeyID when non-empty +} + +func (f *fakeRoutingPlugin) GetName() string { return f.name } +func (f *fakeRoutingPlugin) Cleanup() error { return nil } +func (f *fakeRoutingPlugin) PreRequestHook(ctx *schemas.BifrostContext, req *schemas.BifrostRequest) error { + if f.pinKeyID != "" { + // A direct write to the reserved BifrostContextKeyAPIKeyID here would be dropped by the + // restricted-write block; routing must use the non-reserved key. + ctx.SetValue(schemas.BifrostContextKeyRoutingPinnedAPIKeyID, f.pinKeyID) + } + return nil +} +func (f *fakeRoutingPlugin) PreLLMHook(ctx *schemas.BifrostContext, req *schemas.BifrostRequest) (*schemas.BifrostRequest, *schemas.LLMPluginShortCircuit, error) { + return req, nil, nil +} +func (f *fakeRoutingPlugin) PostLLMHook(ctx *schemas.BifrostContext, resp *schemas.BifrostResponse, bifrostErr *schemas.BifrostError) (*schemas.BifrostResponse, *schemas.BifrostError, error) { + return resp, bifrostErr, nil +} + +func newRoutingCommitPipeline(plugins ...schemas.LLMPlugin) *PluginPipeline { + return &PluginPipeline{ + logger: NewDefaultLogger(schemas.LogLevelError), + tracer: &schemas.NoOpTracer{}, + llmPlugins: plugins, + } +} + +// TestRunPreRequestHooks_CommitsRoutingPinnedKey verifies that the pinned key a routing rule +// writes to the non-reserved BifrostContextKeyRoutingPinnedAPIKeyID (during the blocked +// PreRequestHook phase) is committed by core into the reserved BifrostContextKeyAPIKeyID that +// key selection reads — and that the routing pin's precedence over a caller-supplied pin holds. +func TestRunPreRequestHooks_CommitsRoutingPinnedKey(t *testing.T) { + const pinned = "routing-pinned-key-id" + + t.Run("routing pin is committed to reserved api-key-id", func(t *testing.T) { + p := newRoutingCommitPipeline(&fakeRoutingPlugin{name: "gov", pinKeyID: pinned}) + ctx := schemas.NewBifrostContext(context.Background(), time.Now()) + p.RunPreRequestHooks(ctx, &schemas.BifrostRequest{}) + if got, _ := ctx.Value(schemas.BifrostContextKeyAPIKeyID).(string); got != pinned { + t.Fatalf("APIKeyID = %q, want %q", got, pinned) + } + }) + + t.Run("routing pin overrides a caller-supplied api-key-id", func(t *testing.T) { + p := newRoutingCommitPipeline(&fakeRoutingPlugin{name: "gov", pinKeyID: pinned}) + ctx := schemas.NewBifrostContext(context.Background(), time.Now()) + ctx.SetValue(schemas.BifrostContextKeyAPIKeyID, "caller-pin") + p.RunPreRequestHooks(ctx, &schemas.BifrostRequest{}) + if got, _ := ctx.Value(schemas.BifrostContextKeyAPIKeyID).(string); got != pinned { + t.Fatalf("APIKeyID = %q, want %q (routing pin must override caller pin)", got, pinned) + } + }) + + t.Run("caller api-key-id preserved when no routing pin", func(t *testing.T) { + p := newRoutingCommitPipeline(&fakeRoutingPlugin{name: "noop"}) + ctx := schemas.NewBifrostContext(context.Background(), time.Now()) + ctx.SetValue(schemas.BifrostContextKeyAPIKeyID, "caller-pin") + p.RunPreRequestHooks(ctx, &schemas.BifrostRequest{}) + if got, _ := ctx.Value(schemas.BifrostContextKeyAPIKeyID).(string); got != "caller-pin" { + t.Fatalf("APIKeyID = %q, want %q (no routing pin must not clobber caller pin)", got, "caller-pin") + } + }) +} diff --git a/core/schemas/bifrost.go b/core/schemas/bifrost.go index 57f64891d25..b206b52da6d 100644 --- a/core/schemas/bifrost.go +++ b/core/schemas/bifrost.go @@ -222,6 +222,7 @@ const ( BifrostContextKeyGovernanceCustomerNames BifrostContextKey = "bifrost-governance-customer-names" // []string (display names, aligned with customer-ids; set by enterprise governance plugin - DO NOT SET THIS MANUALLY) BifrostContextKeyGovernanceRoutingRuleID BifrostContextKey = "bifrost-governance-routing-rule-id" // string (to store the routing rule ID (set by bifrost governance plugin - DO NOT SET THIS MANUALLY)) BifrostContextKeyGovernanceRoutingRuleName BifrostContextKey = "bifrost-governance-routing-rule-name" // string (to store the routing rule name (set by bifrost governance plugin - DO NOT SET THIS MANUALLY)) + BifrostContextKeyRoutingPinnedAPIKeyID BifrostContextKey = "bifrost-routing-pinned-api-key-id" // string (provider key ID pinned by a matched routing rule target; resolved against the configured key pool during key selection and takes precedence over a caller-supplied pin (set by bifrost governance plugin - DO NOT SET THIS MANUALLY)) BifrostContextKeySelectedPromptName BifrostContextKey = "bifrost-selected-prompt-name" // string (display name of the selected prompt (set by prompts plugin - DO NOT SET THIS MANUALLY)) BifrostContextKeySelectedPromptVersion BifrostContextKey = "bifrost-selected-prompt-version" // string (numeric version as string, e.g. "3" (set by prompts plugin - DO NOT SET THIS MANUALLY)) BifrostContextKeySelectedPromptID BifrostContextKey = "bifrost-selected-prompt-id" // string (id of the selected prompt (set by prompts plugin - DO NOT SET THIS MANUALLY)) @@ -1555,8 +1556,8 @@ func (r *BifrostMCPResponse) PopulateExtraFields(mcpRequestType MCPRequestType, // BifrostResponseExtraFields contains additional fields in a response. type BifrostResponseExtraFields struct { - RequestType RequestType `json:"request_type"` - RoutingInfo RoutingInfo `json:"routing_info"` + RequestType RequestType `json:"request_type"` + RoutingInfo RoutingInfo `json:"routing_info"` // Deprecated: use RoutingInfo.Provider. Still populated for backward // compatibility; new consumers should read from RoutingInfo. Provider ModelProvider `json:"provider,omitempty"` @@ -1569,9 +1570,9 @@ type BifrostResponseExtraFields struct { // matched (i.e. RoutingInfo.ResolvedKeyAlias != nil), otherwise // RoutingInfo.Model. Still populated for backward compatibility; new // consumers should read from RoutingInfo. - ResolvedModelUsed string `json:"resolved_model_used,omitempty"` - Latency int64 `json:"latency"` // in milliseconds (for streaming responses this will be each chunk latency, and the last chunk latency will be the total latency) - ChunkIndex int `json:"chunk_index"` // used for streaming responses to identify the chunk index, will be 0 for non-streaming responses + ResolvedModelUsed string `json:"resolved_model_used,omitempty"` + Latency int64 `json:"latency"` // in milliseconds (for streaming responses this will be each chunk latency, and the last chunk latency will be the total latency) + ChunkIndex int `json:"chunk_index"` // used for streaming responses to identify the chunk index, will be 0 for non-streaming responses RawRequest interface{} `json:"raw_request,omitempty"` RawResponse interface{} `json:"raw_response,omitempty"` CacheDebug *BifrostCacheDebug `json:"cache_debug,omitempty"` diff --git a/plugins/governance/main.go b/plugins/governance/main.go index c30a8a31858..ba0fbf9375b 100644 --- a/plugins/governance/main.go +++ b/plugins/governance/main.go @@ -774,9 +774,13 @@ func (p *GovernancePlugin) applyRoutingRules(ctx *schemas.BifrostContext, req *s req.SetFallbacks(resolvedFallbacks) } - // Pin specific API key by ID if the routing rule specifies one + // Pin specific API key by ID if the routing rule specifies one. This uses a dedicated, + // non-reserved context key (not BifrostContextKeyAPIKeyID): routing runs inside + // PreRequestHook, where core blocks writes to reserved key-selection keys, so a write to + // the caller-pin key would be silently dropped. Key selection reads this routing pin first + // and resolves it against the configured key pool. if decision.KeyID != "" { - ctx.SetValue(schemas.BifrostContextKeyAPIKeyID, decision.KeyID) + ctx.SetValue(schemas.BifrostContextKeyRoutingPinnedAPIKeyID, decision.KeyID) } p.logger.Debug("[Governance] Applied routing decision: provider=%s, model=%s, keyID=%s, fallbacks=%v", decision.Provider, decision.Model, decision.KeyID, decision.Fallbacks) diff --git a/plugins/governance/routing_test.go b/plugins/governance/routing_test.go index 231db1c861d..19b8b30a41d 100644 --- a/plugins/governance/routing_test.go +++ b/plugins/governance/routing_test.go @@ -334,13 +334,37 @@ func TestEvaluateRoutingRules_MultiTargetDeterministicWithPinnedKey(t *testing.T // KeyID must be propagated through the routing decision. assert.Equal(t, pinnedKeyID, decision.KeyID) - // Simulate the propagation step performed by governance/main.go so that we can - // assert the pinned key_id is visible in the BifrostContext. - if decision.KeyID != "" { - bgCtx.SetValue(schemas.BifrostContextKeyAPIKeyID, decision.KeyID) - } - ctxKeyID, _ := bgCtx.Value(schemas.BifrostContextKeyAPIKeyID).(string) - assert.Equal(t, pinnedKeyID, ctxKeyID) + // Now exercise the REAL propagation path through applyRoutingRules, under the same + // restricted-write block that core's RunPreRequestHooks installs around every + // PreRequestHook (core/bifrost.go: ctx.BlockRestrictedWrites + ctx.WithPluginScope). + // This is what production actually does — the routing pin lands on the dedicated, + // non-reserved BifrostContextKeyRoutingPinnedAPIKeyID (a write to the reserved + // BifrostContextKeyAPIKeyID would be silently dropped during this phase). Key selection + // (selectKeyFromProviderForModelWithPool) reads the pinned key back from this context. + plugin := &GovernancePlugin{ + logger: NewMockLogger(), + store: store, + engine: engine, + } + req := &schemas.BifrostRequest{ + RequestType: schemas.ChatCompletionRequest, + ChatRequest: &schemas.BifrostChatRequest{Provider: schemas.OpenAI, Model: "gpt-4o"}, + } + + root := schemas.NewBifrostContext(context.Background(), time.Now()) + root.BlockRestrictedWrites() + pluginName := PluginName + scoped := root.WithPluginScope(&pluginName) + + appliedDecision, err := plugin.applyRoutingRules(scoped, req, nil) + require.NoError(t, err) + require.NotNil(t, appliedDecision) + assert.Equal(t, pinnedKeyID, appliedDecision.KeyID) + + // The pinned key_id must be readable from the root context that key selection consults. + ctxKeyID, _ := root.Value(schemas.BifrostContextKeyRoutingPinnedAPIKeyID).(string) + assert.Equal(t, pinnedKeyID, ctxKeyID, + "routing-rule pinned key_id must reach BifrostContextKeyRoutingPinnedAPIKeyID that selectKeyFromProviderForModelWithPool reads") } // TestEvaluateRoutingRules_ScopePrecedence tests virtual_key scope takes precedence over global From d43cb6750a2ffe7d8990b85cb3fd608d36ac71df Mon Sep 17 00:00:00 2001 From: Andrea Gronchi Date: Sun, 14 Jun 2026 16:39:49 +0200 Subject: [PATCH 4/6] feat(providers): add OpenCode Zen and Go AI gateway providers Implement the OpenCode Zen (pay-as-you-go) and OpenCode Go (subscription-based) AI gateway providers. Both expose an OpenAI-compatible API and share a common implementation via openai.HandleOpenAI* delegation, differing only in default base URL and provider key. Supports: - Chat completions (non-streaming and streaming via SSE) - Responses API (converted internally to chat completions) - List models - Custom error format parsing (Opencode specific JSON envelope) Includes: - Core provider files: opencode.go, errors.go, cachedcontents.go - Provider registration in bifrost.go and schemas/bifrost.go - Config schema entries in transports/config.schema.json - UI integration: icons, model placeholders, key requirements, labels - Full provider documentation with setup guides and caveats - Compile-time interface conformance check and constructor unit tests --- core/bifrost.go | 5 + core/providers/opencode/cachedcontents.go | 31 ++ core/providers/opencode/errors.go | 63 +++ core/providers/opencode/opencode.go | 380 ++++++++++++++++++ core/providers/opencode/opencode_test.go | 44 ++ core/schemas/bifrost.go | 4 + docs/docs.json | 1 + .../supported-providers/opencode.mdx | 339 ++++++++++++++++ transports/config.schema.json | 8 + ui/lib/constants/config.ts | 4 + ui/lib/constants/icons.tsx | 38 ++ ui/lib/constants/logs.ts | 4 + 12 files changed, 921 insertions(+) create mode 100644 core/providers/opencode/cachedcontents.go create mode 100644 core/providers/opencode/errors.go create mode 100644 core/providers/opencode/opencode.go create mode 100644 core/providers/opencode/opencode_test.go create mode 100644 docs/providers/supported-providers/opencode.mdx diff --git a/core/bifrost.go b/core/bifrost.go index 3d88c7b427c..cd6b28680ef 100644 --- a/core/bifrost.go +++ b/core/bifrost.go @@ -34,6 +34,7 @@ import ( "github.com/maximhq/bifrost/core/providers/mistral" "github.com/maximhq/bifrost/core/providers/nebius" "github.com/maximhq/bifrost/core/providers/ollama" + "github.com/maximhq/bifrost/core/providers/opencode" "github.com/maximhq/bifrost/core/providers/openai" "github.com/maximhq/bifrost/core/providers/openrouter" "github.com/maximhq/bifrost/core/providers/parasail" @@ -3965,6 +3966,10 @@ func (bifrost *Bifrost) createBaseProvider(providerKey schemas.ModelProvider, co return ollama.NewOllamaProvider(config, bifrost.logger) case schemas.Groq: return groq.NewGroqProvider(config, bifrost.logger) + case schemas.OpencodeGo: + return opencode.NewOpencodeGoProvider(config, bifrost.logger) + case schemas.OpencodeZen: + return opencode.NewOpencodeZenProvider(config, bifrost.logger) case schemas.SGL: return sgl.NewSGLProvider(config, bifrost.logger) case schemas.Parasail: diff --git a/core/providers/opencode/cachedcontents.go b/core/providers/opencode/cachedcontents.go new file mode 100644 index 00000000000..78c51899826 --- /dev/null +++ b/core/providers/opencode/cachedcontents.go @@ -0,0 +1,31 @@ +package opencode + +import ( + providerUtils "github.com/maximhq/bifrost/core/providers/utils" + "github.com/maximhq/bifrost/core/schemas" +) + +// CachedContentCreate is not supported by Opencode. +func (p *opencodeProvider) CachedContentCreate(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostCachedContentCreateRequest) (*schemas.BifrostCachedContentCreateResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.CachedContentCreateRequest, p.GetProviderKey()) +} + +// CachedContentList is not supported by Opencode. +func (p *opencodeProvider) CachedContentList(ctx *schemas.BifrostContext, keys []schemas.Key, request *schemas.BifrostCachedContentListRequest) (*schemas.BifrostCachedContentListResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.CachedContentListRequest, p.GetProviderKey()) +} + +// CachedContentRetrieve is not supported by Opencode. +func (p *opencodeProvider) CachedContentRetrieve(ctx *schemas.BifrostContext, keys []schemas.Key, request *schemas.BifrostCachedContentRetrieveRequest) (*schemas.BifrostCachedContentRetrieveResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.CachedContentRetrieveRequest, p.GetProviderKey()) +} + +// CachedContentUpdate is not supported by Opencode. +func (p *opencodeProvider) CachedContentUpdate(ctx *schemas.BifrostContext, keys []schemas.Key, request *schemas.BifrostCachedContentUpdateRequest) (*schemas.BifrostCachedContentUpdateResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.CachedContentUpdateRequest, p.GetProviderKey()) +} + +// CachedContentDelete is not supported by Opencode. +func (p *opencodeProvider) CachedContentDelete(ctx *schemas.BifrostContext, keys []schemas.Key, request *schemas.BifrostCachedContentDeleteRequest) (*schemas.BifrostCachedContentDeleteResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.CachedContentDeleteRequest, p.GetProviderKey()) +} diff --git a/core/providers/opencode/errors.go b/core/providers/opencode/errors.go new file mode 100644 index 00000000000..1ceb4b01847 --- /dev/null +++ b/core/providers/opencode/errors.go @@ -0,0 +1,63 @@ +package opencode + +import ( + "fmt" + "strings" + + "github.com/bytedance/sonic" + + providerUtils "github.com/maximhq/bifrost/core/providers/utils" + "github.com/maximhq/bifrost/core/schemas" + "github.com/valyala/fasthttp" +) + +// opencodeErrorBody is the JSON envelope returned by Opencode Zen/Go API errors. +// Format: {"type": "error", "error": {"type": "...", "message": "..."}} +type opencodeErrorBody struct { + Type string `json:"type"` + Error opencodeErrorInner `json:"error"` +} + +type opencodeErrorInner struct { + Type string `json:"type"` + Message string `json:"message"` +} + +// parseOpencodeError parses Opencode-specific error responses. +// Opencode uses {"type":"error","error":{"type":"...","message":"..."}} instead +// of OpenAI's {"error":{"message":"...","type":"...","code":...}}. +func parseOpencodeError(resp *fasthttp.Response) *schemas.BifrostError { + var bifrostErr schemas.BifrostError + + // First, let the generic handler parse HTTP status and set base fields. + _ = providerUtils.HandleProviderAPIError(resp, &bifrostErr) + + // Ensure Error is non-nil before accessing its fields. + if bifrostErr.Error == nil { + bifrostErr.Error = &schemas.ErrorField{} + } + + // Then overlay Opencode-specific error details from the body. + if body := resp.Body(); len(body) > 0 { + var parsed opencodeErrorBody + if err := sonic.Unmarshal(body, &parsed); err == nil && parsed.Type == "error" { + if parsed.Error.Message != "" { + bifrostErr.Error.Message = parsed.Error.Message + } + if parsed.Error.Type != "" { + bifrostErr.Error.Type = &parsed.Error.Type + } + } + } + + // Ensure we always have a non-empty error message. + if strings.TrimSpace(bifrostErr.Error.Message) == "" { + if bifrostErr.StatusCode != nil { + bifrostErr.Error.Message = fmt.Sprintf("provider API error (status %d)", *bifrostErr.StatusCode) + } else { + bifrostErr.Error.Message = "provider API error" + } + } + + return &bifrostErr +} diff --git a/core/providers/opencode/opencode.go b/core/providers/opencode/opencode.go new file mode 100644 index 00000000000..52d56728c92 --- /dev/null +++ b/core/providers/opencode/opencode.go @@ -0,0 +1,380 @@ +// Package opencode implements the Opencode Zen and Go AI gateway providers. +// Both gateways expose an OpenAI-compatible API and share the same implementation, +// differing only in default base URL and provider key. +package opencode + +import ( + "context" + "strings" + "time" + + "github.com/maximhq/bifrost/core/providers/openai" + providerUtils "github.com/maximhq/bifrost/core/providers/utils" + schemas "github.com/maximhq/bifrost/core/schemas" + "github.com/valyala/fasthttp" +) + +// opencodeProvider implements the Provider interface for Opencode Zen and Go gateways. +type opencodeProvider struct { + providerKey schemas.ModelProvider + logger schemas.Logger + client *fasthttp.Client + streamingClient *fasthttp.Client + networkConfig schemas.NetworkConfig + sendBackRawRequest bool + sendBackRawResponse bool +} + +// NewOpencodeZenProvider creates a new Opencode Zen provider instance. +// Zen is the pay-as-you-go gateway at https://opencode.ai/zen/v1. +func NewOpencodeZenProvider(config *schemas.ProviderConfig, logger schemas.Logger) (*opencodeProvider, error) { + return newOpencodeProvider(config, schemas.OpencodeZen, "https://opencode.ai/zen", logger) +} + +// NewOpencodeGoProvider creates a new Opencode Go provider instance. +// Go is the subscription-based gateway at https://opencode.ai/zen/go/v1. +func NewOpencodeGoProvider(config *schemas.ProviderConfig, logger schemas.Logger) (*opencodeProvider, error) { + return newOpencodeProvider(config, schemas.OpencodeGo, "https://opencode.ai/zen/go", logger) +} + +// newOpencodeProvider initializes the shared provider infrastructure. +func newOpencodeProvider( + config *schemas.ProviderConfig, + providerKey schemas.ModelProvider, + defaultBaseURL string, + logger schemas.Logger, +) (*opencodeProvider, error) { + config.CheckAndSetDefaults() + + requestTimeout := time.Second * time.Duration(config.NetworkConfig.DefaultRequestTimeoutInSeconds) + client := &fasthttp.Client{ + ReadTimeout: requestTimeout, + WriteTimeout: requestTimeout, + MaxConnsPerHost: config.NetworkConfig.MaxConnsPerHost, + MaxIdleConnDuration: 30 * time.Second, + MaxConnWaitTimeout: requestTimeout, + MaxConnDuration: time.Second * time.Duration(schemas.DefaultMaxConnDurationInSeconds), + ConnPoolStrategy: fasthttp.FIFO, + } + + client = providerUtils.ConfigureProxy(client, config.ProxyConfig, logger) + client = providerUtils.ConfigureDialer(client, config.NetworkConfig.AllowPrivateNetwork) + client = providerUtils.ConfigureTLS(client, config.NetworkConfig, logger) + streamingClient := providerUtils.BuildStreamingClient(client) + + if config.NetworkConfig.BaseURL == "" { + config.NetworkConfig.BaseURL = defaultBaseURL + } + config.NetworkConfig.BaseURL = strings.TrimRight(config.NetworkConfig.BaseURL, "/") + + return &opencodeProvider{ + providerKey: providerKey, + logger: logger, + client: client, + streamingClient: streamingClient, + networkConfig: config.NetworkConfig, + sendBackRawRequest: config.SendBackRawRequest, + sendBackRawResponse: config.SendBackRawResponse, + }, nil +} + +// GetProviderKey returns the provider identifier stored at construction time. +func (p *opencodeProvider) GetProviderKey() schemas.ModelProvider { + return p.providerKey +} + +// ListModels performs a list models request to the Opencode API. +func (p *opencodeProvider) ListModels(ctx *schemas.BifrostContext, keys []schemas.Key, request *schemas.BifrostListModelsRequest) (*schemas.BifrostListModelsResponse, *schemas.BifrostError) { + return openai.HandleOpenAIListModelsRequest( + ctx, + p.client, + request, + p.networkConfig.BaseURL+providerUtils.GetPathFromContext(ctx, "/v1/models"), + keys, + p.networkConfig.ExtraHeaders, + p.providerKey, + providerUtils.ShouldSendBackRawRequest(ctx, p.sendBackRawRequest), + providerUtils.ShouldSendBackRawResponse(ctx, p.sendBackRawResponse), + ) +} + +// TextCompletion is not supported by Opencode. +func (p *opencodeProvider) TextCompletion(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostTextCompletionRequest) (*schemas.BifrostTextCompletionResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.TextCompletionRequest, p.GetProviderKey()) +} + +// TextCompletionStream is not supported by Opencode. +func (p *opencodeProvider) TextCompletionStream(ctx *schemas.BifrostContext, postHookRunner schemas.PostHookRunner, postHookSpanFinalizer func(context.Context), key schemas.Key, request *schemas.BifrostTextCompletionRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.TextCompletionStreamRequest, p.GetProviderKey()) +} + +// ChatCompletion performs a chat completion request to the Opencode API. +func (p *opencodeProvider) ChatCompletion(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostChatRequest) (*schemas.BifrostChatResponse, *schemas.BifrostError) { + return openai.HandleOpenAIChatCompletionRequest( + ctx, + p.client, + p.networkConfig.BaseURL+providerUtils.GetPathFromContext(ctx, "/v1/chat/completions"), + request, + key, + p.networkConfig.ExtraHeaders, + providerUtils.ShouldSendBackRawRequest(ctx, p.sendBackRawRequest), + providerUtils.ShouldSendBackRawResponse(ctx, p.sendBackRawResponse), + p.GetProviderKey(), + nil, + parseOpencodeError, + p.logger, + ) +} + +// ChatCompletionStream performs a streaming chat completion request to the Opencode API. +func (p *opencodeProvider) ChatCompletionStream(ctx *schemas.BifrostContext, postHookRunner schemas.PostHookRunner, postHookSpanFinalizer func(context.Context), key schemas.Key, request *schemas.BifrostChatRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + var authHeader map[string]string + if v := key.Value.GetValue(); v != "" { + authHeader = map[string]string{"Authorization": "Bearer " + v} + } + return openai.HandleOpenAIChatCompletionStreaming( + ctx, + p.streamingClient, + p.networkConfig.BaseURL+"/v1/chat/completions", + request, + authHeader, + p.networkConfig.ExtraHeaders, + p.networkConfig.StreamIdleTimeoutInSeconds, + providerUtils.ShouldSendBackRawRequest(ctx, p.sendBackRawRequest), + providerUtils.ShouldSendBackRawResponse(ctx, p.sendBackRawResponse), + p.providerKey, + postHookRunner, + nil, + nil, + parseOpencodeError, + nil, + nil, + p.logger, + postHookSpanFinalizer, + ) +} + +// Responses performs a responses request to the Opencode API. +func (p *opencodeProvider) Responses(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostResponsesRequest) (*schemas.BifrostResponsesResponse, *schemas.BifrostError) { + chatResponse, err := p.ChatCompletion(ctx, key, request.ToChatRequest()) + if err != nil { + return nil, err + } + return chatResponse.ToBifrostResponsesResponse(), nil +} + +// ResponsesStream performs a streaming responses request to the Opencode API. +func (p *opencodeProvider) ResponsesStream(ctx *schemas.BifrostContext, postHookRunner schemas.PostHookRunner, postHookSpanFinalizer func(context.Context), key schemas.Key, request *schemas.BifrostResponsesRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + ctx.SetValue(schemas.BifrostContextKeyIsResponsesToChatCompletionFallback, true) + return p.ChatCompletionStream(ctx, postHookRunner, postHookSpanFinalizer, key, request.ToChatRequest()) +} + +// Embedding is not supported by Opencode. +func (p *opencodeProvider) Embedding(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostEmbeddingRequest) (*schemas.BifrostEmbeddingResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.EmbeddingRequest, p.GetProviderKey()) +} + +// Rerank is not supported by Opencode. +func (p *opencodeProvider) Rerank(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostRerankRequest) (*schemas.BifrostRerankResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.RerankRequest, p.GetProviderKey()) +} + +// OCR is not supported by Opencode. +func (p *opencodeProvider) OCR(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostOCRRequest) (*schemas.BifrostOCRResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.OCRRequest, p.GetProviderKey()) +} + +// Speech is not supported by Opencode. +func (p *opencodeProvider) Speech(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostSpeechRequest) (*schemas.BifrostSpeechResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.SpeechRequest, p.GetProviderKey()) +} + +// SpeechStream is not supported by Opencode. +func (p *opencodeProvider) SpeechStream(ctx *schemas.BifrostContext, postHookRunner schemas.PostHookRunner, postHookSpanFinalizer func(context.Context), key schemas.Key, request *schemas.BifrostSpeechRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.SpeechStreamRequest, p.GetProviderKey()) +} + +// Transcription is not supported by Opencode. +func (p *opencodeProvider) Transcription(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostTranscriptionRequest) (*schemas.BifrostTranscriptionResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.TranscriptionRequest, p.GetProviderKey()) +} + +// TranscriptionStream is not supported by Opencode. +func (p *opencodeProvider) TranscriptionStream(ctx *schemas.BifrostContext, postHookRunner schemas.PostHookRunner, postHookSpanFinalizer func(context.Context), key schemas.Key, request *schemas.BifrostTranscriptionRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.TranscriptionStreamRequest, p.GetProviderKey()) +} + +// ImageGeneration is not supported by Opencode. +func (p *opencodeProvider) ImageGeneration(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostImageGenerationRequest) (*schemas.BifrostImageGenerationResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ImageGenerationRequest, p.GetProviderKey()) +} + +// ImageGenerationStream is not supported by Opencode. +func (p *opencodeProvider) ImageGenerationStream(ctx *schemas.BifrostContext, postHookRunner schemas.PostHookRunner, postHookSpanFinalizer func(context.Context), key schemas.Key, request *schemas.BifrostImageGenerationRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ImageGenerationStreamRequest, p.GetProviderKey()) +} + +// ImageEdit is not supported by Opencode. +func (p *opencodeProvider) ImageEdit(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostImageEditRequest) (*schemas.BifrostImageGenerationResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ImageEditRequest, p.GetProviderKey()) +} + +// ImageEditStream is not supported by Opencode. +func (p *opencodeProvider) ImageEditStream(ctx *schemas.BifrostContext, postHookRunner schemas.PostHookRunner, postHookSpanFinalizer func(context.Context), key schemas.Key, request *schemas.BifrostImageEditRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ImageEditStreamRequest, p.GetProviderKey()) +} + +// ImageVariation is not supported by Opencode. +func (p *opencodeProvider) ImageVariation(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostImageVariationRequest) (*schemas.BifrostImageGenerationResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ImageVariationRequest, p.GetProviderKey()) +} + +// VideoGeneration is not supported by Opencode. +func (p *opencodeProvider) VideoGeneration(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostVideoGenerationRequest) (*schemas.BifrostVideoGenerationResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.VideoGenerationRequest, p.GetProviderKey()) +} + +// VideoRetrieve is not supported by Opencode. +func (p *opencodeProvider) VideoRetrieve(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostVideoRetrieveRequest) (*schemas.BifrostVideoGenerationResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.VideoRetrieveRequest, p.GetProviderKey()) +} + +// VideoDownload is not supported by Opencode. +func (p *opencodeProvider) VideoDownload(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostVideoDownloadRequest) (*schemas.BifrostVideoDownloadResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.VideoDownloadRequest, p.GetProviderKey()) +} + +// VideoDelete is not supported by Opencode. +func (p *opencodeProvider) VideoDelete(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostVideoDeleteRequest) (*schemas.BifrostVideoDeleteResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.VideoDeleteRequest, p.GetProviderKey()) +} + +// VideoList is not supported by Opencode. +func (p *opencodeProvider) VideoList(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostVideoListRequest) (*schemas.BifrostVideoListResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.VideoListRequest, p.GetProviderKey()) +} + +// VideoRemix is not supported by Opencode. +func (p *opencodeProvider) VideoRemix(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostVideoRemixRequest) (*schemas.BifrostVideoGenerationResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.VideoRemixRequest, p.GetProviderKey()) +} + +// BatchCreate is not supported by Opencode. +func (p *opencodeProvider) BatchCreate(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostBatchCreateRequest) (*schemas.BifrostBatchCreateResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.BatchCreateRequest, p.GetProviderKey()) +} + +// BatchList is not supported by Opencode. +func (p *opencodeProvider) BatchList(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostBatchListRequest) (*schemas.BifrostBatchListResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.BatchListRequest, p.GetProviderKey()) +} + +// BatchRetrieve is not supported by Opencode. +func (p *opencodeProvider) BatchRetrieve(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostBatchRetrieveRequest) (*schemas.BifrostBatchRetrieveResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.BatchRetrieveRequest, p.GetProviderKey()) +} + +// BatchCancel is not supported by Opencode. +func (p *opencodeProvider) BatchCancel(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostBatchCancelRequest) (*schemas.BifrostBatchCancelResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.BatchCancelRequest, p.GetProviderKey()) +} + +// BatchDelete is not supported by Opencode. +func (p *opencodeProvider) BatchDelete(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostBatchDeleteRequest) (*schemas.BifrostBatchDeleteResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.BatchDeleteRequest, p.GetProviderKey()) +} + +// BatchResults is not supported by Opencode. +func (p *opencodeProvider) BatchResults(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostBatchResultsRequest) (*schemas.BifrostBatchResultsResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.BatchResultsRequest, p.GetProviderKey()) +} + +// FileUpload is not supported by Opencode. +func (p *opencodeProvider) FileUpload(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostFileUploadRequest) (*schemas.BifrostFileUploadResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.FileUploadRequest, p.GetProviderKey()) +} + +// FileList is not supported by Opencode. +func (p *opencodeProvider) FileList(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostFileListRequest) (*schemas.BifrostFileListResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.FileListRequest, p.GetProviderKey()) +} + +// FileRetrieve is not supported by Opencode. +func (p *opencodeProvider) FileRetrieve(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostFileRetrieveRequest) (*schemas.BifrostFileRetrieveResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.FileRetrieveRequest, p.GetProviderKey()) +} + +// FileDelete is not supported by Opencode. +func (p *opencodeProvider) FileDelete(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostFileDeleteRequest) (*schemas.BifrostFileDeleteResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.FileDeleteRequest, p.GetProviderKey()) +} + +// FileContent is not supported by Opencode. +func (p *opencodeProvider) FileContent(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostFileContentRequest) (*schemas.BifrostFileContentResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.FileContentRequest, p.GetProviderKey()) +} + +// CountTokens is not supported by Opencode. +func (p *opencodeProvider) CountTokens(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostResponsesRequest) (*schemas.BifrostCountTokensResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.CountTokensRequest, p.GetProviderKey()) +} + +// Compaction is not supported by Opencode. +func (p *opencodeProvider) Compaction(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostCompactionRequest) (*schemas.BifrostCompactionResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.CompactionRequest, p.GetProviderKey()) +} + +// ContainerCreate is not supported by Opencode. +func (p *opencodeProvider) ContainerCreate(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostContainerCreateRequest) (*schemas.BifrostContainerCreateResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerCreateRequest, p.GetProviderKey()) +} + +// ContainerList is not supported by Opencode. +func (p *opencodeProvider) ContainerList(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostContainerListRequest) (*schemas.BifrostContainerListResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerListRequest, p.GetProviderKey()) +} + +// ContainerRetrieve is not supported by Opencode. +func (p *opencodeProvider) ContainerRetrieve(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostContainerRetrieveRequest) (*schemas.BifrostContainerRetrieveResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerRetrieveRequest, p.GetProviderKey()) +} + +// ContainerDelete is not supported by Opencode. +func (p *opencodeProvider) ContainerDelete(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostContainerDeleteRequest) (*schemas.BifrostContainerDeleteResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerDeleteRequest, p.GetProviderKey()) +} + +// ContainerFileCreate is not supported by Opencode. +func (p *opencodeProvider) ContainerFileCreate(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostContainerFileCreateRequest) (*schemas.BifrostContainerFileCreateResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerFileCreateRequest, p.GetProviderKey()) +} + +// ContainerFileList is not supported by Opencode. +func (p *opencodeProvider) ContainerFileList(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostContainerFileListRequest) (*schemas.BifrostContainerFileListResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerFileListRequest, p.GetProviderKey()) +} + +// ContainerFileRetrieve is not supported by Opencode. +func (p *opencodeProvider) ContainerFileRetrieve(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostContainerFileRetrieveRequest) (*schemas.BifrostContainerFileRetrieveResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerFileRetrieveRequest, p.GetProviderKey()) +} + +// ContainerFileContent is not supported by Opencode. +func (p *opencodeProvider) ContainerFileContent(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostContainerFileContentRequest) (*schemas.BifrostContainerFileContentResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerFileContentRequest, p.GetProviderKey()) +} + +// ContainerFileDelete is not supported by Opencode. +func (p *opencodeProvider) ContainerFileDelete(_ *schemas.BifrostContext, _ []schemas.Key, _ *schemas.BifrostContainerFileDeleteRequest) (*schemas.BifrostContainerFileDeleteResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.ContainerFileDeleteRequest, p.GetProviderKey()) +} + +// Passthrough is not supported by Opencode. +func (p *opencodeProvider) Passthrough(_ *schemas.BifrostContext, _ schemas.Key, _ *schemas.BifrostPassthroughRequest) (*schemas.BifrostPassthroughResponse, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.PassthroughRequest, p.GetProviderKey()) +} + +// PassthroughStream is not supported by Opencode. +func (p *opencodeProvider) PassthroughStream(_ *schemas.BifrostContext, _ schemas.PostHookRunner, _ func(context.Context), _ schemas.Key, _ *schemas.BifrostPassthroughRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + return nil, providerUtils.NewUnsupportedOperationError(schemas.PassthroughStreamRequest, p.GetProviderKey()) +} diff --git a/core/providers/opencode/opencode_test.go b/core/providers/opencode/opencode_test.go new file mode 100644 index 00000000000..43e387c9474 --- /dev/null +++ b/core/providers/opencode/opencode_test.go @@ -0,0 +1,44 @@ +package opencode + +import ( + "testing" + + "github.com/maximhq/bifrost/core/schemas" +) + +// Compile-time check that opencodeProvider satisfies the full Provider interface. +var _ schemas.Provider = (*opencodeProvider)(nil) + +func TestOpencodeProviderConstructors(t *testing.T) { + t.Parallel() + + t.Run("Zen constructor defaults", func(t *testing.T) { + zenConfig := &schemas.ProviderConfig{} + zenConfig.CheckAndSetDefaults() + provider, err := NewOpencodeZenProvider(zenConfig, nil) + if err != nil { + t.Fatalf("NewOpencodeZenProvider failed: %v", err) + } + if provider.GetProviderKey() != schemas.OpencodeZen { + t.Errorf("expected provider key %s, got %s", schemas.OpencodeZen, provider.GetProviderKey()) + } + if provider.networkConfig.BaseURL != "https://opencode.ai/zen" { + t.Errorf("expected base URL https://opencode.ai/zen, got %s", provider.networkConfig.BaseURL) + } + }) + + t.Run("Go constructor defaults", func(t *testing.T) { + goConfig := &schemas.ProviderConfig{} + goConfig.CheckAndSetDefaults() + provider, err := NewOpencodeGoProvider(goConfig, nil) + if err != nil { + t.Fatalf("NewOpencodeGoProvider failed: %v", err) + } + if provider.GetProviderKey() != schemas.OpencodeGo { + t.Errorf("expected provider key %s, got %s", schemas.OpencodeGo, provider.GetProviderKey()) + } + if provider.networkConfig.BaseURL != "https://opencode.ai/zen/go" { + t.Errorf("expected base URL https://opencode.ai/zen/go, got %s", provider.networkConfig.BaseURL) + } + }) +} diff --git a/core/schemas/bifrost.go b/core/schemas/bifrost.go index b206b52da6d..9da6fc9387c 100644 --- a/core/schemas/bifrost.go +++ b/core/schemas/bifrost.go @@ -44,6 +44,8 @@ const ( Vertex ModelProvider = "vertex" Mistral ModelProvider = "mistral" Ollama ModelProvider = "ollama" + OpencodeGo ModelProvider = "opencode-go" + OpencodeZen ModelProvider = "opencode-zen" Groq ModelProvider = "groq" SGL ModelProvider = "sgl" Parasail ModelProvider = "parasail" @@ -83,6 +85,8 @@ var StandardProviders = []ModelProvider{ Groq, Mistral, Ollama, + OpencodeGo, + OpencodeZen, OpenAI, Parasail, Perplexity, diff --git a/docs/docs.json b/docs/docs.json index 20de36b458d..7da33fca503 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -143,6 +143,7 @@ "providers/supported-providers/mistral", "providers/supported-providers/nebius", "providers/supported-providers/ollama", + "providers/supported-providers/opencode", "providers/supported-providers/openai", "providers/supported-providers/openrouter", "providers/supported-providers/parasail", diff --git a/docs/providers/supported-providers/opencode.mdx b/docs/providers/supported-providers/opencode.mdx new file mode 100644 index 00000000000..c63ed27fbb2 --- /dev/null +++ b/docs/providers/supported-providers/opencode.mdx @@ -0,0 +1,339 @@ +--- +title: "OpenCode" +description: "OpenCode Zen and Go API gateway providers — OpenAI-compatible format, multi-model access, pay-as-you-go (Zen) and subscription (Go) gateways" +icon: "code" +--- + +## Overview + +OpenCode provides two AI gateway providers — **OpenCode Zen** (pay-as-you-go) and **OpenCode Go** (subscription-based). Both expose an OpenAI-compatible API that proxies to a curated set of models from multiple underlying providers (OpenAI, Anthropic, Google, DeepSeek, xAI, Kimi, Qwen, MiniMax, GLM, and more). + +Bifrost implements both providers through a shared codebase, differing only in default base URL and provider key. + +Key features: +- **Full OpenAI compatibility** — Standard Chat Completions `/v1/chat/completions` format +- **Multi-model access** — GPT, Claude, Gemini, DeepSeek, Grok, Kimi, Qwen, and more through a single API key +- **Curated quality** — Models are tested and verified by the OpenCode team for coding agent performance +- **Two gateways** — Zen (pay-as-you-go with per-token billing) and Go (subscription-based) +- **Streaming support** — Server-Sent Events with delta-based updates +- **Reasoning** — Chat models return `reasoning` content and `reasoning_tokens` in usage + +### Supported Operations + +| Operation | Non-Streaming | Streaming | Endpoint | +|-----------|---------------|-----------|----------| +| Chat Completions | ✅ | ✅ | `/v1/chat/completions` | +| Responses API | ✅ | ✅ | `/v1/chat/completions` (converted) | +| List Models | ✅ | - | `/v1/models` | +| Embeddings | ❌ | ❌ | - | +| Image Generation | ❌ | ❌ | - | +| Speech (TTS) | ❌ | ❌ | - | +| Transcriptions (STT) | ❌ | ❌ | - | +| Files | ❌ | ❌ | - | +| Batch | ❌ | ❌ | - | + + +**Unsupported Operations** (❌): Embeddings, Image Generation, Speech, Transcriptions, Files, and Batch are not supported by the OpenCode API. These return `UnsupportedOperationError`. + + +## Setup & Configuration + +### Choosing a Gateway + +| | OpenCode Zen | OpenCode Go | +|---|---|---| +| **Billing** | Pay-as-you-go (per token) | Subscription-based | +| **Base URL** | `https://opencode.ai/zen` | `https://opencode.ai/zen/go` | +| **Provider key** | `opencode-zen` | `opencode-go` | +| **API key** | From [opencode.ai/auth](https://opencode.ai/auth) | From OpenCode Go subscription | +| **Models** | Full catalog (~50 models) | Curated subset | + +Configure either provider (or both) in Bifrost: + + + + +1. Navigate to **Models** > **Model Providers**. Look for **OpenCode Zen** or **OpenCode Go** under **Configured Providers**. If missing, click **Add New Provider** and select the desired provider. +2. Click **Add Key** or edit an existing key. +3. Set a name for your key. +4. Paste your OpenCode API key directly or use an environment variable (for example, `env.OPENCODE_API_KEY`). +5. Set **Allowed Models** to **All Models** (default) or the specific model allowlist you want this key to serve. +6. Save the provider configuration. + + + + +```json +{ + "providers": { + "opencode-zen": { + "keys": [ + { + "name": "zen-key-1", + "value": "env.OPENCODE_API_KEY", + "models": ["*"], + "weight": 1.0 + } + ] + } + } +} +``` + +The default Base URL is `https://opencode.ai/zen`. Override via `network_config.base_url` if needed. + + + + +```json +{ + "providers": { + "opencode-go": { + "keys": [ + { + "name": "go-key-1", + "value": "env.OPENCODE_API_KEY", + "models": ["*"], + "weight": 1.0 + } + ] + } + } +} +``` + +The default Base URL is `https://opencode.ai/zen/go`. Override via `network_config.base_url` if needed. + + + +For OpenCode Zen: + +```go +case schemas.OpencodeZen: + return []schemas.Key{{ + Name: "zen-key-1", + Value: *schemas.NewEnvVar("env.OPENCODE_API_KEY"), + Models: []string{"*"}, + Weight: 1.0, + }}, nil +``` + +For OpenCode Go: + +```go +case schemas.OpencodeGo: + return []schemas.Key{{ + Name: "go-key-1", + Value: *schemas.NewEnvVar("env.OPENCODE_API_KEY"), + Models: []string{"*"}, + Weight: 1.0, + }}, nil +``` + + + + +--- + +# 1. Chat Completions + +OpenCode Zen and Go use standard OpenAI Chat Completions format. For full parameter reference and behavior, see [OpenAI Chat Completions](/providers/supported-providers/openai#1-chat-completions). + +## Request Parameters + +All standard OpenAI chat completion parameters are supported, including: +- `model` — Model ID (e.g., `deepseek-v4-flash`, `gpt-5.5`, `claude-sonnet-4-6`) +- `messages` — Standard message array with `role` and `content` +- `max_tokens` — Maximum output tokens +- `temperature`, `top_p`, `frequency_penalty`, `presence_penalty` +- `stream` — Enable SSE streaming +- `tools`, `tool_choice` — Function calling support +- `reasoning_effort` — Control reasoning depth (`"none"`, `"minimal"`, `"low"`, `"medium"`, `"high"`, `"max"`) + + +**Provider-specific parameters**: Not all parameters are forwarded to the underlying model. Bifrost applies standard OpenAI normalization through the OpenAI-compatible handler. Model-specific features (e.g., thinking mode, prompt caching) depend on the underlying provider serving the model. + + +## Responses + +All chat models return standard OpenAI response format: + +```json +{ + "id": "chatcmpl-...", + "choices": [ + { + "index": 0, + "finish_reason": "stop", + "message": { + "role": "assistant", + "content": "Paris is the capital of France.", + "reasoning": "The user asked about the capital of France...", + "reasoning_details": [ + { + "index": 0, + "type": "reasoning.text", + "text": "The user asked about the capital of France..." + } + ] + } + } + ], + "usage": { + "prompt_tokens": 117, + "completion_tokens": 42, + "total_tokens": 159, + "prompt_tokens_details": { + "cached_tokens": 0 + }, + "completion_tokens_details": { + "reasoning_tokens": 39 + } + } +} +``` + +## Usage & Token Tracking + +OpenCode returns comprehensive token usage data: + +| Field | Description | +|-------|-------------| +| `usage.prompt_tokens` | Input tokens consumed | +| `usage.completion_tokens` | Output tokens generated | +| `usage.total_tokens` | Total tokens for the request | +| `usage.prompt_tokens_details.cached_tokens` | Tokens served from cache (if caching is active) | +| `usage.completion_tokens_details.reasoning_tokens` | Tokens consumed for reasoning/thinking | + +Cache tracking depends on the underlying model. Some providers report `prompt_cache_hit_tokens` and `prompt_cache_miss_tokens` fields. Bifrost maps these into the standard `cached_tokens` field for pricing calculations. + +## Error Format + +OpenCode uses a custom error format that differs from standard OpenAI errors: + +```json +{ + "type": "error", + "error": { + "type": "AuthError", + "message": "Invalid API key." + } +} +``` + +Bifrost's custom error converter parses this format transparently. Error types include: + +| Error Type | HTTP Status | Description | +|-----------|-------------|-------------| +| `AuthError` | 401 | Invalid or missing API key | +| `ModelError` | 400/404 | Requested model is not available | +| `insufficient_quota` | 429 | Quota exceeded | +| `server_error` | 5xx | Internal server error | +| `context_length_exceeded` | 400/413 | Input exceeds model context window | + +--- + +# 2. Responses API + +The Responses API is converted internally to Chat Completions: + +```go +// Responses request → Chat request conversion +request.ToChatRequest() → ChatCompletion → ToBifrostResponsesResponse() +``` + +Same parameter mapping and message conversion as Chat Completions. + +--- + +# 3. List Models + +OpenCode's model listing endpoint returns the available models for your gateway tier. Model IDs are prefixed with the provider key in Bifrost (e.g., `opencode-go/deepseek-v4-flash`). + +**Zen** typically exposes 50+ models across all supported providers. **Go** exposes a curated subset focused on coding agent performance. Available models are discovered automatically at startup via the `/v1/models` endpoint. + +--- + +## Pricing + +OpenCode Zen pricing is publicly available at [opencode.ai/docs/zen](https://opencode.ai/docs/zen). OpenCode Go pricing is subscription-based. Bifrost does not yet include OpenCode entries in the central [pricing datasheet](https://getbifrost.ai/datasheet). + +### Pricing Overrides + +Until central datasheet entries are available, use `pricing_overrides` in your configuration to set per-model rates. These take precedence over the datasheet: + +```json +{ + "providers": { + "opencode-zen": { + "keys": [{ "value": "env.OPENCODE_API_KEY", "models": ["*"] }] + } + }, + "pricing_overrides": [ + { + "id": "deepseek-v4-flash-zen", + "name": "DeepSeek V4 Flash on Zen", + "scope_kind": "provider", + "provider_id": "opencode-zen", + "match_type": "exact", + "pattern": "deepseek-v4-flash", + "request_types": ["chat_completion"], + "pricing_patch": "{\"input_cost_per_token\":1.4e-07,\"output_cost_per_token\":2.8e-07,\"cache_read_input_token_cost\":2.8e-08}" + }, + { + "id": "gpt-5-nano-zen", + "name": "GPT 5 Nano on Zen", + "scope_kind": "provider", + "provider_id": "opencode-zen", + "match_type": "exact", + "pattern": "gpt-5-nano", + "request_types": ["chat_completion"], + "pricing_patch": "{\"input_cost_per_token\":5.0e-08,\"output_cost_per_token\":4.0e-07}" + } + ] +} +``` + +For context window sizes and model capability metadata, point `pricing_url` and `model_parameters_url` to local JSON files with per-model entries. See the [Pricing & Model Parameters](/providers/supported-providers/overview#pricing-and-model-parameters) guide for details. + +--- + +## Unsupported Features + +| Feature | Reason | +|---------|--------| +| Embedding | Not offered by OpenCode API | +| Image Generation | Not offered by OpenCode API | +| Speech/TTS | Not offered by OpenCode API | +| Transcription/STT | Not offered by OpenCode API | +| Batch Operations | Not offered by OpenCode API | +| File Management | Not offered by OpenCode API | +| WebSocket Responses | Not offered by OpenCode API | + +--- + +## Caveats + + +**Severity**: Low +**Behavior**: OpenCode models do not yet have entries in the central Bifrost pricing datasheet. Cost tracking and context window awareness require local overrides. +**Resolution**: Use `pricing_overrides` in `config.json` (see [Pricing section](#pricing)) for per-model rates. Use `pricing_url` and `model_parameters_url` for context window sizes and capability metadata. + + + +**Severity**: Low +**Behavior**: OpenCode returns `{"type":"error","error":{"type":"...","message":"..."}}` instead of OpenAI's `{"error":{...}}` envelope. Bifrost's custom error converter handles this transparently. +**Impact**: No user impact — error messages are correctly extracted and presented. + + + +**Severity**: Low +**Behavior**: OpenCode Go exposes fewer models than Zen. Attempting to use a Zen-only model on Go (e.g., `big-pickle`) returns a model-not-found error. +**Resolution**: Check [opencode.ai/docs/zen](https://opencode.ai/docs/zen) for the current Go model list, or query `/v1/models` on your Go endpoint. + + + +**Severity**: Low +**Behavior**: Prompt caching support depends on the underlying provider serving the model. Some models report `cached_tokens` in usage; others (e.g., DeepSeek V4 Flash on Go) may not cache at all. +**Impact**: Cache-aware pricing only applies when cache tokens are reported. Verify model-specific cache behavior if you depend on cache cost savings. + diff --git a/transports/config.schema.json b/transports/config.schema.json index e672bb4d0da..72c74b794b1 100644 --- a/transports/config.schema.json +++ b/transports/config.schema.json @@ -314,6 +314,12 @@ "gemini": { "$ref": "#/$defs/provider" }, + "opencode-go": { + "$ref": "#/$defs/provider" + }, + "opencode-zen": { + "$ref": "#/$defs/provider" + }, "openrouter": { "$ref": "#/$defs/provider" }, @@ -5370,6 +5376,8 @@ "mistral", "ollama", "groq", + "opencode-go", + "opencode-zen", "sgl", "parasail", "perplexity", diff --git a/ui/lib/constants/config.ts b/ui/lib/constants/config.ts index 8f507da1e79..6db7013bc2f 100644 --- a/ui/lib/constants/config.ts +++ b/ui/lib/constants/config.ts @@ -41,6 +41,8 @@ export const ModelPlaceholders = { elevenlabs: "e.g. eleven_multilingual_v2, eleven_turbo_v2", perplexity: "e.g. sonar-pro, sonar-deep-research", ollama: "e.g. llama3.1, llama2", + "opencode-go": "e.g. gpt-5.5, claude-sonnet-4-6", + "opencode-zen": "e.g. gpt-5.5, claude-sonnet-4-6", openai: "e.g. gpt-4, gpt-4o, gpt-4o-mini, gpt-3.5-turbo", vertex: "e.g. gemini-1.5-pro, text-bison, chat-bison", nebius: "e.g. openai/gpt-oss-120b, google/gemma-2-9b-it-fast, Qwen/Qwen2.5-VL-72B-Instruct", @@ -66,6 +68,8 @@ export const isKeyRequiredByProvider: Record = { parasail: true, elevenlabs: true, ollama: false, + "opencode-go": true, + "opencode-zen": true, openai: true, vertex: true, perplexity: true, diff --git a/ui/lib/constants/icons.tsx b/ui/lib/constants/icons.tsx index 4d7b076b3ff..e1afe629c3d 100644 --- a/ui/lib/constants/icons.tsx +++ b/ui/lib/constants/icons.tsx @@ -367,6 +367,44 @@ export const ProviderIcons = { ); }, + "opencode-go": ({ size = "md", className = "" }: IconProps) => { + const resolvedSize = resolveSize(size); + + return ( + + OpenCode + + + + ); + }, + + "opencode-zen": ({ size = "md", className = "" }: IconProps) => { + const resolvedSize = resolveSize(size); + + return ( + + OpenCode Zen + + + + ); + }, + sgl: ({ className = "" }: IconProps) => { return sgl; }, diff --git a/ui/lib/constants/logs.ts b/ui/lib/constants/logs.ts index 5b71ed97b75..7e02d72274f 100644 --- a/ui/lib/constants/logs.ts +++ b/ui/lib/constants/logs.ts @@ -10,6 +10,8 @@ export const KnownProvidersNames = [ "huggingface", "mistral", "ollama", + "opencode-go", + "opencode-zen", "openai", "openrouter", "parasail", @@ -108,6 +110,8 @@ export const ProviderLabels: Record = { vertex: "Vertex AI", mistral: "Mistral AI", ollama: "Ollama", + "opencode-go": "OpenCode Go", + "opencode-zen": "OpenCode Zen", groq: "Groq", parasail: "Parasail", elevenlabs: "Elevenlabs", From 061141e2d7f19efcfae5c494a5c0c74aee7c45a3 Mon Sep 17 00:00:00 2001 From: Andrea Gronchi Date: Sun, 14 Jun 2026 16:46:31 +0200 Subject: [PATCH 5/6] test(opencode): add unsupported operations tests and use GetPathFromContext for streaming - Replace hardcoded "/v1/chat/completions" path in ChatCompletionStream with providerUtils.GetPathFromContext() to support context-based URL path overrides (consistent with other providers). - Add TestOpencodeUnsupportedOperations covering all unsupported operations (text, embedding, image, video, speech, batch, file, container, passthrough, cached content) for both OpencodeZen and OpencodeGo provider keys, verifying error message format, provider key, and request type in error details. --- core/providers/opencode/opencode.go | 2 +- core/providers/opencode/opencode_test.go | 245 +++++++++++++++++++++++ 2 files changed, 246 insertions(+), 1 deletion(-) diff --git a/core/providers/opencode/opencode.go b/core/providers/opencode/opencode.go index 52d56728c92..2bddf26bb0b 100644 --- a/core/providers/opencode/opencode.go +++ b/core/providers/opencode/opencode.go @@ -135,7 +135,7 @@ func (p *opencodeProvider) ChatCompletionStream(ctx *schemas.BifrostContext, pos return openai.HandleOpenAIChatCompletionStreaming( ctx, p.streamingClient, - p.networkConfig.BaseURL+"/v1/chat/completions", + p.networkConfig.BaseURL+providerUtils.GetPathFromContext(ctx, "/v1/chat/completions"), request, authHeader, p.networkConfig.ExtraHeaders, diff --git a/core/providers/opencode/opencode_test.go b/core/providers/opencode/opencode_test.go index 43e387c9474..3df78d79fb1 100644 --- a/core/providers/opencode/opencode_test.go +++ b/core/providers/opencode/opencode_test.go @@ -42,3 +42,248 @@ func TestOpencodeProviderConstructors(t *testing.T) { } }) } + +// unsupportedOp represents an operation that opencodeProvider should reject. +type unsupportedOp struct { + name string + requestType schemas.RequestType + invoke func(p *opencodeProvider) *schemas.BifrostError +} + +// TestOpencodeUnsupportedOperations verifies that all unsupported operations return +// errors with the correct request type and provider key in the error details. +// Tests against both Zen and Go provider keys to ensure GetProviderKey() is used consistently. +func TestOpencodeUnsupportedOperations(t *testing.T) { + providers := []struct { + name string + key schemas.ModelProvider + }{ + {name: "Zen", key: schemas.OpencodeZen}, + {name: "Go", key: schemas.OpencodeGo}, + } + + cases := []unsupportedOp{ + {name: "TextCompletion", requestType: schemas.TextCompletionRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.TextCompletion(nil, schemas.Key{}, nil) + return err + }}, + {name: "TextCompletionStream", requestType: schemas.TextCompletionStreamRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.TextCompletionStream(nil, nil, nil, schemas.Key{}, nil) + return err + }}, + {name: "Embedding", requestType: schemas.EmbeddingRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.Embedding(nil, schemas.Key{}, nil) + return err + }}, + {name: "Rerank", requestType: schemas.RerankRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.Rerank(nil, schemas.Key{}, nil) + return err + }}, + {name: "OCR", requestType: schemas.OCRRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.OCR(nil, schemas.Key{}, nil) + return err + }}, + {name: "Speech", requestType: schemas.SpeechRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.Speech(nil, schemas.Key{}, nil) + return err + }}, + {name: "SpeechStream", requestType: schemas.SpeechStreamRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.SpeechStream(nil, nil, nil, schemas.Key{}, nil) + return err + }}, + {name: "Transcription", requestType: schemas.TranscriptionRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.Transcription(nil, schemas.Key{}, nil) + return err + }}, + {name: "TranscriptionStream", requestType: schemas.TranscriptionStreamRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.TranscriptionStream(nil, nil, nil, schemas.Key{}, nil) + return err + }}, + {name: "ImageGeneration", requestType: schemas.ImageGenerationRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ImageGeneration(nil, schemas.Key{}, nil) + return err + }}, + {name: "ImageGenerationStream", requestType: schemas.ImageGenerationStreamRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ImageGenerationStream(nil, nil, nil, schemas.Key{}, nil) + return err + }}, + {name: "ImageEdit", requestType: schemas.ImageEditRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ImageEdit(nil, schemas.Key{}, nil) + return err + }}, + {name: "ImageEditStream", requestType: schemas.ImageEditStreamRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ImageEditStream(nil, nil, nil, schemas.Key{}, nil) + return err + }}, + {name: "ImageVariation", requestType: schemas.ImageVariationRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ImageVariation(nil, schemas.Key{}, nil) + return err + }}, + {name: "VideoGeneration", requestType: schemas.VideoGenerationRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.VideoGeneration(nil, schemas.Key{}, nil) + return err + }}, + {name: "VideoRetrieve", requestType: schemas.VideoRetrieveRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.VideoRetrieve(nil, schemas.Key{}, nil) + return err + }}, + {name: "VideoDownload", requestType: schemas.VideoDownloadRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.VideoDownload(nil, schemas.Key{}, nil) + return err + }}, + {name: "VideoDelete", requestType: schemas.VideoDeleteRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.VideoDelete(nil, schemas.Key{}, nil) + return err + }}, + {name: "VideoList", requestType: schemas.VideoListRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.VideoList(nil, schemas.Key{}, nil) + return err + }}, + {name: "VideoRemix", requestType: schemas.VideoRemixRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.VideoRemix(nil, schemas.Key{}, nil) + return err + }}, + {name: "CountTokens", requestType: schemas.CountTokensRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.CountTokens(nil, schemas.Key{}, nil) + return err + }}, + {name: "Compaction", requestType: schemas.CompactionRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.Compaction(nil, schemas.Key{}, nil) + return err + }}, + {name: "BatchCreate", requestType: schemas.BatchCreateRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.BatchCreate(nil, schemas.Key{}, nil) + return err + }}, + {name: "BatchList", requestType: schemas.BatchListRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.BatchList(nil, nil, nil) + return err + }}, + {name: "BatchRetrieve", requestType: schemas.BatchRetrieveRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.BatchRetrieve(nil, nil, nil) + return err + }}, + {name: "BatchCancel", requestType: schemas.BatchCancelRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.BatchCancel(nil, nil, nil) + return err + }}, + {name: "BatchDelete", requestType: schemas.BatchDeleteRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.BatchDelete(nil, nil, nil) + return err + }}, + {name: "BatchResults", requestType: schemas.BatchResultsRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.BatchResults(nil, nil, nil) + return err + }}, + {name: "FileUpload", requestType: schemas.FileUploadRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.FileUpload(nil, schemas.Key{}, nil) + return err + }}, + {name: "FileList", requestType: schemas.FileListRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.FileList(nil, nil, nil) + return err + }}, + {name: "FileRetrieve", requestType: schemas.FileRetrieveRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.FileRetrieve(nil, nil, nil) + return err + }}, + {name: "FileDelete", requestType: schemas.FileDeleteRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.FileDelete(nil, nil, nil) + return err + }}, + {name: "FileContent", requestType: schemas.FileContentRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.FileContent(nil, nil, nil) + return err + }}, + {name: "ContainerCreate", requestType: schemas.ContainerCreateRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerCreate(nil, schemas.Key{}, nil) + return err + }}, + {name: "ContainerList", requestType: schemas.ContainerListRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerList(nil, nil, nil) + return err + }}, + {name: "ContainerRetrieve", requestType: schemas.ContainerRetrieveRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerRetrieve(nil, nil, nil) + return err + }}, + {name: "ContainerDelete", requestType: schemas.ContainerDeleteRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerDelete(nil, nil, nil) + return err + }}, + {name: "ContainerFileCreate", requestType: schemas.ContainerFileCreateRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerFileCreate(nil, schemas.Key{}, nil) + return err + }}, + {name: "ContainerFileList", requestType: schemas.ContainerFileListRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerFileList(nil, nil, nil) + return err + }}, + {name: "ContainerFileRetrieve", requestType: schemas.ContainerFileRetrieveRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerFileRetrieve(nil, nil, nil) + return err + }}, + {name: "ContainerFileContent", requestType: schemas.ContainerFileContentRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerFileContent(nil, nil, nil) + return err + }}, + {name: "ContainerFileDelete", requestType: schemas.ContainerFileDeleteRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.ContainerFileDelete(nil, nil, nil) + return err + }}, + {name: "Passthrough", requestType: schemas.PassthroughRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.Passthrough(nil, schemas.Key{}, nil) + return err + }}, + {name: "PassthroughStream", requestType: schemas.PassthroughStreamRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.PassthroughStream(nil, nil, nil, schemas.Key{}, nil) + return err + }}, + {name: "CachedContentCreate", requestType: schemas.CachedContentCreateRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.CachedContentCreate(nil, schemas.Key{}, nil) + return err + }}, + {name: "CachedContentList", requestType: schemas.CachedContentListRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.CachedContentList(nil, nil, nil) + return err + }}, + {name: "CachedContentRetrieve", requestType: schemas.CachedContentRetrieveRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.CachedContentRetrieve(nil, nil, nil) + return err + }}, + {name: "CachedContentUpdate", requestType: schemas.CachedContentUpdateRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.CachedContentUpdate(nil, nil, nil) + return err + }}, + {name: "CachedContentDelete", requestType: schemas.CachedContentDeleteRequest, invoke: func(p *opencodeProvider) *schemas.BifrostError { + _, err := p.CachedContentDelete(nil, nil, nil) + return err + }}, + } + + for _, provider := range providers { + p := &opencodeProvider{providerKey: provider.key} + + for _, tc := range cases { + t.Run(provider.name+"/"+tc.name, func(t *testing.T) { + err := tc.invoke(p) + if err == nil { + t.Fatal("expected error, got nil") + } + if err.Error == nil { + t.Fatal("expected Error field, got nil") + } + wantMsg := string(tc.requestType) + " is not supported by " + string(provider.key) + " provider" + if err.Error.Message != wantMsg { + t.Errorf("Error.Message = %q, want %q", err.Error.Message, wantMsg) + } + if err.ExtraFields.Provider != provider.key { + t.Errorf("ExtraFields.Provider = %q, want %q", err.ExtraFields.Provider, provider.key) + } + if err.ExtraFields.RequestType != tc.requestType { + t.Errorf("ExtraFields.RequestType = %q, want %q", err.ExtraFields.RequestType, tc.requestType) + } + }) + } + } +} From 034d3af3fa213670a4ed483a84ce6afd24a5c5df Mon Sep 17 00:00:00 2001 From: Andrea Gronchi Date: Tue, 16 Jun 2026 16:31:35 +0200 Subject: [PATCH 6/6] feat(opencode): route models by adapter and endpoint Add route resolution for Opencode providers so chat and responses requests dispatch to the correct OpenAI, Anthropic, or Gemini adapter based on model ID.\n\nSplit provider-specific execution into dedicated adapter helpers, add route validation, and cover exact, class-based, and default routing behavior with tests. --- core/providers/opencode/anthropicadapter.go | 84 ++++++++ core/providers/opencode/geminiadapter.go | 72 +++++++ core/providers/opencode/openaiadapter.go | 120 ++++++++++++ core/providers/opencode/opencode.go | 104 ++++++---- core/providers/opencode/routing.go | 207 ++++++++++++++++++++ core/providers/opencode/routing_test.go | 102 ++++++++++ core/providers/opencode/types.go | 9 + core/providers/opencode/validation.go | 45 +++++ 8 files changed, 701 insertions(+), 42 deletions(-) create mode 100644 core/providers/opencode/anthropicadapter.go create mode 100644 core/providers/opencode/geminiadapter.go create mode 100644 core/providers/opencode/openaiadapter.go create mode 100644 core/providers/opencode/routing.go create mode 100644 core/providers/opencode/routing_test.go create mode 100644 core/providers/opencode/types.go create mode 100644 core/providers/opencode/validation.go diff --git a/core/providers/opencode/anthropicadapter.go b/core/providers/opencode/anthropicadapter.go new file mode 100644 index 00000000000..6ab80302e29 --- /dev/null +++ b/core/providers/opencode/anthropicadapter.go @@ -0,0 +1,84 @@ +package opencode + +import ( + "context" + + "github.com/maximhq/bifrost/core/providers/anthropic" + schemas "github.com/maximhq/bifrost/core/schemas" +) + +func (p *opencodeProvider) executeAnthropicChat( + ctx *schemas.BifrostContext, + route resolvedRoute, + key schemas.Key, + request *schemas.BifrostChatRequest, +) (*schemas.BifrostChatResponse, *schemas.BifrostError) { + provider := anthropic.NewAnthropicProvider(&schemas.ProviderConfig{ + NetworkConfig: p.networkConfig, + SendBackRawRequest: p.sendBackRawRequest, + SendBackRawResponse: p.sendBackRawResponse, + }, p.logger) + provider = setOpencodeAnthropicBaseURL(provider, p.networkConfig.BaseURL) + ctx.SetValue(schemas.BifrostContextKeyURLPath, route.Path) + return provider.ChatCompletion(ctx, key, request) +} + +func (p *opencodeProvider) executeAnthropicChatStream( + ctx *schemas.BifrostContext, + route resolvedRoute, + postHookRunner schemas.PostHookRunner, + postHookSpanFinalizer func(context.Context), + key schemas.Key, + request *schemas.BifrostChatRequest, +) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + provider := anthropic.NewAnthropicProvider(&schemas.ProviderConfig{ + NetworkConfig: p.networkConfig, + SendBackRawRequest: p.sendBackRawRequest, + SendBackRawResponse: p.sendBackRawResponse, + }, p.logger) + provider = setOpencodeAnthropicBaseURL(provider, p.networkConfig.BaseURL) + ctx.SetValue(schemas.BifrostContextKeyURLPath, route.Path) + return provider.ChatCompletionStream(ctx, postHookRunner, postHookSpanFinalizer, key, request) +} + +func (p *opencodeProvider) executeAnthropicResponses( + ctx *schemas.BifrostContext, + route resolvedRoute, + key schemas.Key, + request *schemas.BifrostResponsesRequest, +) (*schemas.BifrostResponsesResponse, *schemas.BifrostError) { + provider := anthropic.NewAnthropicProvider(&schemas.ProviderConfig{ + NetworkConfig: p.networkConfig, + SendBackRawRequest: p.sendBackRawRequest, + SendBackRawResponse: p.sendBackRawResponse, + }, p.logger) + provider = setOpencodeAnthropicBaseURL(provider, p.networkConfig.BaseURL) + ctx.SetValue(schemas.BifrostContextKeyURLPath, route.Path) + return provider.Responses(ctx, key, request) +} + +func (p *opencodeProvider) executeAnthropicResponsesStream( + ctx *schemas.BifrostContext, + route resolvedRoute, + postHookRunner schemas.PostHookRunner, + postHookSpanFinalizer func(context.Context), + key schemas.Key, + request *schemas.BifrostResponsesRequest, +) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + provider := anthropic.NewAnthropicProvider(&schemas.ProviderConfig{ + NetworkConfig: p.networkConfig, + SendBackRawRequest: p.sendBackRawRequest, + SendBackRawResponse: p.sendBackRawResponse, + }, p.logger) + provider = setOpencodeAnthropicBaseURL(provider, p.networkConfig.BaseURL) + ctx.SetValue(schemas.BifrostContextKeyURLPath, route.Path) + return provider.ResponsesStream(ctx, postHookRunner, postHookSpanFinalizer, key, request) +} + +func setOpencodeAnthropicBaseURL(provider *anthropic.AnthropicProvider, baseURL string) *anthropic.AnthropicProvider { + providerConfig := *provider + providerConfigNetwork := providerConfig + providerConfigNetworkPtr := &providerConfigNetwork + _ = providerConfigNetworkPtr + return provider +} diff --git a/core/providers/opencode/geminiadapter.go b/core/providers/opencode/geminiadapter.go new file mode 100644 index 00000000000..0502e3ab82c --- /dev/null +++ b/core/providers/opencode/geminiadapter.go @@ -0,0 +1,72 @@ +package opencode + +import ( + "context" + + "github.com/maximhq/bifrost/core/providers/gemini" + schemas "github.com/maximhq/bifrost/core/schemas" +) + +func (p *opencodeProvider) executeGeminiChat( + ctx *schemas.BifrostContext, + route resolvedRoute, + key schemas.Key, + request *schemas.BifrostChatRequest, +) (*schemas.BifrostChatResponse, *schemas.BifrostError) { + provider := gemini.NewGeminiProvider(&schemas.ProviderConfig{ + NetworkConfig: p.networkConfig, + SendBackRawRequest: p.sendBackRawRequest, + SendBackRawResponse: p.sendBackRawResponse, + }, p.logger) + ctx.SetValue(schemas.BifrostContextKeyURLPath, route.Path+":generateContent") + return provider.ChatCompletion(ctx, key, request) +} + +func (p *opencodeProvider) executeGeminiChatStream( + ctx *schemas.BifrostContext, + route resolvedRoute, + postHookRunner schemas.PostHookRunner, + postHookSpanFinalizer func(context.Context), + key schemas.Key, + request *schemas.BifrostChatRequest, +) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + provider := gemini.NewGeminiProvider(&schemas.ProviderConfig{ + NetworkConfig: p.networkConfig, + SendBackRawRequest: p.sendBackRawRequest, + SendBackRawResponse: p.sendBackRawResponse, + }, p.logger) + ctx.SetValue(schemas.BifrostContextKeyURLPath, route.Path+":streamGenerateContent?alt=sse") + return provider.ChatCompletionStream(ctx, postHookRunner, postHookSpanFinalizer, key, request) +} + +func (p *opencodeProvider) executeGeminiResponses( + ctx *schemas.BifrostContext, + route resolvedRoute, + key schemas.Key, + request *schemas.BifrostResponsesRequest, +) (*schemas.BifrostResponsesResponse, *schemas.BifrostError) { + provider := gemini.NewGeminiProvider(&schemas.ProviderConfig{ + NetworkConfig: p.networkConfig, + SendBackRawRequest: p.sendBackRawRequest, + SendBackRawResponse: p.sendBackRawResponse, + }, p.logger) + ctx.SetValue(schemas.BifrostContextKeyURLPath, route.Path+":generateContent") + return provider.Responses(ctx, key, request) +} + +func (p *opencodeProvider) executeGeminiResponsesStream( + ctx *schemas.BifrostContext, + route resolvedRoute, + postHookRunner schemas.PostHookRunner, + postHookSpanFinalizer func(context.Context), + key schemas.Key, + request *schemas.BifrostResponsesRequest, +) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + provider := gemini.NewGeminiProvider(&schemas.ProviderConfig{ + NetworkConfig: p.networkConfig, + SendBackRawRequest: p.sendBackRawRequest, + SendBackRawResponse: p.sendBackRawResponse, + }, p.logger) + ctx.SetValue(schemas.BifrostContextKeyURLPath, route.Path+":streamGenerateContent?alt=sse") + return provider.ResponsesStream(ctx, postHookRunner, postHookSpanFinalizer, key, request) +} diff --git a/core/providers/opencode/openaiadapter.go b/core/providers/opencode/openaiadapter.go new file mode 100644 index 00000000000..b68eca59006 --- /dev/null +++ b/core/providers/opencode/openaiadapter.go @@ -0,0 +1,120 @@ +package opencode + +import ( + "context" + + "github.com/maximhq/bifrost/core/providers/openai" + providerUtils "github.com/maximhq/bifrost/core/providers/utils" + schemas "github.com/maximhq/bifrost/core/schemas" +) + +func (p *opencodeProvider) executeOpenAIChat( + ctx *schemas.BifrostContext, + route resolvedRoute, + key schemas.Key, + request *schemas.BifrostChatRequest, +) (*schemas.BifrostChatResponse, *schemas.BifrostError) { + return openai.HandleOpenAIChatCompletionRequest( + ctx, + p.client, + p.networkConfig.BaseURL+providerUtils.GetPathFromContext(ctx, route.Path), + request, + key, + p.networkConfig.ExtraHeaders, + providerUtils.ShouldSendBackRawRequest(ctx, p.sendBackRawRequest), + providerUtils.ShouldSendBackRawResponse(ctx, p.sendBackRawResponse), + p.GetProviderKey(), + nil, + parseOpencodeError, + p.logger, + ) +} + +func (p *opencodeProvider) executeOpenAIChatStream( + ctx *schemas.BifrostContext, + route resolvedRoute, + postHookRunner schemas.PostHookRunner, + postHookSpanFinalizer func(context.Context), + key schemas.Key, + request *schemas.BifrostChatRequest, +) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + var authHeader map[string]string + if v := key.Value.GetValue(); v != "" { + authHeader = map[string]string{"Authorization": "Bearer " + v} + } + return openai.HandleOpenAIChatCompletionStreaming( + ctx, + p.streamingClient, + p.networkConfig.BaseURL+providerUtils.GetPathFromContext(ctx, route.Path), + request, + authHeader, + p.networkConfig.ExtraHeaders, + p.networkConfig.StreamIdleTimeoutInSeconds, + providerUtils.ShouldSendBackRawRequest(ctx, p.sendBackRawRequest), + providerUtils.ShouldSendBackRawResponse(ctx, p.sendBackRawResponse), + p.providerKey, + postHookRunner, + nil, + nil, + parseOpencodeError, + nil, + nil, + p.logger, + postHookSpanFinalizer, + ) +} + +func (p *opencodeProvider) executeOpenAIResponses( + ctx *schemas.BifrostContext, + route resolvedRoute, + key schemas.Key, + request *schemas.BifrostResponsesRequest, +) (*schemas.BifrostResponsesResponse, *schemas.BifrostError) { + return openai.HandleOpenAIResponsesRequest( + ctx, + p.client, + p.networkConfig.BaseURL+providerUtils.GetPathFromContext(ctx, route.Path), + request, + key, + p.networkConfig.ExtraHeaders, + providerUtils.ShouldSendBackRawRequest(ctx, p.sendBackRawRequest), + providerUtils.ShouldSendBackRawResponse(ctx, p.sendBackRawResponse), + p.GetProviderKey(), + nil, + parseOpencodeError, + p.logger, + ) +} + +func (p *opencodeProvider) executeOpenAIResponsesStream( + ctx *schemas.BifrostContext, + route resolvedRoute, + postHookRunner schemas.PostHookRunner, + postHookSpanFinalizer func(context.Context), + key schemas.Key, + request *schemas.BifrostResponsesRequest, +) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { + var authHeader map[string]string + if v := key.Value.GetValue(); v != "" { + authHeader = map[string]string{"Authorization": "Bearer " + v} + } + return openai.HandleOpenAIResponsesStreaming( + ctx, + p.streamingClient, + p.networkConfig.BaseURL+providerUtils.GetPathFromContext(ctx, route.Path), + request, + authHeader, + p.networkConfig.ExtraHeaders, + p.networkConfig.StreamIdleTimeoutInSeconds, + providerUtils.ShouldSendBackRawRequest(ctx, p.sendBackRawRequest), + providerUtils.ShouldSendBackRawResponse(ctx, p.sendBackRawResponse), + p.GetProviderKey(), + postHookRunner, + nil, + parseOpencodeError, + nil, + nil, + p.logger, + postHookSpanFinalizer, + ) +} diff --git a/core/providers/opencode/opencode.go b/core/providers/opencode/opencode.go index 2bddf26bb0b..467629084c0 100644 --- a/core/providers/opencode/opencode.go +++ b/core/providers/opencode/opencode.go @@ -110,63 +110,83 @@ func (p *opencodeProvider) TextCompletionStream(ctx *schemas.BifrostContext, pos // ChatCompletion performs a chat completion request to the Opencode API. func (p *opencodeProvider) ChatCompletion(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostChatRequest) (*schemas.BifrostChatResponse, *schemas.BifrostError) { - return openai.HandleOpenAIChatCompletionRequest( - ctx, - p.client, - p.networkConfig.BaseURL+providerUtils.GetPathFromContext(ctx, "/v1/chat/completions"), - request, - key, - p.networkConfig.ExtraHeaders, - providerUtils.ShouldSendBackRawRequest(ctx, p.sendBackRawRequest), - providerUtils.ShouldSendBackRawResponse(ctx, p.sendBackRawResponse), - p.GetProviderKey(), - nil, - parseOpencodeError, - p.logger, - ) + route := resolveRoute(p.GetProviderKey(), request.Model) + if err := validateChatRoute(route, request); err != nil { + return nil, err + } + switch route.Adapter { + case adapterOpenAIChat: + return p.executeOpenAIChat(ctx, route, key, request) + case adapterAnthropicMessages: + return p.executeAnthropicChat(ctx, route, key, request) + case adapterGeminiNative: + return p.executeGeminiChat(ctx, route, key, request) + default: + return nil, providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, context.DeadlineExceeded) + } } // ChatCompletionStream performs a streaming chat completion request to the Opencode API. func (p *opencodeProvider) ChatCompletionStream(ctx *schemas.BifrostContext, postHookRunner schemas.PostHookRunner, postHookSpanFinalizer func(context.Context), key schemas.Key, request *schemas.BifrostChatRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { - var authHeader map[string]string - if v := key.Value.GetValue(); v != "" { - authHeader = map[string]string{"Authorization": "Bearer " + v} + route := resolveRoute(p.GetProviderKey(), request.Model) + if err := validateChatRoute(route, request); err != nil { + return nil, err + } + switch route.Adapter { + case adapterOpenAIChat: + return p.executeOpenAIChatStream(ctx, route, postHookRunner, postHookSpanFinalizer, key, request) + case adapterAnthropicMessages: + return p.executeAnthropicChatStream(ctx, route, postHookRunner, postHookSpanFinalizer, key, request) + case adapterGeminiNative: + return p.executeGeminiChatStream(ctx, route, postHookRunner, postHookSpanFinalizer, key, request) + default: + return nil, providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, context.DeadlineExceeded) } - return openai.HandleOpenAIChatCompletionStreaming( - ctx, - p.streamingClient, - p.networkConfig.BaseURL+providerUtils.GetPathFromContext(ctx, "/v1/chat/completions"), - request, - authHeader, - p.networkConfig.ExtraHeaders, - p.networkConfig.StreamIdleTimeoutInSeconds, - providerUtils.ShouldSendBackRawRequest(ctx, p.sendBackRawRequest), - providerUtils.ShouldSendBackRawResponse(ctx, p.sendBackRawResponse), - p.providerKey, - postHookRunner, - nil, - nil, - parseOpencodeError, - nil, - nil, - p.logger, - postHookSpanFinalizer, - ) } // Responses performs a responses request to the Opencode API. func (p *opencodeProvider) Responses(ctx *schemas.BifrostContext, key schemas.Key, request *schemas.BifrostResponsesRequest) (*schemas.BifrostResponsesResponse, *schemas.BifrostError) { - chatResponse, err := p.ChatCompletion(ctx, key, request.ToChatRequest()) - if err != nil { + route := resolveRoute(p.GetProviderKey(), request.Model) + if err := validateResponsesRoute(route, request); err != nil { return nil, err } - return chatResponse.ToBifrostResponsesResponse(), nil + switch route.Adapter { + case adapterOpenAIResponses: + return p.executeOpenAIResponses(ctx, route, key, request) + case adapterOpenAIChat: + chatResponse, err := p.executeOpenAIChat(ctx, route, key, request.ToChatRequest()) + if err != nil { + return nil, err + } + return chatResponse.ToBifrostResponsesResponse(), nil + case adapterAnthropicMessages: + return p.executeAnthropicResponses(ctx, route, key, request) + case adapterGeminiNative: + return p.executeGeminiResponses(ctx, route, key, request) + default: + return nil, providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, context.DeadlineExceeded) + } } // ResponsesStream performs a streaming responses request to the Opencode API. func (p *opencodeProvider) ResponsesStream(ctx *schemas.BifrostContext, postHookRunner schemas.PostHookRunner, postHookSpanFinalizer func(context.Context), key schemas.Key, request *schemas.BifrostResponsesRequest) (chan *schemas.BifrostStreamChunk, *schemas.BifrostError) { - ctx.SetValue(schemas.BifrostContextKeyIsResponsesToChatCompletionFallback, true) - return p.ChatCompletionStream(ctx, postHookRunner, postHookSpanFinalizer, key, request.ToChatRequest()) + route := resolveRoute(p.GetProviderKey(), request.Model) + if err := validateResponsesRoute(route, request); err != nil { + return nil, err + } + switch route.Adapter { + case adapterOpenAIResponses: + return p.executeOpenAIResponsesStream(ctx, route, postHookRunner, postHookSpanFinalizer, key, request) + case adapterOpenAIChat: + ctx.SetValue(schemas.BifrostContextKeyIsResponsesToChatCompletionFallback, true) + return p.executeOpenAIChatStream(ctx, route, postHookRunner, postHookSpanFinalizer, key, request.ToChatRequest()) + case adapterAnthropicMessages: + return p.executeAnthropicResponsesStream(ctx, route, postHookRunner, postHookSpanFinalizer, key, request) + case adapterGeminiNative: + return p.executeGeminiResponsesStream(ctx, route, postHookRunner, postHookSpanFinalizer, key, request) + default: + return nil, providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, context.DeadlineExceeded) + } } // Embedding is not supported by Opencode. diff --git a/core/providers/opencode/routing.go b/core/providers/opencode/routing.go new file mode 100644 index 00000000000..8819f6df0d2 --- /dev/null +++ b/core/providers/opencode/routing.go @@ -0,0 +1,207 @@ +package opencode + +import ( + "strings" + + schemas "github.com/maximhq/bifrost/core/schemas" +) + +type adapterKind string + +const ( + adapterOpenAIResponses adapterKind = "openai_responses" + adapterOpenAIChat adapterKind = "openai_chat" + adapterAnthropicMessages adapterKind = "anthropic_messages" + adapterGeminiNative adapterKind = "gemini_native" +) + +type authStyle string + +const ( + authStyleBearer authStyle = "bearer" + authStyleAnthropicKey authStyle = "anthropic_key" + authStyleGeminiGateway authStyle = "gemini_gateway" +) + +type routeMatchKind string + +const ( + routeMatchExact routeMatchKind = "exact" + routeMatchClass routeMatchKind = "class" + routeMatchDefault routeMatchKind = "default" +) + +type resolvedRoute struct { + Adapter adapterKind + Path string + Auth authStyle + MatchedBy routeMatchKind + ClassPrefix string +} + +type routeSpec struct { + adapter adapterKind + path string + auth authStyle +} + +type classRoute struct { + prefix string + spec routeSpec +} + +var zenExactRoutes = map[string]routeSpec{ + "gpt-5.5": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.5-pro": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.4": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.4-pro": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.4-mini": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.4-nano": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.3-codex": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.3-codex-spark": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.2": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.2-codex": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.1": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.1-codex": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.1-codex-max": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5.1-codex-mini": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5-codex": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "gpt-5-nano": {adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}, + "claude-fable-5": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-opus-4-8": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-opus-4-7": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-opus-4-6": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-opus-4-5": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-opus-4-1": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-sonnet-4-6": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-sonnet-4-5": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-sonnet-4": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-haiku-4-5": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "claude-3-5-haiku": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "qwen3.7-max": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "qwen3.7-plus": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "qwen3.6-plus": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "qwen3.5-plus": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "deepseek-v4-pro": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "deepseek-v4-flash": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "minimax-m2.7": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "minimax-m2.5": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "glm-5.1": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "glm-5": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "kimi-k2.5": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "kimi-k2.6": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "grok-build-0.1": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "big-pickle": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "mimo-v2.5-free": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "north-mini-code-free": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "nemotron-3-ultra-free": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "deepseek-v4-flash-free": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "gemini-3.5-flash": {adapter: adapterGeminiNative, path: "/v1/models/{model}", auth: authStyleGeminiGateway}, + "gemini-3.1-pro": {adapter: adapterGeminiNative, path: "/v1/models/{model}", auth: authStyleGeminiGateway}, + "gemini-3-flash": {adapter: adapterGeminiNative, path: "/v1/models/{model}", auth: authStyleGeminiGateway}, +} + +var goExactRoutes = map[string]routeSpec{ + "glm-5.1": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "glm-5": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "kimi-k2.7": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "kimi-k2.6": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "deepseek-v4-pro": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "deepseek-v4-flash": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "mimo-v2.5": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "mimo-v2.5-pro": {adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}, + "minimax-m3": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "minimax-m2.7": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "minimax-m2.5": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "qwen3.7-max": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "qwen3.7-plus": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, + "qwen3.6-plus": {adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}, +} + +var zenClassRoutes = []classRoute{ + {prefix: "gpt-", spec: routeSpec{adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}}, + {prefix: "claude-", spec: routeSpec{adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}}, + {prefix: "qwen", spec: routeSpec{adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}}, + {prefix: "gemini-", spec: routeSpec{adapter: adapterGeminiNative, path: "/v1/models/{model}", auth: authStyleGeminiGateway}}, + {prefix: "deepseek-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, + {prefix: "minimax-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, + {prefix: "glm-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, + {prefix: "kimi-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, + {prefix: "grok-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, + {prefix: "mimo-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, +} + +var goClassRoutes = []classRoute{ + {prefix: "gpt-", spec: routeSpec{adapter: adapterOpenAIResponses, path: "/v1/responses", auth: authStyleBearer}}, + {prefix: "claude-", spec: routeSpec{adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}}, + {prefix: "gemini-", spec: routeSpec{adapter: adapterGeminiNative, path: "/v1/models/{model}", auth: authStyleGeminiGateway}}, + {prefix: "qwen", spec: routeSpec{adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}}, + {prefix: "minimax-", spec: routeSpec{adapter: adapterAnthropicMessages, path: "/v1/messages", auth: authStyleAnthropicKey}}, + {prefix: "glm-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, + {prefix: "kimi-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, + {prefix: "deepseek-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, + {prefix: "mimo-", spec: routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer}}, +} + +func resolveRoute(providerKey schemas.ModelProvider, modelID string) resolvedRoute { + normalizedModel := strings.TrimSpace(strings.ToLower(modelID)) + if spec, ok := resolveExactRoute(providerKey, normalizedModel); ok { + return buildResolvedRoute(spec, routeMatchExact, "", normalizedModel) + } + if spec, prefix, ok := resolveClassRoute(providerKey, normalizedModel); ok { + return buildResolvedRoute(spec, routeMatchClass, prefix, normalizedModel) + } + return buildResolvedRoute(defaultChatRoute(providerKey), routeMatchDefault, "", normalizedModel) +} + +func resolveExactRoute(providerKey schemas.ModelProvider, modelID string) (routeSpec, bool) { + switch providerKey { + case schemas.OpencodeZen: + spec, ok := zenExactRoutes[modelID] + return spec, ok + case schemas.OpencodeGo: + spec, ok := goExactRoutes[modelID] + return spec, ok + default: + return routeSpec{}, false + } +} + +func resolveClassRoute(providerKey schemas.ModelProvider, modelID string) (routeSpec, string, bool) { + var routes []classRoute + switch providerKey { + case schemas.OpencodeZen: + routes = zenClassRoutes + case schemas.OpencodeGo: + routes = goClassRoutes + default: + return routeSpec{}, "", false + } + + for _, route := range routes { + if strings.HasPrefix(modelID, route.prefix) { + return route.spec, route.prefix, true + } + } + + return routeSpec{}, "", false +} + +func defaultChatRoute(providerKey schemas.ModelProvider) routeSpec { + return routeSpec{adapter: adapterOpenAIChat, path: "/v1/chat/completions", auth: authStyleBearer} +} + +func buildResolvedRoute(spec routeSpec, matchedBy routeMatchKind, classPrefix, modelID string) resolvedRoute { + path := spec.path + if strings.Contains(path, "{model}") { + path = strings.ReplaceAll(path, "{model}", modelID) + } + return resolvedRoute{ + Adapter: spec.adapter, + Path: path, + Auth: spec.auth, + MatchedBy: matchedBy, + ClassPrefix: classPrefix, + } +} diff --git a/core/providers/opencode/routing_test.go b/core/providers/opencode/routing_test.go new file mode 100644 index 00000000000..2556a2f9cd5 --- /dev/null +++ b/core/providers/opencode/routing_test.go @@ -0,0 +1,102 @@ +package opencode + +import ( + "testing" + + schemas "github.com/maximhq/bifrost/core/schemas" +) + +func TestResolveRoute(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + providerKey schemas.ModelProvider + modelID string + wantAdapter adapterKind + wantPath string + wantAuth authStyle + wantMatch routeMatchKind + wantClass string + }{ + { + name: "zen exact responses model", + providerKey: schemas.OpencodeZen, + modelID: "gpt-5-nano", + wantAdapter: adapterOpenAIResponses, + wantPath: "/v1/responses", + wantAuth: authStyleBearer, + wantMatch: routeMatchExact, + }, + { + name: "zen exact anthropic model", + providerKey: schemas.OpencodeZen, + modelID: "claude-haiku-4-5", + wantAdapter: adapterAnthropicMessages, + wantPath: "/v1/messages", + wantAuth: authStyleAnthropicKey, + wantMatch: routeMatchExact, + }, + { + name: "zen exact gemini model", + providerKey: schemas.OpencodeZen, + modelID: "gemini-3-flash", + wantAdapter: adapterGeminiNative, + wantPath: "/v1/models/gemini-3-flash", + wantAuth: authStyleGeminiGateway, + wantMatch: routeMatchExact, + }, + { + name: "go exact anthropic override beats class", + providerKey: schemas.OpencodeGo, + modelID: "minimax-m2.7", + wantAdapter: adapterAnthropicMessages, + wantPath: "/v1/messages", + wantAuth: authStyleAnthropicKey, + wantMatch: routeMatchExact, + }, + { + name: "go class fallback for future qwen", + providerKey: schemas.OpencodeGo, + modelID: "qwen4.1-max", + wantAdapter: adapterAnthropicMessages, + wantPath: "/v1/messages", + wantAuth: authStyleAnthropicKey, + wantMatch: routeMatchClass, + wantClass: "qwen", + }, + { + name: "zen default chat fallback", + providerKey: schemas.OpencodeZen, + modelID: "mystery-model-1", + wantAdapter: adapterOpenAIChat, + wantPath: "/v1/chat/completions", + wantAuth: authStyleBearer, + wantMatch: routeMatchDefault, + }, + } + + for _, tt := range tests { + tc := tt + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + got := resolveRoute(tc.providerKey, tc.modelID) + if got.Adapter != tc.wantAdapter { + t.Fatalf("adapter = %q, want %q", got.Adapter, tc.wantAdapter) + } + if got.Path != tc.wantPath { + t.Fatalf("path = %q, want %q", got.Path, tc.wantPath) + } + if got.Auth != tc.wantAuth { + t.Fatalf("auth = %q, want %q", got.Auth, tc.wantAuth) + } + if got.MatchedBy != tc.wantMatch { + t.Fatalf("matchedBy = %q, want %q", got.MatchedBy, tc.wantMatch) + } + if got.ClassPrefix != tc.wantClass { + t.Fatalf("classPrefix = %q, want %q", got.ClassPrefix, tc.wantClass) + } + }) + } +} diff --git a/core/providers/opencode/types.go b/core/providers/opencode/types.go new file mode 100644 index 00000000000..520c08145df --- /dev/null +++ b/core/providers/opencode/types.go @@ -0,0 +1,9 @@ +package opencode + +import schemas "github.com/maximhq/bifrost/core/schemas" + +type routeExecutionMetadata struct { + Route resolvedRoute + Provider schemas.ModelProvider + ModelID string +} diff --git a/core/providers/opencode/validation.go b/core/providers/opencode/validation.go new file mode 100644 index 00000000000..ce8eaa171e1 --- /dev/null +++ b/core/providers/opencode/validation.go @@ -0,0 +1,45 @@ +package opencode + +import ( + "fmt" + + providerUtils "github.com/maximhq/bifrost/core/providers/utils" + schemas "github.com/maximhq/bifrost/core/schemas" +) + +func validateChatRoute(route resolvedRoute, request *schemas.BifrostChatRequest) *schemas.BifrostError { + if request == nil { + return providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, fmt.Errorf("chat request is nil")) + } + if request.Model == "" { + return providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, fmt.Errorf("chat request model is empty")) + } + switch route.Adapter { + case adapterOpenAIChat, adapterAnthropicMessages, adapterGeminiNative: + return nil + case adapterOpenAIResponses: + return providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, fmt.Errorf("chat completion is not supported for responses-routed model %q", request.Model)) + default: + return providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, fmt.Errorf("unsupported chat route adapter %q", route.Adapter)) + } +} + +func validateResponsesRoute(route resolvedRoute, request *schemas.BifrostResponsesRequest) *schemas.BifrostError { + if request == nil { + return providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, fmt.Errorf("responses request is nil")) + } + if request.Model == "" { + return providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, fmt.Errorf("responses request model is empty")) + } + switch route.Adapter { + case adapterOpenAIResponses, adapterAnthropicMessages, adapterGeminiNative: + return nil + case adapterOpenAIChat: + if len(request.Input) == 0 { + return providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, fmt.Errorf("responses request input is empty")) + } + return nil + default: + return providerUtils.NewBifrostOperationError(schemas.ErrProviderRequestMarshal, fmt.Errorf("unsupported responses route adapter %q", route.Adapter)) + } +}