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
31 changes: 30 additions & 1 deletion core/providers/anthropic/anthropic.go
Original file line number Diff line number Diff line change
Expand Up @@ -887,6 +887,11 @@ func HandleAnthropicChatCompletionStreaming(
// across events and set on the final chunk: fast mode and data residency.
var servedSpeed *string
var servedInferenceGeo *string
// Model that actually served the turn after a server-side fallback handoff.
// Latched like the two above because it appears only on the usage event's
// iterations, and the neutral chat usage drops iterations before pricing —
// so the final chunk's RoutingInfo is the only place it can survive.
var servedFallbackModel *string
// Register the accumulating usage handle so a mid-stream cancel/timeout
// can bill for tokens already processed Mutated in place below;
// the deferred HandleStreamCancellation/Timeout reads it from context.
Expand Down Expand Up @@ -982,6 +987,10 @@ func HandleAnthropicChatCompletionStreaming(
servedInferenceGeo = usageToProcess.InferenceGeo
usage.InferenceGeo = usageToProcess.InferenceGeo
}
if served := usageToProcess.ServerSideFallbackModel(); served != nil {
servedFallbackModel = served
usage.ServerSideFallbackModel = served
}
Comment thread
TejasGhatte marked this conversation as resolved.
Resolved
Comment on lines +990 to +993

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.

P1 Capture fallback model earlier — ServerSideFallbackModel() becomes available only when the terminal message_delta includes usage.iterations. If the stream is cancelled or times out after fallback content starts but before that event is processed, the deferred billing handler snapshots usage while this field is still nil. The partial turn is then priced using the requested model instead of the model that served it. Retain the serving model from metadata available before the terminal usage event so cancellation billing can use it.

// Collect usage information and send at the end of the stream
// Here in some cases usage comes before final message
// So we need to check if the response.Usage is nil and then if usage != nil
Expand Down Expand Up @@ -1150,6 +1159,9 @@ func HandleAnthropicChatCompletionStreaming(
if servedInferenceGeo != nil {
response.InferenceGeo = servedInferenceGeo
}
if servedFallbackModel != nil {
response.ExtraFields.RoutingInfo.ServerSideFallbackModel = servedFallbackModel
}
// Set raw request if enabled
if sendBackRawRequest {
providerUtils.ParseAndSetRawRequest(&response.ExtraFields, jsonBody)
Expand Down Expand Up @@ -1508,6 +1520,10 @@ func HandleAnthropicResponsesStream(
var modelName string
var servedSpeed *string
var servedInferenceGeo *string
// Model that served the turn after a server-side fallback handoff. Latched
// here rather than stamped in the converter: the per-chunk loop below replaces
// ExtraFields wholesale, so anything the converter puts there is discarded.
var servedFallbackModel *string

for {
// If context was cancelled/timed out, let defer handle it
Expand Down Expand Up @@ -1570,6 +1586,12 @@ func HandleAnthropicResponsesStream(
billedUsage.InferenceGeo = usageToProcess.InferenceGeo
}
}
if served := usageToProcess.ServerSideFallbackModel(); served != nil {
servedFallbackModel = served
if billedUsage != nil {
billedUsage.ServerSideFallbackModel = served
}
}
}

responses, bifrostErr, isLastChunk := event.ToBifrostResponsesStream(ctx, chunkIndex, streamState)
Expand Down Expand Up @@ -1634,6 +1656,11 @@ func HandleAnthropicResponsesStream(
if servedInferenceGeo != nil {
response.Response.InferenceGeo = servedInferenceGeo
}
// Applied after the per-chunk ExtraFields reset above, which is
// what makes this survive to the cost calculation.
if servedFallbackModel != nil {
response.ExtraFields.RoutingInfo.ServerSideFallbackModel = servedFallbackModel
}
// Set raw request if enabled
if sendBackRawRequest {
providerUtils.ParseAndSetRawRequest(&response.ExtraFields, jsonBody)
Expand Down Expand Up @@ -2738,6 +2765,8 @@ func (provider *AnthropicProvider) CountTokens(ctx *schemas.BifrostContext, key
request,
AnthropicRequestBuildConfig{
Provider: schemas.Anthropic,
Model: request.Model,
IsCountTokens: true,
IsStreaming: false,
BetaHeaderOverrides: provider.networkConfig.BetaHeaderOverrides,
ShouldSendBackRawRequest: provider.sendBackRawRequest,
Expand Down Expand Up @@ -3058,4 +3087,4 @@ func (provider *AnthropicProvider) PassthroughStream(
},
},
), nil
}
}
4 changes: 4 additions & 0 deletions core/providers/anthropic/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -899,6 +899,10 @@ func (response *AnthropicMessageResponse) ToBifrostChatResponse(ctx *schemas.Bif
Created: int(time.Now().Unix()),
}

// Record the server-side fallback serving model before usage is flattened —
// the neutral chat usage has no iterations to recover it from later.
bifrostResponse.ExtraFields.RoutingInfo.ServerSideFallbackModel = response.Usage.ServerSideFallbackModel()
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

// Check if we have a structured output tool
var structuredOutputToolName string
if ctx != nil {
Expand Down
4 changes: 4 additions & 0 deletions core/providers/anthropic/responses.go
Original file line number Diff line number Diff line change
Expand Up @@ -4065,6 +4065,10 @@ func (response *AnthropicMessageResponse) ToBifrostResponsesResponse(ctx *schema
// Convert usage information using common converter (handles iterations recursively)
bifrostResp.Usage = ConvertAnthropicUsageToBifrostUsage(response.Usage)

// Record the model that actually served the turn when server-side fallback
// handed off mid-request. Routing cannot see this, so pricing reads it here.
bifrostResp.ExtraFields.RoutingInfo.ServerSideFallbackModel = response.Usage.ServerSideFallbackModel()

// Convert content to Responses output messages using the new conversion method
if len(response.Content) > 0 {
// Create a temporary message to use the conversion method
Expand Down
Loading
Loading