Skip to content

Go: add token usage for orcarouter, baichuan, cohere and novita - #17455

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
Haruko386:master
Jul 28, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
Haruko386:master

Conversation

@Haruko386

@Haruko386 Haruko386 commented Jul 28, 2026 •

Copy link
Copy Markdown
Member

Summary

As title #17284

@Haruko386 Haruko386 added the 🐞 bug Something isn't working, pull request that fix bug. label Jul 28, 2026
@dosubot dosubot Bot added the size:XS This PR changes 0-9 lines, ignoring generated files. label Jul 28, 2026
@Haruko386
Haruko386 marked this pull request as draft July 28, 2026 03:11
@Haruko386
Haruko386 marked this pull request as ready for review July 28, 2026 03:11
@Haruko386 Haruko386 added the ci Continue Integration label Jul 28, 2026
@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Baichuan, Cohere, Novita, and OrcaRouter now use typed chat response models with shared parsing and streaming usage helpers. Embedding and reranking integrations also record token usage from provider responses.

Changes

Provider response and token usage handling

Layer / File(s) Summary
Typed chat response parsing
internal/entity/models/baichuan.go, internal/entity/models/cohere.go, internal/entity/models/novita.go, internal/entity/models/orcarouter.go
Chat responses use typed provider models, shared parsing, validation, tool-call extraction, reasoning handling, and token usage mapping.
Streaming usage handling
internal/entity/models/baichuan.go, internal/entity/models/cohere.go, internal/entity/models/novita.go, internal/entity/models/orcarouter.go, internal/entity/models/cohere_test.go
Streaming callbacks decode provider usage events, apply token counts to model usage, and test tool-call and streaming usage behavior.
Embedding and reranking usage recording
internal/entity/models/baichuan.go, internal/entity/models/cohere.go, internal/entity/models/novita.go
Embedding and reranking schemas expose response identifiers and usage fields, which are passed to recordResponseUsage.

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

Sequence Diagram(s)

sequenceDiagram
  participant ChatStreamlyWithSender
  participant SSEEvent
  participant UsageDecoder
  participant applyStreamUsage
  ChatStreamlyWithSender->>SSEEvent: receive provider streaming event
  SSEEvent->>UsageDecoder: decode provider token usage
  UsageDecoder->>applyStreamUsage: provide decoded usage
  applyStreamUsage->>ChatStreamlyWithSender: update model usage
Loading

Possibly related PRs

Suggested labels: 💞 feature, ☯️ refactor

Suggested reviewers: jinhai-cn

Poem

I’m a rabbit with typed tokens bright,
Parsing chat through the moonlit night.
Streams bring usage, embeddings too,
Reranks count what providers do.
Hop, hop—clean responses bloom! 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description only says 'As title' and lacks the required brief summary and background context. Expand the Summary with a short explanation of the problem, the affected providers, and any relevant background or impact.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title accurately and concisely summarizes the main change: adding token usage support for the four model integrations.

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.

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

🤖 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/service/nlp/retrieval.go`:
- Around line 525-529: Update the retrieval result construction in the relevant
Search flow so RetrievalResult.Total is not derived from validIdx for only the
current rerank window. Compute it from the complete post-threshold result set,
or preserve a separate page-count field while keeping Total aligned with its
documented post-pagination meaning. Add a regression test that spans a
searchPage boundary and verifies the total remains consistent across windows.
🪄 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: 106d393a-fd8f-4e0e-a4e5-a77dddaac9b8

📥 Commits

Reviewing files that changed from the base of the PR and between 3268938 and a21feb5.

📒 Files selected for processing (1)
  • internal/service/nlp/retrieval.go

Comment on lines 525 to 529
return &RetrievalResult{
Chunks: filteredChunks,
DocAggs: docAggs,
Total: int64(len(filteredChunks)),
Total: int64(len(validIdx)),
}, nil

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.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Do not use the current rerank window as the total.

validIdx contains threshold-passing indices only from the current Search call, whose results are capped by rerankLimit; it is not the complete retrieval set. Consequently, Total changes when pagination advances to another search window and can undercount the true post-reranking total. It also conflicts with the existing RetrievalResult.Total documentation describing a post-pagination count. Compute the total from a complete post-threshold result set, or explicitly preserve a separate page-count field, and add a regression test across a searchPage boundary.

🤖 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/service/nlp/retrieval.go` around lines 525 - 529, Update the
retrieval result construction in the relevant Search flow so
RetrievalResult.Total is not derived from validIdx for only the current rerank
window. Compute it from the complete post-threshold result set, or preserve a
separate page-count field while keeping Total aligned with its documented
post-pagination meaning. Add a regression test that spans a searchPage boundary
and verifies the total remains consistent across windows.

@Haruko386
Haruko386 marked this pull request as draft July 28, 2026 07:13
@Haruko386 Haruko386 changed the title fix: search-bot return pageSize chunk instead of the total chunks Go: add token usage for orcarouter, baichuan, cohere and novita Jul 28, 2026
@Haruko386
Haruko386 marked this pull request as ready for review July 28, 2026 08:36
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels Jul 28, 2026
@Haruko386 Haruko386 removed the ci Continue Integration label Jul 28, 2026
@Haruko386
Haruko386 marked this pull request as draft July 28, 2026 08:36
@Haruko386
Haruko386 marked this pull request as ready for review July 28, 2026 08:36
@Haruko386 Haruko386 added the ci Continue Integration label Jul 28, 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: 2

🤖 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/cohere.go`:
- Around line 191-216: Update the Cohere response handling in the
parseChatCompletionResponse callback to decode message.tool_calls into
CohereChatResponse and propagate them in the returned chatResponseParts. Allow
responses with empty message content when tool calls are present, while still
rejecting responses where both content and tool_calls are absent; preserve
existing content and usage handling.
- Around line 56-123: Update decodeCohereStreamUsage and the streaming callback
at internal/entity/models/cohere.go:290-295 to read message-end usage from
event["delta"]["usage"]["tokens"], including v2/chat input_tokens and
output_tokens, instead of relying only on top-level usage fields. Preserve the
existing token conversion and zero-usage behavior, and ensure the callback
invokes this Cohere-specific decoder.
🪄 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: bf927974-8856-4aa8-ba73-4f282cd13ffe

📥 Commits

Reviewing files that changed from the base of the PR and between a21feb5 and c916a30.

📒 Files selected for processing (4)
  • internal/entity/models/baichuan.go
  • internal/entity/models/cohere.go
  • internal/entity/models/novita.go
  • internal/entity/models/orcarouter.go

Comment thread internal/entity/models/cohere.go Resolved
Comment thread internal/entity/models/cohere.go Resolved

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

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

72-127: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add embedding and rerank usage-accounting tests.

The new tests cover chat and streaming usage, but not the added embedding and rerank recordResponseUsage paths. Add one mocked response for each to assert request ID and token totals.

As per coding guidelines, “Preserve still-valid behavior with focused tests.”

🤖 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/cohere_test.go` around lines 72 - 127, Add focused
tests for the embedding and rerank paths that invoke recordResponseUsage, using
mocked server responses for each operation. Assert that both request ID
propagation and prompt/token totals are recorded correctly, while preserving the
existing chat and streaming usage tests and behavior.

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.

Inline comments:
In `@internal/entity/models/cohere_test.go`:
- Around line 77-86: Update the HTTP handler test around the body parsing and
stream assertion to use t.Errorf instead of t.Fatalf, then return immediately
after each failed read, unmarshal, or validation check so the handler goroutine
exits safely without continuing with invalid state.

---

Nitpick comments:
In `@internal/entity/models/cohere_test.go`:
- Around line 72-127: Add focused tests for the embedding and rerank paths that
invoke recordResponseUsage, using mocked server responses for each operation.
Assert that both request ID propagation and prompt/token totals are recorded
correctly, while preserving the existing chat and streaming usage tests and
behavior.
🪄 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: c55cd945-d8e8-4e83-bb3c-0585e17862a8

📥 Commits

Reviewing files that changed from the base of the PR and between c916a30 and e501ba0.

📒 Files selected for processing (2)
  • internal/entity/models/cohere.go
  • internal/entity/models/cohere_test.go

Comment on lines +77 to +86
raw, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
var body map[string]any
if err := json.Unmarshal(raw, &body); err != nil {
t.Fatalf("unmarshal body: %v", err)
}
if body["stream"] != true {
t.Fatalf("stream=%v, want true", body["stream"])

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail
go doc testing.T.FailNow

Repository: infiniflow/ragflow

Length of output: 639


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail
fd -a 'cohere_test.go' .

Repository: infiniflow/ragflow

Length of output: 213


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail
wc -l internal/entity/models/cohere_test.go
sed -n '1,140p' internal/entity/models/cohere_test.go

Repository: infiniflow/ragflow

Length of output: 3689


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail
go doc testing.T.Fatalf

Repository: infiniflow/ragflow

Length of output: 295


Use t.Errorf and return from the HTTP handler.

The server handler runs in a different goroutine from the test, and Fatalf calls runtime.Goexit in that handler goroutine. Mark failures with t.Errorf(...) and return after each invalid handler check.

Proposed fix
 		raw, err := io.ReadAll(r.Body)
 		if err != nil {
-			t.Fatalf("read body: %v", err)
+			t.Errorf("read body: %v", err)
+			return
 		}
 		var body map[string]any
 		if err := json.Unmarshal(raw, &body); err != nil {
-			t.Fatalf("unmarshal body: %v", err)
+			t.Errorf("unmarshal body: %v", err)
+			return
 		}
 		if body["stream"] != true {
-			t.Fatalf("stream=%v, want true", body["stream"])
+			t.Errorf("stream=%v, want true", body["stream"])
+			return
 		}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
raw, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
var body map[string]any
if err := json.Unmarshal(raw, &body); err != nil {
t.Fatalf("unmarshal body: %v", err)
}
if body["stream"] != true {
t.Fatalf("stream=%v, want true", body["stream"])
raw, err := io.ReadAll(r.Body)
if err != nil {
t.Errorf("read body: %v", err)
return
}
var body map[string]any
if err := json.Unmarshal(raw, &body); err != nil {
t.Errorf("unmarshal body: %v", err)
return
}
if body["stream"] != true {
t.Errorf("stream=%v, want true", body["stream"])
return
}
🤖 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/cohere_test.go` around lines 77 - 86, Update the HTTP
handler test around the body parsing and stream assertion to use t.Errorf
instead of t.Fatalf, then return immediately after each failed read, unmarshal,
or validation check so the handler goroutine exits safely without continuing
with invalid state.

Source: Learnings

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:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants