Skip to content
Merged
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
1 change: 1 addition & 0 deletions core/changelog.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
- fix: forward OpenCode Responses requests directly to /v1/responses [@mohammadrezwankhan](https://github.com/mohammadrezwankhan)
- fix: preserve max_tokens for OpenCode-compatible chat endpoints [@Alex-wangyang](https://github.com/Alex-wangyang)
- fix: stop treating HuggingFace as a provider that omits the `[DONE]` marker - it does send one, and listing it as not sending one made the shared OpenAI streaming loop `break` on the first `finish_reason`, discarding the trailing usage-only chunk (`choices: []` plus top-level `usage`) that several router inference providers emit after it. Those streams completed with zero tokens and therefore zero cost, while non-streaming calls to the same models priced correctly [@elliottrabac](https://github.com/elliottrabac)
- fix: default `stream_options.include_usage` on HuggingFace chat streaming - the shared OpenAI streaming handler sets it on its own request path but returns early when a provider supplies a custom request converter, so HuggingFace never sent it. Several router inference providers then omit the terminal usage chunk (and Together nests usage under `choices[]` for some models, which the shared accumulator does not read), so streams completed with zero tokens and therefore zero cost while non-streaming calls on the same models priced correctly. An explicit `stream_options` from the caller still wins [@elliottrabac](https://github.com/elliottrabac)
Expand Down
42 changes: 35 additions & 7 deletions core/providers/opencode/opencode.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,17 +154,45 @@ func (p *opencodeProvider) ChatCompletionStream(ctx *schemas.BifrostContext, pos

// 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
return openai.HandleOpenAIResponsesRequest(
ctx,
p.client,
p.networkConfig.BaseURL+providerUtils.GetPathFromContext(ctx, "/v1/responses"),
request,
openai.BearerAuthHeader(key),
p.networkConfig.ExtraHeaders,
providerUtils.ShouldSendBackRawRequest(ctx, p.sendBackRawRequest),
providerUtils.ShouldSendBackRawResponse(ctx, p.sendBackRawResponse),
p.providerKey,
nil,
parseOpencodeError,
nil,
p.logger,
)
}

// 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())
return openai.HandleOpenAIResponsesStreaming(
ctx,
p.streamingClient,
p.networkConfig.BaseURL+providerUtils.GetPathFromContext(ctx, "/v1/responses"),
request,
openai.BearerAuthHeader(key),
p.networkConfig.ExtraHeaders,
p.networkConfig.StreamIdleTimeoutInSeconds,
providerUtils.ShouldSendBackRawRequest(ctx, p.sendBackRawRequest),
providerUtils.ShouldSendBackRawResponse(ctx, p.sendBackRawResponse),
p.providerKey,
postHookRunner,
nil,
parseOpencodeError,
nil,
nil,
nil,
p.logger,
postHookSpanFinalizer,
)
}

// Embedding is not supported by Opencode.
Expand Down
165 changes: 165 additions & 0 deletions core/providers/opencode/opencode_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
package opencode

import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"

"github.com/maximhq/bifrost/core/schemas"
)
Expand Down Expand Up @@ -287,3 +295,160 @@ func TestOpencodeUnsupportedOperations(t *testing.T) {
}
}
}

// TestOpencodeResponsesRouting verifies that Zen and Go providers forward both
// regular and streaming Responses calls to their native OpenAI-compatible endpoint.
func TestOpencodeResponsesRouting(t *testing.T) {
const (
model = "opencode-test-model"
apiKey = "opencode-test-key"
inputText = "exercise native responses routing"
)

for _, tc := range []struct {
name string
providerKey schemas.ModelProvider
newProvider func(*schemas.ProviderConfig) (*opencodeProvider, error)
}{
{name: "Zen", providerKey: schemas.OpencodeZen, newProvider: func(config *schemas.ProviderConfig) (*opencodeProvider, error) {
return NewOpencodeZenProvider(config, nil)
}},
{name: "Go", providerKey: schemas.OpencodeGo, newProvider: func(config *schemas.ProviderConfig) (*opencodeProvider, error) {
return NewOpencodeGoProvider(config, nil)
}},
} {
t.Run(tc.name, func(t *testing.T) {
type capturedRequest struct {
method string
path string
authorization string
body map[string]any
}

var (
mu sync.Mutex
captures []capturedRequest
)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

mu.Lock()
captures = append(captures, capturedRequest{
method: r.Method,
path: r.URL.Path,
authorization: r.Header.Get("Authorization"),
body: payload,
})
mu.Unlock()

if streaming, _ := payload["stream"].(bool); streaming {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = fmt.Fprint(w, "data: {\"type\":\"response.completed\",\"sequence_number\":1,\"response\":{\"id\":\"resp_stream\",\"object\":\"response\",\"model\":\"opencode-test-model\",\"output\":[]}}\n\n")
if flusher, ok := w.(http.Flusher); ok {
flusher.Flush()
}
return
}

w.Header().Set("Content-Type", "application/json")
_, _ = fmt.Fprint(w, `{"id":"resp_regular","object":"response","model":"opencode-test-model","output":[]}`)
}))
defer server.Close()

provider, err := tc.newProvider(&schemas.ProviderConfig{
NetworkConfig: schemas.NetworkConfig{
BaseURL: server.URL,
DefaultRequestTimeoutInSeconds: 10,
},
})
if err != nil {
t.Fatalf("new provider: %v", err)
}

newRequest := func() *schemas.BifrostResponsesRequest {
return &schemas.BifrostResponsesRequest{
Provider: tc.providerKey,
Model: model,
Input: []schemas.ResponsesMessage{{
Role: schemas.Ptr(schemas.ResponsesInputMessageRoleUser),
Content: &schemas.ResponsesMessageContent{ContentStr: schemas.Ptr(inputText)},
}},
}
}
key := schemas.Key{Value: *schemas.NewSecretVar(apiKey)}

ctx, cancel := schemas.NewBifrostContextWithTimeout(context.Background(), 10*time.Second)
defer cancel()
response, bifrostErr := provider.Responses(ctx, key, newRequest())
if bifrostErr != nil {
t.Fatalf("Responses: %v", bifrostErr)
}
if response == nil || response.ID == nil || *response.ID != "resp_regular" {
t.Fatalf("Responses returned %#v, want response id resp_regular", response)
}

streamCtx, streamCancel := schemas.NewBifrostContextWithTimeout(context.Background(), 10*time.Second)
defer streamCancel()
postHookRunner := func(_ *schemas.BifrostContext, result *schemas.BifrostResponse, _ *schemas.BifrostError) (*schemas.BifrostResponse, *schemas.BifrostError) {
return result, nil
}
stream, bifrostErr := provider.ResponsesStream(streamCtx, postHookRunner, nil, key, newRequest())
if bifrostErr != nil {
t.Fatalf("ResponsesStream: %v", bifrostErr)
}
streamed := false
for chunk := range stream {
if chunk != nil {
streamed = true
}
}
if !streamed {
t.Fatal("ResponsesStream completed without emitting a response chunk")
}

mu.Lock()
defer mu.Unlock()
if len(captures) != 2 {
t.Fatalf("upstream request count = %d, want 2", len(captures))
}
seenRegular, seenStreaming := false, false
for _, capture := range captures {
if capture.method != http.MethodPost {
t.Errorf("request method = %q, want %q", capture.method, http.MethodPost)
}
if capture.path != "/v1/responses" {
t.Errorf("request path = %q, want /v1/responses", capture.path)
}
if capture.authorization != "Bearer "+apiKey {
t.Errorf("Authorization = %q, want %q", capture.authorization, "Bearer "+apiKey)
}
if gotModel, _ := capture.body["model"].(string); gotModel != model {
t.Errorf("request model = %q, want %q", gotModel, model)
}
input, ok := capture.body["input"].([]any)
if !ok || len(input) != 1 {
t.Errorf("request input = %#v, want one message", capture.body["input"])
}

if streaming, _ := capture.body["stream"].(bool); streaming {
seenStreaming = true
} else {
seenRegular = true
}
}
if !seenRegular || !seenStreaming {
t.Errorf("saw regular=%t streaming=%t requests, want both", seenRegular, seenStreaming)
}
})
}
}