Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions .github/workflows/scripts/load-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"
Expand Down Expand Up @@ -242,7 +249,8 @@ create_config() {
{
"name": "mocker-key",
"value": "Bearer mocker-key",
"weight": 1
"weight": 1,
"models": ["*"]
}
],
"network_config": {
Expand All @@ -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
}
}
}
}
Expand Down Expand Up @@ -848,3 +848,4 @@ main() {
}

main "$@"

20 changes: 19 additions & 1 deletion core/bifrost.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -6852,7 +6857,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)
Expand All @@ -6876,6 +6880,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.
Expand Down
70 changes: 70 additions & 0 deletions core/bifrost_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
})
}
84 changes: 84 additions & 0 deletions core/providers/opencode/anthropicadapter.go
Original file line number Diff line number Diff line change
@@ -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
}
31 changes: 31 additions & 0 deletions core/providers/opencode/cachedcontents.go
Original file line number Diff line number Diff line change
@@ -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())
}
63 changes: 63 additions & 0 deletions core/providers/opencode/errors.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading