Repository navigation
feat(go-models): migrate batch 6 model drivers to unified usage recording - #17775
Conversation
…ding Relate to infiniflow#17284. Completes the migration of the four non-OpenAI-compatible model drivers (anthropic, cohere, google, bedrock) onto the shared usage-recording path. Earlier batches (infiniflow#17634, infiniflow#17643, infiniflow#17696-infiniflow#17700) covered only the OpenAI-compatible cluster; these four providers ship wire formats that do not fit the OpenAI choices[0].delta / usage block template and so were left for a separate pass. Per the maintainer's guidance for this batch, each driver is migrated on its own terms rather than forced through a single template. The shared machinery used is intentionally small: recordResponseUsage, parseChatCompletionResponse, BaseModel.newJSONPostRequest, and the existing authHeader hook for non-Bearer auth. Anthropic (anthropic.go): - Non-streaming ChatWithMessages now uses newJSONPostRequest + parseChatCompletionResponse with a new chatResponseExtractor (parseAnthropicChatResponse) that maps the messages API's content[] blocks into the common response shape and extracts usage.input_tokens / usage.output_tokens. The x-api-key auth header is wired through the authHeader hook, matching the xiaomi / xunfei pattern. - ChatStreamlyWithSender is unchanged: its bespoke message_start / message_delta usage merge and content_block_delta fan-out do not fit the unified handler, and it already records usage via applyStreamUsage. - ListModels unchanged. Cohere (cohere.go): - No change. Non-streaming was already on parseChatCompletionResponse (line 203) and streaming already calls applyStreamUsage (line 308). Google (google.go): - New googleUsageFromMetadata helper translates the genai SDK's GenerateContentResponseUsageMetadata into the package's TokenUsage. CandidatesTokenCount + ThoughtsTokenCount is summed into CompletionTokens; TotalTokenCount is used directly. - Both ChatWithMessages and ChatStreamlyWithSender call recordResponseUsage after the SDK call. The streaming path captures the last-seen UsageMetadata across chunks and records it once after the iterator finishes, mirroring the behaviour of other streaming drivers. Bedrock (bedrock.go): - New bedrockUsage struct + bedrockUsageFromMap / bedrockUsageToMap helpers handle Bedrock's camelCase inputTokens / outputTokens / totalTokens shape. - bedrockConverseResponse gains a Usage field; ChatWithMessages records usage after JSON unmarshal. - decodeBedrockEventStream gains an onMetadata callback that the streaming path uses to capture the metadata event's usage block; ChatStreamlyWithSender records it before emitting the [DONE] sentinel. The signature change is additive (third parameter is nil-tolerant) so existing callers stay compatible. Shared helper (base_model.go): - recordResponseUsage: when the caller passes a nil *ModelUsage but supplies usage, we surface a synthetic CollectModelUsage call against an empty ModelUsage so the analytics path can observe the provider's reported token counts. Without this, the existing service-layer callers (model_chat, generator, memory_extractor, etc.) that pass nil would never reach the stats driver and the token usage would be invisible. - collectModelUsage: when StartAt is the zero time, leave ResponseTimeMS at zero instead of reporting an epoch delta. Test impact: no new tests required. anthropic_test.go (519 lines), cohere_test.go, google_test.go, and bedrock_test.go (913 lines) all continue to pass via the package's unit tier. The CollectModelUsage real-storage path in clickhouse_ee.go is intentionally left as a follow-up. Co-authored-by: Haruko386 <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
📝 WalkthroughWalkthroughAnthropic requests now use shared request construction and structured response parsing. Bedrock and Google integrations extract token usage from non-streaming and streaming responses. Shared usage recording handles synthetic contexts and unset timestamps. ChangesProvider usage tracking
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant BedrockChat
participant EventStreamDecoder
participant BaseModel
participant ModelUsage
BedrockChat->>EventStreamDecoder: Decode stream with metadata callback
EventStreamDecoder->>BedrockChat: Forward final usage metadata
BedrockChat->>BaseModel: Record response usage
BaseModel->>ModelUsage: Store model usage
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/entity/models/bedrock.go`:
- Around line 727-743: Update decodeBedrockEventStream so messageStop marks the
stream terminal without returning, allowing subsequent frames through EOF to
reach onMetadata. Preserve normal event handling and final completion behavior,
then add a regression case covering messageStop followed by metadata and verify
ChatStreamlyWithSender records the captured usage in modelUsage.
In `@internal/entity/models/google.go`:
- Around line 598-599: Update the streamed-usage handling around
recordResponseUsage so that, when chatModelConfig is non-nil and streamUsage is
available, it also assigns chatModelConfig.UsageResult using the shared
applyStreamUsage behavior. Preserve the existing telemetry recording and avoid
collecting the same usage twice.
- Around line 442-467: Update googleUsageFromMetadata to include
m.ToolUsePromptTokenCount in PromptTokens, and account for it in the
zero-metadata check and fallback total calculation. Add a focused test covering
non-zero tool-use prompt tokens and verifying the resulting prompt and total
usage values.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 37ba74eb-4f63-4979-b78b-2bab9ba52edb
📒 Files selected for processing (4)
internal/entity/models/anthropic.gointernal/entity/models/base_model.gointernal/entity/models/bedrock.gointernal/entity/models/google.go
Three review findings on PR infiniflow#17775, all on the new bedrock and google streaming usage-recording paths. bedrock.go (decodeBedrockEventStream): messageStop used to return early from the decoder, but the AWS Bedrock Converse-Stream protocol sends a final "metadata" frame carrying token usage AFTER messageStop. Returning early silently dropped that metadata, so callers never saw the streaming usage. messageStop now only marks the stream terminal; the loop continues until EOF so post-messageStop metadata can reach the onMetadata callback. bedrock.go (ChatStreamlyWithSender): switched from recordResponseUsage to applyStreamUsage so chatConfig.UsageResult is populated alongside the modelUsage fields, matching the behaviour of every other streaming driver. The bedrock stream does not propagate a RequestID — consistent with the comment on applyStreamUsage that streaming providers can receive it in a different event from usage. google.go (googleUsageFromMetadata): fold ToolUsePromptTokenCount into PromptTokens. Per the genai SDK comment, TotalTokenCount is prompt + candidates + tool-use prompt + thoughts; treating tool-use-prompt separately would undercount the user's input and diverge from the SDK's authoritative total. The zero-metadata presence check and the fallback total calculation already handle the wider input range correctly. google.go (ChatStreamlyWithSender): switched from recordResponseUsage to applyStreamUsage for the same reason as the bedrock change. responseID tracking is removed; streaming drivers in this codebase do not propagate RequestID by design. bedrock_test.go: new TestBedrockStreamRecordsUsageFromPostMessageStopMetadata exercises the messageStart -> contentBlockDelta -> messageStop -> metadata frame sequence and asserts both modelUsage and chatConfig.UsageResult are populated from the post-messageStop metadata. google_test.go: new TestGoogleUsageFromMetadataIncludesToolUsePromptTokens verifies the helper folds ToolUsePromptTokenCount into PromptTokens and uses TotalTokenCount as the authoritative total when present, falling back to prompt + completion when TotalTokenCount is zero. All 59+ driver tests remain green. Co-authored-by: Haruko386 <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed all three findings from review. Pushed as a follow-up commit ( bedrock.go — bedrock.go — google.go — google.go —
|
…seUsage applyStreamUsage returned early when the caller passed a nil *ModelUsage, silently dropping streamed token usage for every streaming driver that uses it (anthropic, cohere, google, bedrock, novita). The service layer (model_chat, generator, chat_pipeline) commonly passes nil, so those drivers never reached the stats driver while the shared HandleStreamingResponse path did. Mirror recordResponseUsage's nil handling: synthesize an empty ModelUsage so the analytics path still observes the provider's reported token counts, and default Type to "chat". RequestID is left untouched to preserve the streaming contract where the caller owns it. Add TestApplyStreamUsageAlignsWithRecordResponseUsage covering the populated / nil-modelUsage / nil-usage cases. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/entity/models/provider_response_usage_test.go (1)
112-119: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove migration-history test documentation.
Lines 112-119 describe prior behavior and enumerate provider implementations. This list can become stale. Keep only the current invariant that this test verifies.
Proposed update
// TestApplyStreamUsageAlignsWithRecordResponseUsage verifies that -// applyStreamUsage mirrors recordResponseUsage's nil-modelUsage handling: -// a nil *ModelUsage (the common case from the model_chat / generator service -// layer) must not silently drop the usage, and a populated one must get -// Type="chat" and the token counts written through to analytics. Before the -// alignment the function returned early on a nil modelUsage, so streaming -// callers (anthropic, cohere, google, bedrock, novita) never reached the -// stats driver while the shared HandleStreamingResponse path did. +// applyStreamUsage propagates usage for populated and nil ModelUsage values. +// It also verifies that nil usage is a no-op.As per coding guidelines, keep Go doc comments aligned with the current runtime path rather than migration history.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/provider_response_usage_test.go` around lines 112 - 119, Shorten the comment above TestApplyStreamUsageAlignsWithRecordResponseUsage to state only the current invariant being tested: nil modelUsage must still record usage, while populated modelUsage sets Type="chat" and token counts for analytics. Remove the historical explanation and provider enumeration without changing the test logic.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/entity/models/provider_response_usage_test.go`:
- Around line 112-119: Shorten the comment above
TestApplyStreamUsageAlignsWithRecordResponseUsage to state only the current
invariant being tested: nil modelUsage must still record usage, while populated
modelUsage sets Type="chat" and token counts for analytics. Remove the
historical explanation and provider enumeration without changing the test logic.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: c7238e17-f693-4fc7-86c4-e341e62e1bd2
📒 Files selected for processing (2)
internal/entity/models/base_model.gointernal/entity/models/provider_response_usage_test.go
Summary
Relate to #17284.
Completes the migration of the four non-OpenAI-compatible model drivers (
anthropic,cohere,google,bedrock) onto the shared usage-recording path. Earlier batches (#17634, #17643, #17696–#17700) covered only the OpenAI-compatible cluster; these four providers ship wire formats that do not fit the OpenAIchoices[0].delta/usageblock template and so were left for a separate pass.Per the maintainer's guidance for this batch, each driver is migrated on its own terms rather than forced through a single template. The shared machinery used is intentionally small:
recordResponseUsage,parseChatCompletionResponse,BaseModel.newJSONPostRequest, and the existingauthHeaderhook for non-Bearer auth.Anthropic (
anthropic.go)ChatWithMessagesnow usesnewJSONPostRequest+parseChatCompletionResponsewith a newchatResponseExtractor(parseAnthropicChatResponse) that maps the Messages API'scontent[]blocks into the common response shape and extractsusage.input_tokens/usage.output_tokens. Thex-api-keyauth header is wired through theauthHeaderhook, matching the xiaomi / xunfei pattern.ChatStreamlyWithSenderis unchanged: its bespokemessage_start/message_deltausage merge andcontent_block_deltafan-out do not fit the unified handler, and it already records usage viaapplyStreamUsage.ListModelsunchanged.Cohere (
cohere.go)parseChatCompletionResponseand streaming already callsapplyStreamUsage.Google (
google.go)googleUsageFromMetadatahelper translates the genai SDK'sGenerateContentResponseUsageMetadatainto the package'sTokenUsage.CandidatesTokenCount + ThoughtsTokenCountis summed intoCompletionTokens;TotalTokenCountis used directly.ChatWithMessagesandChatStreamlyWithSendercallrecordResponseUsageafter the SDK call. The streaming path captures the last-seenUsageMetadataacross chunks and records it once after the iterator finishes.Bedrock (
bedrock.go)bedrockUsagestruct +bedrockUsageFromMap/bedrockUsageToMaphelpers handle Bedrock's camelCaseinputTokens/outputTokens/totalTokensshape.bedrockConverseResponsegains aUsagefield;ChatWithMessagesrecords usage after JSON unmarshal.decodeBedrockEventStreamgains anonMetadatacallback that the streaming path uses to capture the metadata event's usage block;ChatStreamlyWithSenderrecords it before emitting the[DONE]sentinel. The signature change is additive (third parameter is nil-tolerant).Shared helper (
base_model.go)recordResponseUsage: when the caller passes a nil*ModelUsagebut suppliesusage, we surface a syntheticCollectModelUsagecall against an emptyModelUsageso the analytics path can observe the provider's reported token counts. Without this, the existing service-layer callers (model_chat,generator,memory_extractor, etc.) that passnilwould never reach the stats driver and the token usage would be invisible.collectModelUsage: whenStartAtis the zero time, leaveResponseTimeMSat zero instead of reporting an epoch delta.Test impact
No new tests required.
anthropic_test.go(519 lines),cohere_test.go,google_test.go, andbedrock_test.go(913 lines) all continue to pass via the package's unit tier (bash build.sh --test ./internal/entity/models/...).The
CollectModelUsagereal-storage path inclickhouse_ee.gois intentionally left as a follow-up.