@langwatch/server 3.1.0-beta.7 → 3.1.0-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -6
- package/packages/server/dist/cli.cjs +23 -17
- package/cmd/service/main.go +0 -68
- package/go.mod +0 -117
- package/go.sum +0 -299
- package/pkg/breaker/breaker.go +0 -157
- package/pkg/breaker/breaker_test.go +0 -131
- package/pkg/clog/LICENSE +0 -26
- package/pkg/clog/clog.go +0 -90
- package/pkg/clog/clog_test.go +0 -56
- package/pkg/clog/panic.go +0 -39
- package/pkg/config/LICENSE +0 -26
- package/pkg/config/config.go +0 -86
- package/pkg/config/config_test.go +0 -70
- package/pkg/config/otel.go +0 -50
- package/pkg/config/server.go +0 -61
- package/pkg/config/validate.go +0 -80
- package/pkg/config/validate_test.go +0 -74
- package/pkg/contexts/contexts_test.go +0 -34
- package/pkg/contexts/request_id.go +0 -1
- package/pkg/contexts/service_info.go +0 -33
- package/pkg/errfuncs/errfuncs.go +0 -9
- package/pkg/errfuncs/errfuncs_test.go +0 -28
- package/pkg/forkedcontext/forkedcontext.go +0 -57
- package/pkg/health/health.go +0 -123
- package/pkg/health/health_test.go +0 -84
- package/pkg/herr/LICENSE +0 -26
- package/pkg/herr/code.go +0 -14
- package/pkg/herr/herr.go +0 -112
- package/pkg/herr/herr_test.go +0 -78
- package/pkg/herr/http.go +0 -133
- package/pkg/herr/http_test.go +0 -103
- package/pkg/herr/validate.go +0 -72
- package/pkg/herr/validate_test.go +0 -75
- package/pkg/httpmiddleware/bearer.go +0 -47
- package/pkg/httpmiddleware/httputil_test.go +0 -167
- package/pkg/httpmiddleware/inflight.go +0 -23
- package/pkg/httpmiddleware/maxbody.go +0 -30
- package/pkg/httpmiddleware/recover.go +0 -38
- package/pkg/httpmiddleware/requestid.go +0 -40
- package/pkg/httpmiddleware/telemetry.go +0 -96
- package/pkg/httpmiddleware/version.go +0 -16
- package/pkg/jwtverify/verifier.go +0 -72
- package/pkg/jwtverify/verifier_test.go +0 -134
- package/pkg/ksuid/LICENSE +0 -26
- package/pkg/ksuid/ksuid.go +0 -157
- package/pkg/ksuid/ksuid_test.go +0 -107
- package/pkg/ksuid/resources.go +0 -13
- package/pkg/lifecycle/group.go +0 -175
- package/pkg/lifecycle/group_test.go +0 -236
- package/pkg/lifecycle/service.go +0 -112
- package/pkg/netprobe/netprobe.go +0 -89
- package/pkg/netprobe/netprobe_test.go +0 -55
- package/pkg/otelsetup/otelsetup.go +0 -226
- package/pkg/otelsetup/otelsetup_test.go +0 -130
- package/pkg/ptr/LICENSE +0 -26
- package/pkg/ptr/ptr.go +0 -34
- package/pkg/ptr/ptr_test.go +0 -66
- package/pkg/retry/bench_test.go +0 -67
- package/pkg/retry/retry.go +0 -188
- package/pkg/retry/retry_test.go +0 -222
- package/pkg/slicefuncs/LICENSE +0 -26
- package/pkg/slicefuncs/slicefuncs.go +0 -10
- package/pkg/slicefuncs/slicefuncs_test.go +0 -29
- package/pkg/stacktrace/LICENSE +0 -26
- package/pkg/stacktrace/frames.go +0 -77
- package/pkg/stacktrace/frames_test.go +0 -73
- package/services/aigateway/BENCHMARKS.md +0 -110
- package/services/aigateway/README.md +0 -156
- package/services/aigateway/adapters/authresolver/bench_test.go +0 -13
- package/services/aigateway/adapters/authresolver/redis.go +0 -61
- package/services/aigateway/adapters/authresolver/service.go +0 -442
- package/services/aigateway/adapters/authresolver/service_test.go +0 -435
- package/services/aigateway/adapters/budget/bench_test.go +0 -50
- package/services/aigateway/adapters/budget/budget.go +0 -59
- package/services/aigateway/adapters/cacherules/evaluator.go +0 -134
- package/services/aigateway/adapters/cacherules/evaluator_test.go +0 -207
- package/services/aigateway/adapters/controlplane/bench_test.go +0 -40
- package/services/aigateway/adapters/controlplane/client.go +0 -213
- package/services/aigateway/adapters/controlplane/client_test.go +0 -73
- package/services/aigateway/adapters/controlplane/config_wire.go +0 -310
- package/services/aigateway/adapters/controlplane/guardrails.go +0 -88
- package/services/aigateway/adapters/controlplane/signer.go +0 -95
- package/services/aigateway/adapters/controlplane/signer_test.go +0 -64
- package/services/aigateway/adapters/customertracebridge/context.go +0 -48
- package/services/aigateway/adapters/customertracebridge/context_test.go +0 -24
- package/services/aigateway/adapters/customertracebridge/emitter.go +0 -329
- package/services/aigateway/adapters/customertracebridge/emitter_test.go +0 -93
- package/services/aigateway/adapters/customertracebridge/registry.go +0 -82
- package/services/aigateway/adapters/customertracebridge/transport.go +0 -122
- package/services/aigateway/adapters/gatewaytracer/attrs.go +0 -28
- package/services/aigateway/adapters/gatewaytracer/attrs_genai.go +0 -24
- package/services/aigateway/adapters/gatewaytracer/headers.go +0 -8
- package/services/aigateway/adapters/gatewaytracer/tracer.go +0 -101
- package/services/aigateway/adapters/httpapi/bench_test.go +0 -83
- package/services/aigateway/adapters/httpapi/middleware.go +0 -123
- package/services/aigateway/adapters/httpapi/router.go +0 -635
- package/services/aigateway/adapters/httpapi/router_test.go +0 -633
- package/services/aigateway/adapters/modelresolver/resolver.go +0 -107
- package/services/aigateway/adapters/modelresolver/resolver_test.go +0 -140
- package/services/aigateway/adapters/policy/matcher.go +0 -250
- package/services/aigateway/adapters/policy/matcher_test.go +0 -124
- package/services/aigateway/adapters/providers/bifrost.go +0 -798
- package/services/aigateway/adapters/providers/bifrost_parser.go +0 -201
- package/services/aigateway/adapters/providers/bifrost_test.go +0 -181
- package/services/aigateway/adapters/ratelimit/limiter.go +0 -122
- package/services/aigateway/adapters/ratelimit/limiter_test.go +0 -81
- package/services/aigateway/app/app.go +0 -104
- package/services/aigateway/app/dispatch.go +0 -89
- package/services/aigateway/app/dispatch_test.go +0 -475
- package/services/aigateway/app/handlers.go +0 -79
- package/services/aigateway/app/peek_bench_test.go +0 -21
- package/services/aigateway/app/pipeline/bench_test.go +0 -34
- package/services/aigateway/app/pipeline/budget.go +0 -55
- package/services/aigateway/app/pipeline/cache.go +0 -34
- package/services/aigateway/app/pipeline/cachecontrol.go +0 -86
- package/services/aigateway/app/pipeline/cachecontrol_test.go +0 -110
- package/services/aigateway/app/pipeline/guardrail.go +0 -121
- package/services/aigateway/app/pipeline/pipeline.go +0 -159
- package/services/aigateway/app/pipeline/policy.go +0 -23
- package/services/aigateway/app/pipeline/ratelimit.go +0 -21
- package/services/aigateway/app/pipeline/rawframing_test.go +0 -67
- package/services/aigateway/app/pipeline/resolve.go +0 -44
- package/services/aigateway/app/pipeline/trace.go +0 -129
- package/services/aigateway/app/ports.go +0 -61
- package/services/aigateway/cmd/root.go +0 -42
- package/services/aigateway/config.go +0 -86
- package/services/aigateway/deps.go +0 -177
- package/services/aigateway/domain/bundle.go +0 -203
- package/services/aigateway/domain/errors.go +0 -23
- package/services/aigateway/domain/model.go +0 -24
- package/services/aigateway/domain/provider.go +0 -38
- package/services/aigateway/domain/request.go +0 -65
- package/services/aigateway/domain/response.go +0 -56
- package/services/aigateway/domain/verdict.go +0 -55
- package/services/aigateway/serve.go +0 -45
- package/services/aigateway/tests/matrix/README.md +0 -71
- package/services/aigateway/tests/matrix/anthropic_test.go +0 -61
- package/services/aigateway/tests/matrix/azure_test.go +0 -52
- package/services/aigateway/tests/matrix/bedrock_test.go +0 -69
- package/services/aigateway/tests/matrix/gemini_test.go +0 -117
- package/services/aigateway/tests/matrix/matrix_test.go +0 -601
- package/services/aigateway/tests/matrix/openai_test.go +0 -66
- package/services/aigateway/tests/matrix/vertex_test.go +0 -160
|
@@ -1,798 +0,0 @@
|
|
|
1
|
-
// Package providers wraps bifrost as the provider dispatch engine.
|
|
2
|
-
// All AI providers (OpenAI, Anthropic, Azure, Bedrock, Vertex, Gemini)
|
|
3
|
-
// are handled by a single bifrost instance. Per-request credentials
|
|
4
|
-
// come from context via the Account interface.
|
|
5
|
-
package providers
|
|
6
|
-
|
|
7
|
-
import (
|
|
8
|
-
"bytes"
|
|
9
|
-
"context"
|
|
10
|
-
"encoding/json"
|
|
11
|
-
"fmt"
|
|
12
|
-
"net/http"
|
|
13
|
-
"os"
|
|
14
|
-
"strings"
|
|
15
|
-
"time"
|
|
16
|
-
|
|
17
|
-
"github.com/tidwall/gjson"
|
|
18
|
-
|
|
19
|
-
"github.com/bytedance/sonic"
|
|
20
|
-
bifrost "github.com/maximhq/bifrost/core"
|
|
21
|
-
bfschemas "github.com/maximhq/bifrost/core/schemas"
|
|
22
|
-
"go.uber.org/zap"
|
|
23
|
-
|
|
24
|
-
"github.com/langwatch/langwatch/pkg/herr"
|
|
25
|
-
"github.com/langwatch/langwatch/services/aigateway/domain"
|
|
26
|
-
)
|
|
27
|
-
|
|
28
|
-
// BifrostRouter dispatches requests through bifrost.
|
|
29
|
-
// Implements app.ProviderRouter.
|
|
30
|
-
type BifrostRouter struct {
|
|
31
|
-
bf *bifrost.Bifrost
|
|
32
|
-
logger *zap.Logger
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
// BifrostOptions configures the bifrost router.
|
|
36
|
-
type BifrostOptions struct {
|
|
37
|
-
Logger *zap.Logger
|
|
38
|
-
InitialPoolSize int
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
// NewBifrostRouter creates a provider router backed by bifrost.
|
|
42
|
-
func NewBifrostRouter(ctx context.Context, opts BifrostOptions) (*BifrostRouter, error) {
|
|
43
|
-
pool := opts.InitialPoolSize
|
|
44
|
-
if pool <= 0 {
|
|
45
|
-
pool = 1000
|
|
46
|
-
}
|
|
47
|
-
bf, err := bifrost.Init(ctx, bfschemas.BifrostConfig{
|
|
48
|
-
Account: &account{},
|
|
49
|
-
InitialPoolSize: pool,
|
|
50
|
-
Logger: &bifrostLogger{logger: opts.Logger},
|
|
51
|
-
})
|
|
52
|
-
if err != nil {
|
|
53
|
-
return nil, fmt.Errorf("bifrost init: %w", err)
|
|
54
|
-
}
|
|
55
|
-
return &BifrostRouter{bf: bf, logger: opts.Logger}, nil
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// Dispatch sends a non-streaming request through bifrost.
|
|
59
|
-
//
|
|
60
|
-
// For /v1/chat/completions (RequestTypeChat) the inbound body is
|
|
61
|
-
// OpenAI-shape; we parse it into Bifrost's normalized
|
|
62
|
-
// (Input, Params) pair and Bifrost translates to the provider's native
|
|
63
|
-
// wire format (Anthropic Messages API, Gemini generateContent, etc.)
|
|
64
|
-
// + un-normalizes the response back to OpenAI shape.
|
|
65
|
-
//
|
|
66
|
-
// For /v1/messages (RequestTypeMessages) the inbound body is already
|
|
67
|
-
// provider-native (Anthropic /v1/messages shape). Running it through
|
|
68
|
-
// the OpenAI parser would silently drop Anthropic-specific fields like
|
|
69
|
-
// `thinking`, so we opt into Bifrost's raw-forward mode and let it
|
|
70
|
-
// passthrough. Downstream VKs for `/v1/messages` are expected to route
|
|
71
|
-
// to an Anthropic-family provider; sending it to OpenAI is a caller
|
|
72
|
-
// error and Bifrost/OpenAI will reject accordingly.
|
|
73
|
-
func (r *BifrostRouter) Dispatch(ctx context.Context, req *domain.Request, cred domain.Credential) (*domain.Response, error) {
|
|
74
|
-
provider := mapProvider(cred.ProviderID)
|
|
75
|
-
model := req.Model
|
|
76
|
-
if req.Resolved != nil {
|
|
77
|
-
model = req.Resolved.ModelID
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
if req.Type == domain.RequestTypeResponses {
|
|
81
|
-
return r.dispatchResponses(ctx, req, provider, model, cred)
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
if req.Type == domain.RequestTypePassthrough {
|
|
85
|
-
return r.dispatchPassthrough(ctx, req, provider, model, cred)
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
bfReq, dispatchCtx, err := buildChatRequest(ctx, req, provider, model)
|
|
89
|
-
if err != nil {
|
|
90
|
-
return nil, err
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
bfCtx := bfschemas.NewBifrostContext(withCredential(dispatchCtx, cred), time.Time{})
|
|
94
|
-
|
|
95
|
-
resp, berr := r.bf.ChatCompletionRequest(bfCtx, bfReq)
|
|
96
|
-
if berr != nil {
|
|
97
|
-
// Raw-forward paths (/v1/messages, OpenAI-compat chat) ask Bifrost
|
|
98
|
-
// to retain the provider's native response bytes on the error —
|
|
99
|
-
// prefer those over the generic 504 provider_timeout mask when
|
|
100
|
-
// present. Clients like claude-code / OpenAI SDK need the real
|
|
101
|
-
// provider error envelope (rate-limit hints, overload signals,
|
|
102
|
-
// billing errors) to surface correctly.
|
|
103
|
-
if rawBody, status, ok := rawResponseFromBifrostError(berr); ok {
|
|
104
|
-
return &domain.Response{
|
|
105
|
-
Body: rawBody,
|
|
106
|
-
StatusCode: status,
|
|
107
|
-
}, nil
|
|
108
|
-
}
|
|
109
|
-
return nil, classifyBifrostError(ctx, berr)
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
// /v1/messages callers (Anthropic SDK, claude-code, ...) expect the
|
|
113
|
-
// provider's native response shape — not Bifrost's OpenAI-normalized
|
|
114
|
-
// BifrostChatResponse. When the raw-forward branch captured
|
|
115
|
-
// ExtraFields.RawResponse (SendBackRawResponse=true in the context),
|
|
116
|
-
// return those bytes verbatim instead of re-marshaling the normalized
|
|
117
|
-
// struct. OpenAI-compat chat-completions callers keep the normalized
|
|
118
|
-
// shape.
|
|
119
|
-
if req.Type == domain.RequestTypeMessages {
|
|
120
|
-
if rawBody, ok := rawResponseBytes(resp); ok {
|
|
121
|
-
return &domain.Response{
|
|
122
|
-
Body: rawBody,
|
|
123
|
-
StatusCode: http.StatusOK,
|
|
124
|
-
Usage: extractUsage(resp),
|
|
125
|
-
}, nil
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
body, _ := sonic.Marshal(resp)
|
|
130
|
-
return &domain.Response{
|
|
131
|
-
Body: body,
|
|
132
|
-
StatusCode: http.StatusOK,
|
|
133
|
-
Usage: extractUsage(resp),
|
|
134
|
-
}, nil
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
// dispatchResponses routes /v1/responses traffic through Bifrost's
|
|
138
|
-
// ResponsesRequest endpoint. The body is raw-forwarded — Bifrost's
|
|
139
|
-
// provider adapters (currently OpenAI + Azure) decode the native shape
|
|
140
|
-
// themselves. No need to normalize through the chat-completions parser.
|
|
141
|
-
func (r *BifrostRouter) dispatchResponses(
|
|
142
|
-
ctx context.Context,
|
|
143
|
-
req *domain.Request,
|
|
144
|
-
provider bfschemas.ModelProvider,
|
|
145
|
-
model string,
|
|
146
|
-
cred domain.Credential,
|
|
147
|
-
) (*domain.Response, error) {
|
|
148
|
-
bfReq := &bfschemas.BifrostResponsesRequest{
|
|
149
|
-
Provider: provider,
|
|
150
|
-
Model: model,
|
|
151
|
-
RawRequestBody: req.Body,
|
|
152
|
-
// Empty-slice (not nil) stub lets us bypass Bifrost's
|
|
153
|
-
// makeResponsesRequest non-nil-Input guard at bifrost.go:778.
|
|
154
|
-
// On the raw-forward path the provider adapter reads
|
|
155
|
-
// req.RawRequestBody directly; Input is not consulted.
|
|
156
|
-
Input: []bfschemas.ResponsesMessage{},
|
|
157
|
-
}
|
|
158
|
-
bfCtx := bfschemas.NewBifrostContext(rawForwardCtx(withCredential(ctx, cred)), time.Time{})
|
|
159
|
-
|
|
160
|
-
resp, berr := r.bf.ResponsesRequest(bfCtx, bfReq)
|
|
161
|
-
if berr != nil {
|
|
162
|
-
if rawBody, status, ok := rawResponseFromBifrostError(berr); ok {
|
|
163
|
-
return &domain.Response{
|
|
164
|
-
Body: rawBody,
|
|
165
|
-
StatusCode: status,
|
|
166
|
-
}, nil
|
|
167
|
-
}
|
|
168
|
-
return nil, classifyBifrostError(ctx, berr)
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
// Prefer the provider's native response bytes so /v1/responses
|
|
172
|
-
// clients (codex, OpenAI Responses SDK, ...) see the exact wire
|
|
173
|
-
// frames the provider emitted. Falls back to the normalized
|
|
174
|
-
// BifrostResponsesResponse marshal if RawResponse is absent.
|
|
175
|
-
if rawBody, ok := rawResponseBytesResp(resp); ok {
|
|
176
|
-
return &domain.Response{
|
|
177
|
-
Body: rawBody,
|
|
178
|
-
StatusCode: http.StatusOK,
|
|
179
|
-
Usage: extractResponsesUsage(resp),
|
|
180
|
-
}, nil
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
body, _ := sonic.Marshal(resp)
|
|
184
|
-
return &domain.Response{
|
|
185
|
-
Body: body,
|
|
186
|
-
StatusCode: http.StatusOK,
|
|
187
|
-
Usage: extractResponsesUsage(resp),
|
|
188
|
-
}, nil
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
// DispatchStream sends a streaming request through bifrost. Routing
|
|
192
|
-
// semantics match Dispatch (translate on RequestTypeChat, raw-forward
|
|
193
|
-
// on RequestTypeMessages). Chunks returned by Bifrost are
|
|
194
|
-
// BifrostChatResponse (OpenAI-compatible), so the SSE bytes the gateway
|
|
195
|
-
// emits downstream are the shape the OpenAI SDK expects regardless of
|
|
196
|
-
// which provider Bifrost routed to.
|
|
197
|
-
func (r *BifrostRouter) DispatchStream(ctx context.Context, req *domain.Request, cred domain.Credential) (domain.StreamIterator, error) {
|
|
198
|
-
provider := mapProvider(cred.ProviderID)
|
|
199
|
-
model := req.Model
|
|
200
|
-
if req.Resolved != nil {
|
|
201
|
-
model = req.Resolved.ModelID
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
if req.Type == domain.RequestTypeResponses {
|
|
205
|
-
return r.dispatchResponsesStream(ctx, req, provider, model, cred)
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
if req.Type == domain.RequestTypePassthrough {
|
|
209
|
-
return r.dispatchPassthroughStream(ctx, req, provider, model, cred)
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
if req.Type == domain.RequestTypeChat && isOpenAICompatibleProvider(provider) {
|
|
213
|
-
req.Body = ensureStreamIncludeUsage(req.Body)
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
bfReq, dispatchCtx, err := buildChatRequest(ctx, req, provider, model)
|
|
217
|
-
if err != nil {
|
|
218
|
-
return nil, err
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
bfCtx := bfschemas.NewBifrostContext(withCredential(dispatchCtx, cred), time.Time{})
|
|
222
|
-
|
|
223
|
-
ch, berr := r.bf.ChatCompletionStreamRequest(bfCtx, bfReq)
|
|
224
|
-
if berr != nil {
|
|
225
|
-
return nil, classifyBifrostError(ctx, berr)
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
return &bifrostStreamIterator{ch: ch}, nil
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
// dispatchResponsesStream is the streaming sibling of dispatchResponses.
|
|
232
|
-
// Bifrost emits Responses-API-specific SSE event frames
|
|
233
|
-
// (response.created, response.output_item.added, response.output_text.delta,
|
|
234
|
-
// response.completed, ...); the gateway forwards each chunk's serialized
|
|
235
|
-
// BifrostResponsesResponse verbatim — clients using the OpenAI Responses
|
|
236
|
-
// SDK see the shape they expect.
|
|
237
|
-
func (r *BifrostRouter) dispatchResponsesStream(
|
|
238
|
-
ctx context.Context,
|
|
239
|
-
req *domain.Request,
|
|
240
|
-
provider bfschemas.ModelProvider,
|
|
241
|
-
model string,
|
|
242
|
-
cred domain.Credential,
|
|
243
|
-
) (domain.StreamIterator, error) {
|
|
244
|
-
bfReq := &bfschemas.BifrostResponsesRequest{
|
|
245
|
-
Provider: provider,
|
|
246
|
-
Model: model,
|
|
247
|
-
RawRequestBody: req.Body,
|
|
248
|
-
// Empty-slice (not nil) stub lets us bypass Bifrost's
|
|
249
|
-
// makeResponsesRequest non-nil-Input guard at bifrost.go:778.
|
|
250
|
-
// On the raw-forward path the provider adapter reads
|
|
251
|
-
// req.RawRequestBody directly; Input is not consulted.
|
|
252
|
-
Input: []bfschemas.ResponsesMessage{},
|
|
253
|
-
}
|
|
254
|
-
bfCtx := bfschemas.NewBifrostContext(rawForwardCtx(withCredential(ctx, cred)), time.Time{})
|
|
255
|
-
|
|
256
|
-
ch, berr := r.bf.ResponsesStreamRequest(bfCtx, bfReq)
|
|
257
|
-
if berr != nil {
|
|
258
|
-
return nil, classifyBifrostError(ctx, berr)
|
|
259
|
-
}
|
|
260
|
-
return &bifrostStreamIterator{ch: ch}, nil
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
// dispatchPassthrough routes /v1beta/models/... (Gemini-native shape,
|
|
264
|
-
// consumed by gemini-cli and the @google/genai SDK) through Bifrost's
|
|
265
|
-
// Passthrough endpoint. The request body is forwarded verbatim; Bifrost
|
|
266
|
-
// only rewrites auth (x-goog-api-key) and base URL. Response is the raw
|
|
267
|
-
// upstream body with preserved status + headers, suitable for clients
|
|
268
|
-
// that expect Google's native generateContent response shape.
|
|
269
|
-
func (r *BifrostRouter) dispatchPassthrough(
|
|
270
|
-
ctx context.Context,
|
|
271
|
-
req *domain.Request,
|
|
272
|
-
provider bfschemas.ModelProvider,
|
|
273
|
-
model string,
|
|
274
|
-
cred domain.Credential,
|
|
275
|
-
) (*domain.Response, error) {
|
|
276
|
-
bfReq := passthroughRequest(req, model)
|
|
277
|
-
bfCtx := bfschemas.NewBifrostContext(withCredential(ctx, cred), time.Time{})
|
|
278
|
-
|
|
279
|
-
resp, berr := r.bf.Passthrough(bfCtx, provider, bfReq)
|
|
280
|
-
if berr != nil {
|
|
281
|
-
if rawBody, status, ok := rawResponseFromBifrostError(berr); ok {
|
|
282
|
-
return &domain.Response{
|
|
283
|
-
Body: rawBody,
|
|
284
|
-
StatusCode: status,
|
|
285
|
-
}, nil
|
|
286
|
-
}
|
|
287
|
-
return nil, classifyBifrostError(ctx, berr)
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
status := resp.StatusCode
|
|
291
|
-
if status == 0 {
|
|
292
|
-
status = http.StatusOK
|
|
293
|
-
}
|
|
294
|
-
out := &domain.Response{
|
|
295
|
-
Body: resp.Body,
|
|
296
|
-
StatusCode: status,
|
|
297
|
-
Headers: passthroughResponseHeaders(resp.Headers),
|
|
298
|
-
}
|
|
299
|
-
// Cost-enrichment downstream needs prompt/completion token counts on
|
|
300
|
-
// the customer span. Bifrost's Passthrough adapter returns raw bytes
|
|
301
|
-
// without a typed Usage struct, so extract Gemini's `usageMetadata`
|
|
302
|
-
// here. Sibling logic in the stream iterator parses the same shape
|
|
303
|
-
// per-chunk; this branch handles the synchronous :generateContent
|
|
304
|
-
// (non-streaming) response.
|
|
305
|
-
if u, ok := parseGeminiPassthroughUsage(resp.Body); ok {
|
|
306
|
-
out.Usage = u
|
|
307
|
-
}
|
|
308
|
-
return out, nil
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
// dispatchPassthroughStream is the streaming sibling of dispatchPassthrough.
|
|
312
|
-
// Bifrost returns chunks whose Body is the raw SSE bytes emitted by the
|
|
313
|
-
// upstream (Google's streamGenerateContent already yields proper
|
|
314
|
-
// `event:/data:` framing); the iterator emits them unchanged so
|
|
315
|
-
// gemini-cli / @google/genai see the exact wire format they expect.
|
|
316
|
-
func (r *BifrostRouter) dispatchPassthroughStream(
|
|
317
|
-
ctx context.Context,
|
|
318
|
-
req *domain.Request,
|
|
319
|
-
provider bfschemas.ModelProvider,
|
|
320
|
-
model string,
|
|
321
|
-
cred domain.Credential,
|
|
322
|
-
) (domain.StreamIterator, error) {
|
|
323
|
-
bfReq := passthroughRequest(req, model)
|
|
324
|
-
bfCtx := bfschemas.NewBifrostContext(withCredential(ctx, cred), time.Time{})
|
|
325
|
-
|
|
326
|
-
ch, berr := r.bf.PassthroughStream(bfCtx, provider, bfReq)
|
|
327
|
-
if berr != nil {
|
|
328
|
-
return nil, classifyBifrostError(ctx, berr)
|
|
329
|
-
}
|
|
330
|
-
return &bifrostStreamIterator{ch: ch, rawFraming: true}, nil
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
// passthroughRequest builds the Bifrost-side passthrough request from
|
|
334
|
-
// our domain.Request. Body, method, path, query, and forwarded client
|
|
335
|
-
// headers are carried verbatim; model + provider drive key selection.
|
|
336
|
-
func passthroughRequest(req *domain.Request, model string) *bfschemas.BifrostPassthroughRequest {
|
|
337
|
-
p := req.Passthrough
|
|
338
|
-
return &bfschemas.BifrostPassthroughRequest{
|
|
339
|
-
Model: model,
|
|
340
|
-
Method: p.Method,
|
|
341
|
-
Path: p.Path,
|
|
342
|
-
RawQuery: p.RawQuery,
|
|
343
|
-
Body: req.Body,
|
|
344
|
-
SafeHeaders: p.Headers,
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
// passthroughResponseHeaders returns headers safe to forward to the
|
|
349
|
-
// client. Content-Length and Content-Encoding are dropped since the
|
|
350
|
-
// body we forward may differ in framing from what the upstream sent.
|
|
351
|
-
func passthroughResponseHeaders(in map[string]string) map[string]string {
|
|
352
|
-
if len(in) == 0 {
|
|
353
|
-
return nil
|
|
354
|
-
}
|
|
355
|
-
out := make(map[string]string, len(in))
|
|
356
|
-
for k, v := range in {
|
|
357
|
-
switch {
|
|
358
|
-
case strings.EqualFold(k, "Content-Length"),
|
|
359
|
-
strings.EqualFold(k, "Content-Encoding"):
|
|
360
|
-
continue
|
|
361
|
-
default:
|
|
362
|
-
out[k] = v
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
return out
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
// rawForwardCtx enriches a context with both Bifrost flags the
|
|
369
|
-
// raw-forward code path needs: UseRawRequestBody sends the inbound
|
|
370
|
-
// bytes unchanged to the provider adapter; SendBackRawResponse attaches
|
|
371
|
-
// the provider's native response bytes to ExtraFields.RawResponse so
|
|
372
|
-
// the gateway can emit them verbatim downstream.
|
|
373
|
-
func rawForwardCtx(ctx context.Context) context.Context {
|
|
374
|
-
ctx = context.WithValue(ctx, bfschemas.BifrostContextKeyUseRawRequestBody, true)
|
|
375
|
-
ctx = context.WithValue(ctx, bfschemas.BifrostContextKeySendBackRawResponse, true)
|
|
376
|
-
return ctx
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
// rawResponseBytes extracts the provider's native chat-completion
|
|
380
|
-
// response bytes from BifrostResponseExtraFields.RawResponse. Bifrost
|
|
381
|
-
// populates this only when BifrostContextKeySendBackRawResponse is set
|
|
382
|
-
// on the dispatch context (see rawForwardCtx). Returns (nil, false) if
|
|
383
|
-
// the response or raw payload is absent.
|
|
384
|
-
func rawResponseBytes(resp *bfschemas.BifrostChatResponse) ([]byte, bool) {
|
|
385
|
-
if resp == nil {
|
|
386
|
-
return nil, false
|
|
387
|
-
}
|
|
388
|
-
return extractRawResponseBytes(resp.ExtraFields.RawResponse)
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
// rawResponseBytesResp is the Responses-API sibling of rawResponseBytes.
|
|
392
|
-
func rawResponseBytesResp(resp *bfschemas.BifrostResponsesResponse) ([]byte, bool) {
|
|
393
|
-
if resp == nil {
|
|
394
|
-
return nil, false
|
|
395
|
-
}
|
|
396
|
-
return extractRawResponseBytes(resp.ExtraFields.RawResponse)
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
// extractRawResponseBytes normalises the various concrete types
|
|
400
|
-
// Bifrost may stash into ExtraFields.RawResponse (typed `interface{}`)
|
|
401
|
-
// into a []byte suitable for writing to the HTTP response.
|
|
402
|
-
//
|
|
403
|
-
// Bifrost's providers/utils EnrichError stores RawResponse as
|
|
404
|
-
// json.RawMessage (a distinct type from []byte in Go's type switch,
|
|
405
|
-
// so we must match it explicitly before the generic []byte branch).
|
|
406
|
-
func extractRawResponseBytes(raw interface{}) ([]byte, bool) {
|
|
407
|
-
switch v := raw.(type) {
|
|
408
|
-
case nil:
|
|
409
|
-
return nil, false
|
|
410
|
-
case json.RawMessage:
|
|
411
|
-
if len(v) == 0 {
|
|
412
|
-
return nil, false
|
|
413
|
-
}
|
|
414
|
-
return []byte(v), true
|
|
415
|
-
case []byte:
|
|
416
|
-
if len(v) == 0 {
|
|
417
|
-
return nil, false
|
|
418
|
-
}
|
|
419
|
-
return v, true
|
|
420
|
-
case string:
|
|
421
|
-
if v == "" {
|
|
422
|
-
return nil, false
|
|
423
|
-
}
|
|
424
|
-
return []byte(v), true
|
|
425
|
-
default:
|
|
426
|
-
b, err := sonic.Marshal(raw)
|
|
427
|
-
if err != nil || len(b) == 0 {
|
|
428
|
-
return nil, false
|
|
429
|
-
}
|
|
430
|
-
return b, true
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
// rawResponseFromBifrostError peels the provider's native response bytes
|
|
435
|
-
// off a BifrostError — populated by Bifrost when the dispatch context
|
|
436
|
-
// carries BifrostContextKeySendBackRawResponse=true (raw-forward paths).
|
|
437
|
-
// Lets the gateway pass through Anthropic / OpenAI / etc. error
|
|
438
|
-
// envelopes verbatim instead of masking them as a generic 504
|
|
439
|
-
// provider_timeout, which is what clients like claude-code / codex
|
|
440
|
-
// expect to parse (rate-limit hints, overload signals, billing errors
|
|
441
|
-
// etc. ride in the provider-native error shape).
|
|
442
|
-
func rawResponseFromBifrostError(berr *bfschemas.BifrostError) ([]byte, int, bool) {
|
|
443
|
-
if berr == nil {
|
|
444
|
-
return nil, 0, false
|
|
445
|
-
}
|
|
446
|
-
body, ok := extractRawResponseBytes(berr.ExtraFields.RawResponse)
|
|
447
|
-
if !ok {
|
|
448
|
-
return nil, 0, false
|
|
449
|
-
}
|
|
450
|
-
status := http.StatusBadGateway
|
|
451
|
-
if berr.StatusCode != nil && *berr.StatusCode > 0 {
|
|
452
|
-
status = *berr.StatusCode
|
|
453
|
-
}
|
|
454
|
-
return body, status, true
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
// ListModels returns an empty list — model discovery is VK-config-driven.
|
|
458
|
-
func (r *BifrostRouter) ListModels(_ context.Context, _ []domain.Credential) ([]domain.Model, error) {
|
|
459
|
-
return nil, nil
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
// --- Bifrost Account (multi-tenant credential provider) ---
|
|
463
|
-
|
|
464
|
-
type credCtxKey struct{}
|
|
465
|
-
|
|
466
|
-
func withCredential(ctx context.Context, cred domain.Credential) context.Context {
|
|
467
|
-
return context.WithValue(ctx, credCtxKey{}, cred)
|
|
468
|
-
}
|
|
469
|
-
|
|
470
|
-
func credentialFromContext(ctx context.Context) domain.Credential {
|
|
471
|
-
if v, ok := ctx.Value(credCtxKey{}).(domain.Credential); ok {
|
|
472
|
-
return v
|
|
473
|
-
}
|
|
474
|
-
return domain.Credential{}
|
|
475
|
-
}
|
|
476
|
-
|
|
477
|
-
// account implements bfschemas.Account for multi-tenant credential dispatch.
|
|
478
|
-
type account struct{}
|
|
479
|
-
|
|
480
|
-
func (a *account) GetConfiguredProviders() ([]bfschemas.ModelProvider, error) {
|
|
481
|
-
return bfschemas.StandardProviders, nil
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
func (a *account) GetKeysForProvider(ctx context.Context, provider bfschemas.ModelProvider) ([]bfschemas.Key, error) {
|
|
485
|
-
cred := credentialFromContext(ctx)
|
|
486
|
-
if cred.ID == "" {
|
|
487
|
-
return nil, fmt.Errorf("no credential on context for provider %s", provider)
|
|
488
|
-
}
|
|
489
|
-
key := credentialToBifrostKey(cred, provider)
|
|
490
|
-
return []bfschemas.Key{key}, nil
|
|
491
|
-
}
|
|
492
|
-
|
|
493
|
-
func (a *account) GetConfigForProvider(provider bfschemas.ModelProvider) (*bfschemas.ProviderConfig, error) {
|
|
494
|
-
cfg := &bfschemas.ProviderConfig{}
|
|
495
|
-
if proxyURL := os.Getenv("LW_GATEWAY_OUTBOUND_PROXY"); proxyURL != "" {
|
|
496
|
-
// Debug-only: route outbound provider traffic through an HTTP proxy
|
|
497
|
-
// (e.g. `http://localhost:8888` for mitmproxy). Lets operators
|
|
498
|
-
// capture the exact request Bifrost sends to provider APIs —
|
|
499
|
-
// unblocks outbound-delta diagnosis (headers, body) when a
|
|
500
|
-
// provider-side behavior (e.g. Anthropic cache) fires on direct
|
|
501
|
-
// curl but not through the gateway. Do NOT set in production.
|
|
502
|
-
cfg.ProxyConfig = &bfschemas.ProxyConfig{
|
|
503
|
-
Type: bfschemas.HTTPProxy,
|
|
504
|
-
URL: proxyURL,
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
cfg.CheckAndSetDefaults()
|
|
508
|
-
return cfg, nil
|
|
509
|
-
}
|
|
510
|
-
|
|
511
|
-
// credentialToBifrostKey converts a domain.Credential into bifrost's Key format.
|
|
512
|
-
func credentialToBifrostKey(cred domain.Credential, provider bfschemas.ModelProvider) bfschemas.Key {
|
|
513
|
-
k := bfschemas.Key{
|
|
514
|
-
ID: cred.ID,
|
|
515
|
-
Name: cred.ID,
|
|
516
|
-
Weight: 1,
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
switch provider {
|
|
520
|
-
case bfschemas.Azure:
|
|
521
|
-
k.Value = envVar(cred.APIKey)
|
|
522
|
-
endpoint := cred.Extra["endpoint"]
|
|
523
|
-
cfg := &bfschemas.AzureKeyConfig{
|
|
524
|
-
Endpoint: envVar(endpoint),
|
|
525
|
-
Deployments: cred.DeploymentMap,
|
|
526
|
-
}
|
|
527
|
-
if apiVersion, ok := cred.Extra["api_version"]; ok {
|
|
528
|
-
v := envVar(apiVersion)
|
|
529
|
-
cfg.APIVersion = &v
|
|
530
|
-
}
|
|
531
|
-
k.AzureKeyConfig = cfg
|
|
532
|
-
|
|
533
|
-
case bfschemas.Bedrock:
|
|
534
|
-
cfg := &bfschemas.BedrockKeyConfig{
|
|
535
|
-
AccessKey: envVar(cred.Extra["access_key"]),
|
|
536
|
-
SecretKey: envVar(cred.Extra["secret_key"]),
|
|
537
|
-
Deployments: cred.DeploymentMap,
|
|
538
|
-
}
|
|
539
|
-
if st, ok := cred.Extra["session_token"]; ok && st != "" {
|
|
540
|
-
v := envVar(st)
|
|
541
|
-
cfg.SessionToken = &v
|
|
542
|
-
}
|
|
543
|
-
if region, ok := cred.Extra["region"]; ok && region != "" {
|
|
544
|
-
v := envVar(region)
|
|
545
|
-
cfg.Region = &v
|
|
546
|
-
}
|
|
547
|
-
k.BedrockKeyConfig = cfg
|
|
548
|
-
|
|
549
|
-
case bfschemas.Vertex:
|
|
550
|
-
k.VertexKeyConfig = &bfschemas.VertexKeyConfig{
|
|
551
|
-
ProjectID: envVar(cred.Extra["project_id"]),
|
|
552
|
-
ProjectNumber: envVar(cred.Extra["project_number"]),
|
|
553
|
-
Region: envVar(cred.Extra["region"]),
|
|
554
|
-
AuthCredentials: envVar(cred.Extra["auth_credentials"]),
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
default:
|
|
558
|
-
// OpenAI, Anthropic, Gemini, etc. — plain API key.
|
|
559
|
-
k.Value = envVar(cred.APIKey)
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
return k
|
|
563
|
-
}
|
|
564
|
-
|
|
565
|
-
func envVar(v string) bfschemas.EnvVar {
|
|
566
|
-
return bfschemas.EnvVar{Val: v, FromEnv: false}
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
// --- Provider mapping ---
|
|
570
|
-
|
|
571
|
-
func mapProvider(id domain.ProviderID) bfschemas.ModelProvider {
|
|
572
|
-
switch id {
|
|
573
|
-
case domain.ProviderAzure:
|
|
574
|
-
return bfschemas.Azure
|
|
575
|
-
case domain.ProviderBedrock:
|
|
576
|
-
return bfschemas.Bedrock
|
|
577
|
-
case domain.ProviderVertex:
|
|
578
|
-
return bfschemas.Vertex
|
|
579
|
-
case domain.ProviderGemini:
|
|
580
|
-
return bfschemas.Gemini
|
|
581
|
-
case domain.ProviderAnthropic:
|
|
582
|
-
return bfschemas.Anthropic
|
|
583
|
-
default:
|
|
584
|
-
return bfschemas.ModelProvider(string(id))
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
|
|
588
|
-
// --- Error classification ---
|
|
589
|
-
|
|
590
|
-
func classifyBifrostError(ctx context.Context, berr *bfschemas.BifrostError) error {
|
|
591
|
-
status := 0
|
|
592
|
-
if berr.StatusCode != nil {
|
|
593
|
-
status = *berr.StatusCode
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
code := domain.ErrProviderError
|
|
597
|
-
switch status {
|
|
598
|
-
case http.StatusTooManyRequests:
|
|
599
|
-
code = domain.ErrRateLimited
|
|
600
|
-
case http.StatusGatewayTimeout, 0:
|
|
601
|
-
code = domain.ErrProviderTimeout
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
return herr.New(ctx, code, herr.M{
|
|
605
|
-
"status": status,
|
|
606
|
-
"message": bfErrorMsg(berr),
|
|
607
|
-
})
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
func bfErrorMsg(e *bfschemas.BifrostError) string {
|
|
611
|
-
if e == nil {
|
|
612
|
-
return ""
|
|
613
|
-
}
|
|
614
|
-
if e.Error != nil {
|
|
615
|
-
return e.Error.Message
|
|
616
|
-
}
|
|
617
|
-
return fmt.Sprintf("bifrost error (status %v)", e.StatusCode)
|
|
618
|
-
}
|
|
619
|
-
|
|
620
|
-
// --- Usage extraction ---
|
|
621
|
-
|
|
622
|
-
func extractUsage(resp *bfschemas.BifrostChatResponse) domain.Usage {
|
|
623
|
-
if resp == nil || resp.Usage == nil {
|
|
624
|
-
return domain.Usage{}
|
|
625
|
-
}
|
|
626
|
-
return domain.Usage{
|
|
627
|
-
PromptTokens: resp.Usage.PromptTokens,
|
|
628
|
-
CompletionTokens: resp.Usage.CompletionTokens,
|
|
629
|
-
TotalTokens: resp.Usage.TotalTokens,
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
|
|
633
|
-
// extractResponsesUsage maps the Responses-API usage block onto the
|
|
634
|
-
// gateway's neutral domain.Usage. The Responses API uses
|
|
635
|
-
// input/output/total_tokens (not prompt/completion) — same numeric
|
|
636
|
-
// content, different names.
|
|
637
|
-
func extractResponsesUsage(resp *bfschemas.BifrostResponsesResponse) domain.Usage {
|
|
638
|
-
if resp == nil || resp.Usage == nil {
|
|
639
|
-
return domain.Usage{}
|
|
640
|
-
}
|
|
641
|
-
return domain.Usage{
|
|
642
|
-
PromptTokens: resp.Usage.InputTokens,
|
|
643
|
-
CompletionTokens: resp.Usage.OutputTokens,
|
|
644
|
-
TotalTokens: resp.Usage.TotalTokens,
|
|
645
|
-
}
|
|
646
|
-
}
|
|
647
|
-
|
|
648
|
-
// --- Stream iterator ---
|
|
649
|
-
|
|
650
|
-
type bifrostStreamIterator struct {
|
|
651
|
-
ch chan *bfschemas.BifrostStreamChunk
|
|
652
|
-
current []byte
|
|
653
|
-
usage domain.Usage
|
|
654
|
-
err error
|
|
655
|
-
done bool
|
|
656
|
-
// rawFraming is set on passthrough streams where each chunk.Body is
|
|
657
|
-
// already formatted SSE bytes from the upstream (Gemini streamGenerateContent
|
|
658
|
-
// yields proper `event:/data:` framing). Router.writeSSE inspects this
|
|
659
|
-
// to skip the default `data: <chunk>\n\n` re-wrap.
|
|
660
|
-
rawFraming bool
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
func (it *bifrostStreamIterator) Next(ctx context.Context) bool {
|
|
664
|
-
if it.done {
|
|
665
|
-
return false
|
|
666
|
-
}
|
|
667
|
-
select {
|
|
668
|
-
case <-ctx.Done():
|
|
669
|
-
it.err = ctx.Err()
|
|
670
|
-
it.done = true
|
|
671
|
-
return false
|
|
672
|
-
case chunk, ok := <-it.ch:
|
|
673
|
-
if !ok {
|
|
674
|
-
it.done = true
|
|
675
|
-
return false
|
|
676
|
-
}
|
|
677
|
-
if chunk.BifrostError != nil {
|
|
678
|
-
it.err = fmt.Errorf("stream error: %s", bfErrorMsg(chunk.BifrostError))
|
|
679
|
-
it.done = true
|
|
680
|
-
return false
|
|
681
|
-
}
|
|
682
|
-
if chunk.BifrostChatResponse != nil {
|
|
683
|
-
data, _ := sonic.Marshal(chunk.BifrostChatResponse)
|
|
684
|
-
it.current = data
|
|
685
|
-
if chunk.BifrostChatResponse.Usage != nil {
|
|
686
|
-
u := chunk.BifrostChatResponse.Usage
|
|
687
|
-
it.usage = domain.Usage{
|
|
688
|
-
PromptTokens: u.PromptTokens,
|
|
689
|
-
CompletionTokens: u.CompletionTokens,
|
|
690
|
-
TotalTokens: u.TotalTokens,
|
|
691
|
-
}
|
|
692
|
-
}
|
|
693
|
-
} else if chunk.BifrostResponsesStreamResponse != nil {
|
|
694
|
-
// Responses API stream frames (response.created /
|
|
695
|
-
// response.output_text.delta / response.completed / ...).
|
|
696
|
-
// Marshal verbatim — clients using the OpenAI Responses SDK
|
|
697
|
-
// decode these by `type`. Final usage appears on the
|
|
698
|
-
// response.completed event's nested Response object.
|
|
699
|
-
data, _ := sonic.Marshal(chunk.BifrostResponsesStreamResponse)
|
|
700
|
-
it.current = data
|
|
701
|
-
//nolint:staticcheck // explicit embedded-field reference matches the parallel branches above for readability.
|
|
702
|
-
if resp := chunk.BifrostResponsesStreamResponse.Response; resp != nil && resp.Usage != nil {
|
|
703
|
-
u := resp.Usage
|
|
704
|
-
it.usage = domain.Usage{
|
|
705
|
-
PromptTokens: u.InputTokens,
|
|
706
|
-
CompletionTokens: u.OutputTokens,
|
|
707
|
-
TotalTokens: u.TotalTokens,
|
|
708
|
-
}
|
|
709
|
-
}
|
|
710
|
-
} else if chunk.BifrostPassthroughResponse != nil {
|
|
711
|
-
// Passthrough stream chunks carry the raw upstream bytes
|
|
712
|
-
// (Gemini streamGenerateContent already emits proper
|
|
713
|
-
// `event:/data:` SSE framing). Forward verbatim — the
|
|
714
|
-
// writer side knows not to re-wrap when rawFraming is set.
|
|
715
|
-
//nolint:staticcheck // explicit embedded-field reference matches the parallel branches above for readability.
|
|
716
|
-
it.current = chunk.BifrostPassthroughResponse.Body
|
|
717
|
-
// Parse Gemini-native usageMetadata out of the chunk body so
|
|
718
|
-
// the trace wrapper can stamp prompt/completion/cached
|
|
719
|
-
// tokens on the customer span. Bifrost's Passthrough adapter
|
|
720
|
-
// doesn't emit a typed Usage struct on these chunks (raw
|
|
721
|
-
// passthrough by design), so we crack the JSON here. Each
|
|
722
|
-
// non-final chunk omits usageMetadata; we keep the last
|
|
723
|
-
// non-zero values seen so the iterator's Usage() reports
|
|
724
|
-
// the FINAL token totals at stream close.
|
|
725
|
-
//nolint:staticcheck // explicit embedded-field reference matches the parallel branches above for readability.
|
|
726
|
-
if u, ok := parseGeminiPassthroughUsage(chunk.BifrostPassthroughResponse.Body); ok {
|
|
727
|
-
it.usage = u
|
|
728
|
-
}
|
|
729
|
-
}
|
|
730
|
-
return true
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
|
|
734
|
-
// parseGeminiPassthroughUsage extracts Gemini's `usageMetadata` block from a
|
|
735
|
-
// raw streamGenerateContent SSE chunk body. Lines have the form
|
|
736
|
-
//
|
|
737
|
-
// data: {"candidates":[…],"usageMetadata":{…},"modelVersion":"…"}\n\n
|
|
738
|
-
//
|
|
739
|
-
// gjson tolerates the `data: ` prefix because we strip leading non-JSON
|
|
740
|
-
// bytes before searching. Returns (Usage{}, false) when the chunk doesn't
|
|
741
|
-
// carry usageMetadata (intermediate chunks); the iterator keeps its prior
|
|
742
|
-
// last-seen value so the FINAL chunk's totals win.
|
|
743
|
-
func parseGeminiPassthroughUsage(body []byte) (domain.Usage, bool) {
|
|
744
|
-
if len(body) == 0 {
|
|
745
|
-
return domain.Usage{}, false
|
|
746
|
-
}
|
|
747
|
-
// Strip leading `data: ` framing if present so gjson can parse the
|
|
748
|
-
// embedded JSON object directly.
|
|
749
|
-
scan := body
|
|
750
|
-
if i := bytes.IndexByte(scan, '{'); i > 0 {
|
|
751
|
-
scan = scan[i:]
|
|
752
|
-
}
|
|
753
|
-
usage := gjson.GetBytes(scan, "usageMetadata")
|
|
754
|
-
if !usage.Exists() {
|
|
755
|
-
return domain.Usage{}, false
|
|
756
|
-
}
|
|
757
|
-
prompt := int(usage.Get("promptTokenCount").Int())
|
|
758
|
-
completion := int(usage.Get("candidatesTokenCount").Int())
|
|
759
|
-
total := int(usage.Get("totalTokenCount").Int())
|
|
760
|
-
if prompt == 0 && completion == 0 && total == 0 {
|
|
761
|
-
return domain.Usage{}, false
|
|
762
|
-
}
|
|
763
|
-
if total == 0 {
|
|
764
|
-
total = prompt + completion
|
|
765
|
-
}
|
|
766
|
-
// Note: cachedContentTokenCount (when present) is folded into prompt
|
|
767
|
-
// tokens upstream by Gemini; the trace pipeline derives cache_read
|
|
768
|
-
// from a separate gen_ai.usage.cache_read attr, not from total.
|
|
769
|
-
return domain.Usage{
|
|
770
|
-
PromptTokens: prompt,
|
|
771
|
-
CompletionTokens: completion,
|
|
772
|
-
TotalTokens: total,
|
|
773
|
-
}, true
|
|
774
|
-
}
|
|
775
|
-
|
|
776
|
-
func (it *bifrostStreamIterator) RawFraming() bool { return it.rawFraming }
|
|
777
|
-
|
|
778
|
-
func (it *bifrostStreamIterator) Chunk() []byte { return it.current }
|
|
779
|
-
func (it *bifrostStreamIterator) Usage() domain.Usage { return it.usage }
|
|
780
|
-
func (it *bifrostStreamIterator) Err() error { return it.err }
|
|
781
|
-
func (it *bifrostStreamIterator) Close() error { return nil }
|
|
782
|
-
|
|
783
|
-
// --- Bifrost logger adapter ---
|
|
784
|
-
|
|
785
|
-
type bifrostLogger struct {
|
|
786
|
-
logger *zap.Logger
|
|
787
|
-
}
|
|
788
|
-
|
|
789
|
-
func (l *bifrostLogger) Debug(msg string, args ...any) { l.logger.Debug(fmt.Sprintf(msg, args...)) }
|
|
790
|
-
func (l *bifrostLogger) Info(msg string, args ...any) { l.logger.Info(fmt.Sprintf(msg, args...)) }
|
|
791
|
-
func (l *bifrostLogger) Warn(msg string, args ...any) { l.logger.Warn(fmt.Sprintf(msg, args...)) }
|
|
792
|
-
func (l *bifrostLogger) Error(msg string, args ...any) { l.logger.Error(fmt.Sprintf(msg, args...)) }
|
|
793
|
-
func (l *bifrostLogger) Fatal(msg string, args ...any) { l.logger.Fatal(fmt.Sprintf(msg, args...)) }
|
|
794
|
-
func (l *bifrostLogger) SetLevel(_ bfschemas.LogLevel) {}
|
|
795
|
-
func (l *bifrostLogger) SetOutputType(_ bfschemas.LoggerOutputType) {}
|
|
796
|
-
func (l *bifrostLogger) LogHTTPRequest(_ bfschemas.LogLevel, _ string) bfschemas.LogEventBuilder {
|
|
797
|
-
return bfschemas.NoopLogEvent
|
|
798
|
-
}
|