Skip to content

feat(go-models): migrate batch 6 model drivers to unified usage recording - #17775

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
jay77721:pr/migrate-models-batch6
Aug 4, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
jay77721:pr/migrate-models-batch6

Conversation

@jay77721

@jay77721 jay77721 commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

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 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 and streaming already calls applyStreamUsage.

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.

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).

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 (bash build.sh --test ./internal/entity/models/...).

The CollectModelUsage real-storage path in clickhouse_ee.go is intentionally left as a follow-up.

…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]>
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Aug 4, 2026
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Anthropic 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.

Changes

Provider usage tracking

Layer / File(s) Summary
Shared usage recording
internal/entity/models/base_model.go, internal/entity/models/provider_response_usage_test.go
Shared usage recording now supports synthetic usage contexts and leaves response time at zero when no start timestamp exists. Tests cover populated, nil, and absent usage.
Anthropic request and response usage
internal/entity/models/anthropic.go
Anthropic requests use shared JSON construction, x-api-key authentication, standard headers, and structured response parsing with request ID and token usage.
Bedrock Converse usage
internal/entity/models/bedrock.go, internal/entity/models/bedrock_test.go
Bedrock converts response usage and records it for non-streaming responses and streaming metadata events. The test covers metadata received after messageStop.
Google Gemini usage
internal/entity/models/google.go, internal/entity/models/google_test.go
Google converts usage metadata, includes thought and tool-use prompt tokens, derives missing totals, and records final usage for non-streaming and streaming chats. Tests cover these conversions.

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
Loading

Possibly related PRs

Suggested labels: 🐞 bug, ☯️ refactor, 🧪 test

Suggested reviewers: hz-186, jinhai-cn

Poem

A rabbit counts tokens with care,
Across three model streams in the air.
Metadata arrives at the end,
Shared usage records attend.
Hop, parse, and measure with flair! 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the migration of model drivers to unified usage recording.
Description check ✅ Passed The description includes a complete Summary section with purpose, provider details, shared changes, tests, and follow-up scope.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@jay77721
jay77721 requested a review from Haruko386 August 4, 2026 04:52
@jay77721 jay77721 added the ci Continue Integration label Aug 4, 2026

@coderabbitai coderabbitai Bot left a comment

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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 79a57d2 and 1b64c8c.

📒 Files selected for processing (4)
  • internal/entity/models/anthropic.go
  • internal/entity/models/base_model.go
  • internal/entity/models/bedrock.go
  • internal/entity/models/google.go

Comment thread internal/entity/models/bedrock.go Resolved
Comment thread internal/entity/models/google.go Resolved
Comment thread internal/entity/models/google.go Resolved
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]>
@jay77721

jay77721 commented Aug 4, 2026

Copy link
Copy Markdown
Member Author

Addressed all three findings from review. Pushed as a follow-up commit (a437bcb65).

bedrock.go — decodeBedrockEventStream
The case "messageStop" arm no longer return nil; it only sets sawTerminal = true and the loop continues until EOF. The AWS Bedrock Converse-Stream protocol sends a final metadata frame (carrying token usage) after messageStop, so returning early silently dropped the streaming usage. The new TestBedrockStreamRecordsUsageFromPostMessageStopMetadata covers this exact sequence (messageStart → contentBlockDelta → messageStop → metadata) and asserts both modelUsage and chatConfig.UsageResult are populated.

bedrock.go — ChatStreamlyWithSender
Switched the trailing recordResponseUsage(...) call to applyStreamUsage(chatModelConfig, modelUsage, streamUsage) so chatConfig.UsageResult is also populated — matching the unified streaming behaviour of every other driver. No usage is collected twice: applyStreamUsage is the single entry point that does both the field-write and the clickhouse call.

google.go — googleUsageFromMetadata
ToolUsePromptTokenCount is now folded into PromptTokens. The zero-metadata presence check and the fallback total = in + out already cover the wider input range, so no further change there. New TestGoogleUsageFromMetadataIncludesToolUsePromptTokens covers both paths (TotalTokenCount present and absent).

google.go — ChatStreamlyWithSender
Same recordResponseUsage → applyStreamUsage switch as bedrock, with the same justification. The responseID tracking is removed; streaming drivers in this codebase intentionally do not propagate RequestID (per the comment on applyStreamUsage).

bash build.sh --test ./internal/entity/models/... — full package green; all four driver test families (anthropic 14, cohere 2, google 24, bedrock 24) pass.

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Aug 4, 2026
@Haruko386
Haruko386 marked this pull request as draft August 4, 2026 05:10
@Haruko386 Haruko386 removed the ci Continue Integration label Aug 4, 2026
@Haruko386
Haruko386 marked this pull request as ready for review August 4, 2026 05:10
@Haruko386 Haruko386 added the ci Continue Integration label Aug 4, 2026
…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]>

@coderabbitai coderabbitai Bot left a comment

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.

🧹 Nitpick comments (1)
internal/entity/models/provider_response_usage_test.go (1)

112-119: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove 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

📥 Commits

Reviewing files that changed from the base of the PR and between a437bcb and bcb8d65.

📒 Files selected for processing (2)
  • internal/entity/models/base_model.go
  • internal/entity/models/provider_response_usage_test.go

@JinHai-CN
JinHai-CN merged commit 74f6355 into infiniflow:main Aug 4, 2026
3 checks passed
@jay77721
jay77721 deleted the pr/migrate-models-batch6 branch August 5, 2026 07:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants