Repository navigation
Go: add token usage for orcarouter, baichuan, cohere and novita - #17455
Conversation
📝 WalkthroughWalkthroughBaichuan, 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. ChangesProvider response and token usage handling
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
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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: 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
📒 Files selected for processing (1)
internal/service/nlp/retrieval.go
| return &RetrievalResult{ | ||
| Chunks: filteredChunks, | ||
| DocAggs: docAggs, | ||
| Total: int64(len(filteredChunks)), | ||
| Total: int64(len(validIdx)), | ||
| }, nil |
There was a problem hiding this comment.
🎯 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.
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
internal/entity/models/baichuan.gointernal/entity/models/cohere.gointernal/entity/models/novita.gointernal/entity/models/orcarouter.go
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/entity/models/cohere_test.go (1)
72-127: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd embedding and rerank usage-accounting tests.
The new tests cover chat and streaming usage, but not the added
embeddingandrerankrecordResponseUsagepaths. 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
📒 Files selected for processing (2)
internal/entity/models/cohere.gointernal/entity/models/cohere_test.go
| 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"]) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
go doc testing.T.FailNowRepository: 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.goRepository: infiniflow/ragflow
Length of output: 3689
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
go doc testing.T.FatalfRepository: 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.
| 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
Summary
As title #17284