Skip to content

fix(go-models): record provider token usage - #17423

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:feat/llm-usage-silicon-ali-qiniu-hw-huoshan
Jul 27, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
Harry-Hz-Zhang:feat/llm-usage-silicon-ali-qiniu-hw-huoshan

Conversation

@Harry-Hz-Zhang

@Harry-Hz-Zhang Harry-Hz-Zhang commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Related to #17284

  • Parse chat, embedding, and rerank usage from provider responses
  • Record usage with the correct model type even when no usage sink is provided
  • Cover SiliconFlow, Aliyun, Huawei Cloud, Qiniu, and VolcEngine response formats

Testing

  • go vet ./internal/entity/models
  • CGO_ENABLED=0 go test ./internal/entity/models -count=1

@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 27, 2026
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c7794c01-bcb6-48de-9ea6-7f54b9711e0b

📥 Commits

Reviewing files that changed from the base of the PR and between 06ea837 and 95435aa.

📒 Files selected for processing (4)
  • internal/entity/models/base_model.go
  • internal/entity/models/openai_compatible_usage_test.go
  • internal/entity/models/qiniu.go
  • internal/entity/models/siliconflow.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/entity/models/qiniu.go
  • internal/entity/models/siliconflow.go

📝 Walkthrough

Walkthrough

The PR standardizes typed OpenAI-compatible chat parsing across five providers, adds streaming usage extraction, records embedding and reranking usage, adjusts rerank defaults, and adds provider integration tests.

Changes

Provider usage integration

Layer / File(s) Summary
Shared usage recording
internal/entity/models/base_model.go
Centralizes non-streaming usage recording and safely handles absent streaming usage sinks.
Typed chat and streaming flows
internal/entity/models/aliyun.go, internal/entity/models/huaweicloud.go, internal/entity/models/qiniu.go, internal/entity/models/siliconflow.go, internal/entity/models/volcengine.go
Uses typed chat responses, handles reasoning and tool calls, extracts SSE usage, and validates VolcEngine stream termination.
Embedding and rerank usage
internal/entity/models/aliyun.go, internal/entity/models/huaweicloud.go, internal/entity/models/siliconflow.go, internal/entity/models/volcengine.go
Records token usage, aggregates VolcEngine embedding usage, and updates rerank defaults and response mapping.
Provider usage tests
internal/entity/models/*usage_test.go, internal/entity/models/siliconflow_test.go, internal/entity/models/volcengine_test.go
Validates chat, streaming, embedding, rerank usage, request options, reasoning effort, and truncated streams.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant ChatStreamlyWithSender
  participant ProviderSSE
  participant ModelUsage
  Client->>ChatStreamlyWithSender: submit streaming chat request
  ChatStreamlyWithSender->>ProviderSSE: send stream_options.include_usage
  ProviderSSE-->>ChatStreamlyWithSender: return SSE deltas and usage event
  ChatStreamlyWithSender->>ModelUsage: decode and apply token usage
  ModelUsage-->>Client: expose UsageResult
Loading

Possibly related issues

Possibly related PRs

Suggested labels: ☯️ refactor

Suggested reviewers: haruko386

Poem

I’m a bunny counting tokens bright,
Typed messages hop just right.
SSE streams bring usage near,
Embeddings and reranks appear.
Tests cheer softly: “Well done!”

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: recording provider token usage in go models.
Description check ✅ Passed The description matches the template's Summary section and includes helpful testing commands.
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.

@Harry-Hz-Zhang Harry-Hz-Zhang added 🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration labels Jul 27, 2026
@Harry-Hz-Zhang
Harry-Hz-Zhang requested a review from Haruko386 July 27, 2026 07:56

@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: 4

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

505-511: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Dead fallback: topN can never be 0 here.

topN starts at len(documents), which is guaranteed non-zero by the early return at Line 490, and is only reassigned when rerankConfig.TopN > 0. Drop the leftover branch.

♻️ Remove the unreachable branch
 	topN := len(documents)
 	if rerankConfig != nil && rerankConfig.TopN > 0 {
 		topN = rerankConfig.TopN
 	}
-	if topN == 0 {
-		topN = len(documents)
-	}
🤖 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/aliyun.go` around lines 505 - 511, Remove the
unreachable topN == 0 fallback branch in the reranking logic around topN
initialization, while preserving the existing default to len(documents) and
positive rerankConfig.TopN override.
🤖 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/base_model.go`:
- Around line 76-91: The usage helpers create local records when no caller-owned
model usage exists, causing incomplete persistence. Update recordResponseUsage
and applyStreamUsage to return immediately when their model usage argument is
nil; keep existing usage collection unchanged for non-nil records, and note that
internal/entity/models/base_model.go lines 133-138 requires the same handling in
applyStreamUsage.

In `@internal/entity/models/non_chat_usage_test.go`:
- Around line 1-8: Add the standard InfiniFlow Apache-2.0 license header at the
top of non_chat_usage_test.go, matching the header used by
openai_compatible_usage_test.go.

In `@internal/entity/models/openai_compatible_usage_test.go`:
- Around line 62-65: In the httptest handler decode-error branches, replace
t.Fatalf with t.Errorf and immediately return so the handler terminates without
leaving the request unanswered. Apply this in
internal/entity/models/openai_compatible_usage_test.go lines 62-65 and
internal/entity/models/volcengine_test.go lines 119-122, using the existing
request-body decode logic in each handler.

In `@internal/entity/models/siliconflow.go`:
- Around line 254-261: Enable usage reporting in both streaming request bodies:
update internal/entity/models/siliconflow.go at lines 254-261 and
internal/entity/models/qiniu.go at lines 321-328 to add stream_options with
include_usage set to true where each request body is built, so
decodeOpenAICompatibleStreamUsage can receive the emitted usage chunk.

---

Nitpick comments:
In `@internal/entity/models/aliyun.go`:
- Around line 505-511: Remove the unreachable topN == 0 fallback branch in the
reranking logic around topN initialization, while preserving the existing
default to len(documents) and positive rerankConfig.TopN override.
🪄 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: 58a496aa-0710-4421-a928-f04795209f28

📥 Commits

Reviewing files that changed from the base of the PR and between cd846cc and 06ea837.

📒 Files selected for processing (10)
  • internal/entity/models/aliyun.go
  • internal/entity/models/base_model.go
  • internal/entity/models/huaweicloud.go
  • internal/entity/models/non_chat_usage_test.go
  • internal/entity/models/openai_compatible_usage_test.go
  • internal/entity/models/qiniu.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/siliconflow_test.go
  • internal/entity/models/volcengine.go
  • internal/entity/models/volcengine_test.go

Comment thread internal/entity/models/base_model.go Resolved
Comment thread internal/entity/models/siliconflow.go Resolved

@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 Jul 27, 2026
@Harry-Hz-Zhang Harry-Hz-Zhang removed the lgtm This PR has been approved by a maintainer label Jul 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants