Skip to content
Closed
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
5 changes: 4 additions & 1 deletion core/providers/anthropic.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,10 @@ func (provider *AnthropicProvider) completeRequest(ctx context.Context, requestB
req.SetRequestURI(url)
req.Header.SetMethod(http.MethodPost)
req.Header.SetContentType("application/json")
req.Header.Set("x-api-key", key)
// Can be empty in case of passthrough
if key != "" {
req.Header.Set("x-api-key", key)
}
req.Header.Set("anthropic-version", provider.apiVersion)

req.SetBody(jsonData)
Expand Down
119 changes: 92 additions & 27 deletions transports/bifrost-http/integrations/anthropic.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"strconv"
"strings"

bifrost "github.com/maximhq/bifrost/core"
"github.com/maximhq/bifrost/core/schemas"
Expand All @@ -18,33 +19,42 @@ type AnthropicRouter struct {
*GenericRouter
}

// CreateAnthropicRouteConfigs creates route configurations for Anthropic endpoints.
func CreateAnthropicRouteConfigs(pathPrefix string) []RouteConfig {
return []RouteConfig{
{
Type: RouteConfigTypeAnthropic,
Path: pathPrefix + "/v1/complete",
Method: "POST",
GetRequestTypeInstance: func() interface{} {
return &anthropic.AnthropicTextRequest{}
},
RequestConverter: func(req interface{}) (*schemas.BifrostRequest, error) {
if anthropicReq, ok := req.(*anthropic.AnthropicTextRequest); ok {
return &schemas.BifrostRequest{
TextCompletionRequest: anthropicReq.ToBifrostTextCompletionRequest(),
}, nil
}
return nil, errors.New("invalid request type")
},
TextResponseConverter: func(resp *schemas.BifrostTextCompletionResponse) (interface{}, error) {
return anthropic.ToAnthropicTextCompletionResponse(resp), nil
},
ErrorConverter: func(err *schemas.BifrostError) interface{} {
return anthropic.ToAnthropicChatCompletionError(err)
},
// createAnthropicCompleteRouteConfig creates a route configuration for the `/v1/complete` endpoint.
func createAnthropicCompleteRouteConfig(pathPrefix string) RouteConfig {
return RouteConfig{
Type: RouteConfigTypeAnthropic,
Path: pathPrefix + "/v1/complete",
Method: "POST",
GetRequestTypeInstance: func() interface{} {
return &anthropic.AnthropicTextRequest{}
},
{
Path: pathPrefix + "/v1/messages",
RequestConverter: func(req interface{}) (*schemas.BifrostRequest, error) {
if anthropicReq, ok := req.(*anthropic.AnthropicTextRequest); ok {
return &schemas.BifrostRequest{
TextCompletionRequest: anthropicReq.ToBifrostTextCompletionRequest(),
}, nil
}
return nil, errors.New("invalid request type")
},
TextResponseConverter: func(resp *schemas.BifrostTextCompletionResponse) (interface{}, error) {
return anthropic.ToAnthropicTextCompletionResponse(resp), nil
},
ErrorConverter: func(err *schemas.BifrostError) interface{} {
return anthropic.ToAnthropicChatCompletionError(err)
},
}
}

// createAnthropicMessagesRouteConfig creates a route configuration for the `/v1/messages` endpoint.
func createAnthropicMessagesRouteConfig(pathPrefix string) []RouteConfig {
var routes []RouteConfig
for _, path := range []string{
"/v1/messages",
"/v1/messages/{path:*}",
} {
routes = append(routes, RouteConfig{
Type: RouteConfigTypeAnthropic,
Path: pathPrefix + path,
Method: "POST",
GetRequestTypeInstance: func() interface{} {
return &anthropic.AnthropicMessageRequest{}
Expand All @@ -71,8 +81,17 @@ func CreateAnthropicRouteConfigs(pathPrefix string) []RouteConfig {
return anthropic.ToAnthropicResponsesStreamError(err)
},
},
},
PreCallback: checkAnthropicPassthrough,
})
}
return routes
}

// CreateAnthropicRouteConfigs creates route configurations for Anthropic endpoints.
func CreateAnthropicRouteConfigs(pathPrefix string) []RouteConfig {
return append([]RouteConfig{
createAnthropicCompleteRouteConfig(pathPrefix),
}, createAnthropicMessagesRouteConfig(pathPrefix)...)
}

func CreateAnthropicListModelsRouteConfigs(pathPrefix string, handlerStore lib.HandlerStore) []RouteConfig {
Expand Down Expand Up @@ -103,6 +122,52 @@ func CreateAnthropicListModelsRouteConfigs(pathPrefix string, handlerStore lib.H
}
}

// checkAnthropicPassthrough pre-callback checks if the request is for a claude model.
// If it is, it attaches the raw request body for direct use by the provider.
// It also checks for anthropic oauth headers and sets the bifrost context.
func checkAnthropicPassthrough(ctx *fasthttp.RequestCtx, bifrostCtx *context.Context, req interface{}, rawBody []byte) error {
var provider schemas.ModelProvider
var model string

switch r := req.(type) {
case *anthropic.AnthropicTextRequest:
provider, model = schemas.ParseModelString(r.Model, "")
// Check if model parameter explicitly has `anthropic/` prefix
if after, ok := strings.CutPrefix(model, "anthropic/"); ok {
r.Model = after
}

case *anthropic.AnthropicMessageRequest:
provider, model = schemas.ParseModelString(r.Model, "")
// Check if model parameter explicitly has `anthropic/` prefix
if after, ok := strings.CutPrefix(model, "anthropic/"); ok {
r.Model = after
}
}

Comment on lines +133 to +147

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Prefix trimming never executes

schemas.ParseModelString already strips the provider prefix from model, so this CutPrefix guard is always false and r.Model keeps values like anthropic/claude-3.5-sonnet. Those provider-qualified names are forwarded unchanged and Anthropic rejects them. Trim r.Model directly (and keep the local model variable in sync) so passthrough requests receive the bare model name they expect.

-		if after, ok := strings.CutPrefix(model, "anthropic/"); ok {
-			r.Model = after
+		if after, ok := strings.CutPrefix(r.Model, "anthropic/"); ok {
+			r.Model = after
+			model = after
		}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
case *anthropic.AnthropicTextRequest:
provider, model = schemas.ParseModelString(r.Model, "")
// Check if model parameter explicitly has `anthropic/` prefix
if after, ok := strings.CutPrefix(model, "anthropic/"); ok {
r.Model = after
}
case *anthropic.AnthropicMessageRequest:
provider, model = schemas.ParseModelString(r.Model, "")
// Check if model parameter explicitly has `anthropic/` prefix
if after, ok := strings.CutPrefix(model, "anthropic/"); ok {
r.Model = after
}
}
case *anthropic.AnthropicTextRequest:
provider, model = schemas.ParseModelString(r.Model, "")
// Check if model parameter explicitly has `anthropic/` prefix
if after, ok := strings.CutPrefix(r.Model, "anthropic/"); ok {
r.Model = after
model = after
}
case *anthropic.AnthropicMessageRequest:
provider, model = schemas.ParseModelString(r.Model, "")
// Check if model parameter explicitly has `anthropic/` prefix
if after, ok := strings.CutPrefix(r.Model, "anthropic/"); ok {
r.Model = after
model = after
}
}
🤖 Prompt for AI Agents
In transports/bifrost-http/integrations/anthropic.go around lines 133 to 147,
the current CutPrefix check never runs because schemas.ParseModelString already
removed the provider prefix; as a result r.Model can remain as "anthropic/..."
and be forwarded to Anthropic. Fix by trimming the "anthropic/" prefix directly
on r.Model (e.g. use strings.CutPrefix on r.Model and set r.Model = after when
ok) and then update the local model variable to match (model = r.Model) in both
the AnthropicTextRequest and AnthropicMessageRequest cases so passthrough
requests send the bare model name.

if !strings.Contains(model, "claude") || (provider != schemas.Anthropic && provider != "") {
// Not a Claude model or not an Anthropic model, so we can continue
return nil
}

// Check if anthropic oauth headers are present
if !isAnthropicAPIKeyAuth(ctx) {
headers := extractHeadersFromRequest(ctx)
url := extractExactPath(ctx)
if !strings.HasPrefix(url, "/") {
url = "/" + url
}

*bifrostCtx = context.WithValue(*bifrostCtx, schemas.BifrostContextKeyExtraHeaders, headers)
*bifrostCtx = context.WithValue(*bifrostCtx, schemas.BifrostContextKeyURLPath, url)
*bifrostCtx = context.WithValue(*bifrostCtx, schemas.BifrostContextKeySkipKeySelection, true)
}

// Set the request body in the context
*bifrostCtx = context.WithValue(*bifrostCtx, schemas.BifrostContextKeyRequestBody, rawBody)
return nil
}

// extractAnthropicListModelsParams extracts query parameters for list models request
func extractAnthropicListModelsParams(ctx *fasthttp.RequestCtx, bifrostCtx *context.Context, req interface{}, rawBody []byte) error {
if listModelsReq, ok := req.(*schemas.BifrostListModelsRequest); ok {
Expand Down
24 changes: 22 additions & 2 deletions transports/bifrost-http/integrations/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"log"
"reflect"
"strings"

"github.com/bytedance/sonic"
"github.com/maximhq/bifrost/core/schemas"
Expand Down Expand Up @@ -86,13 +87,13 @@ func extractHeadersFromRequest(ctx *fasthttp.RequestCtx) map[string][]string {
return headers
}

// getExactPath returns the request path *after* the integration prefix,
// extractExactPath returns the request path *after* the integration prefix,
// preserving the original query string exactly as sent by the client.
//
// Example:
//
// /openai/v1/chat/completions?model=gpt-4o -> /chat/completions?model=gpt-4o
func getExactPath(ctx *fasthttp.RequestCtx) string {
func extractExactPath(ctx *fasthttp.RequestCtx) string {
// ctx.Path() returns only the path (no query) as a []byte backed by fasthttp’s internal buffers.
// Treat it as read-only; don’t append to it directly.
path := ctx.Path() // e.g. "/openai/v1/chat/completions"
Expand Down Expand Up @@ -299,3 +300,22 @@ func (g *GenericRouter) extractFallbacksFromRequest(req interface{}) ([]string,

return nil, nil
}

// isAnthropicAPIKeyAuth checks if the request uses standard API key authentication.
// Returns true for API key auth (x-api-key header), false for OAuth (Bearer sk-ant-oat*).
// This is required for Claude Code specifically, which may use OAuth authentication.
// Default behavior is to assume API mode when neither x-api-key nor OAuth token is present.
func isAnthropicAPIKeyAuth(ctx *fasthttp.RequestCtx) bool {
// If x-api-key header is present - this is definitely API mode
if apiKey := string(ctx.Request.Header.Peek("x-api-key")); apiKey != "" {
return true
}
// Check for OAuth token in Authorization header
if authHeader := string(ctx.Request.Header.Peek("Authorization")); authHeader != "" {
if strings.HasPrefix(strings.ToLower(authHeader), "bearer sk-ant-oat") {
return false // OAuth mode, NOT API
}
}
// Default to API mode
return true
}