Repository navigation
Port agent PRs to GO - 2 - #16565
Port agent PRs to GO - 2#16565
Conversation
📝 WalkthroughWalkthroughAdds per-run token usage tracking across model calls, tool loops, and agent SSE completion payloads, and adds Close() cleanup methods for canvas resources and the MCP tool adapter. ChangesToken usage tracking and reporting
Estimated code review effort: 4 (Complex) | ~60 minutes Resource cleanup via Close()
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 inconclusive)
✅ 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
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/entity/models/chat_tools.go (1)
141-154: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winNon-streaming tool loop's fallback token estimate never reaches the run-level usage sink.
Fallback: if the provider didn't return usage info, estimate from the answer text using tiktoken, but this only updates the local
totalTokensreturn value — it never callsrecordUsageFromResponse/tokenizer.RecordRunTokenUsage. The same gap exists in the exceeded-max-rounds final call. Compare withrunStreamToolLoop'scommitRound(lines 236-258), which always records either the authoritative usage or theroundTokensestimate into the sink. As written,workflow_finished.usage(agent.go) will under-report tokens for non-streaming tool-calling runs whenever the provider omits usage data, while the returnedtotalTokensfromChatWithToolsis correct — an inconsistency between the two consumers of the same computation.🐛 Proposed fix to keep both paths consistent
if resp.Usage == nil || resp.Usage.TotalTokens == 0 { - totalTokens += tokenizer.NumTokensFromString(answer) + estimated := tokenizer.NumTokensFromString(answer) + totalTokens += estimated + tokenizer.RecordRunTokenUsage(ctx, 0, 0, estimated) } return answer, totalTokens, niladdRoundUsage(resp) // Fallback: use text-based estimation if no authoritative usage. if resp.Usage == nil || resp.Usage.TotalTokens == 0 { - totalTokens += tokenizer.NumTokensFromString(*resp.Answer) + estimated := tokenizer.NumTokensFromString(*resp.Answer) + totalTokens += estimated + tokenizer.RecordRunTokenUsage(ctx, 0, 0, estimated) } return *resp.Answer, totalTokens, nilAlso applies to: 160-178
🤖 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/chat_tools.go` around lines 141 - 154, The non-streaming tool loop in ChatWithTools is estimating fallback tokens locally but never writing that estimate to the run-level usage sink, so workflow_finished.usage can under-report. Update the fallback paths in the ChatWithTools tool loop (both the no-tool-calls return path and the exceeded-max-rounds final response path) to call the same usage recording helper used elsewhere, such as recordUsageFromResponse or tokenizer.RecordRunTokenUsage, whenever resp.Usage is missing or zero. Keep the returned totalTokens unchanged, but ensure the sink receives the authoritative usage when present or the tiktoken estimate when not, matching runStreamToolLoop’s commitRound behavior.
🧹 Nitpick comments (2)
internal/agent/canvas/canvas.go (1)
95-120: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDoc comment overstates recursion behavior.
The comment says "Maps, slices, and pointers are recursed into," but the
switchonly handlesmap[string]anyand[]any. Bare pointers to structs (e.g.*SomeWrapper{ Adapter *MCPToolAdapter }) that don't themselves implementClose()won't be recursed into — only values already satisfyinginterface{ Close() }are caught via the earlier type assertion. Since DSL-decoded params are typicallymap[string]any/[]any/primitives, this is unlikely to bite in practice today, but the comment is misleading for future maintainers who inject typed struct wrappers intoParams.✏️ Suggested comment fix
-// walkAndClose recursively walks a value and calls Close() on any -// objects that implement a Close() method. Maps, slices, and pointers -// are recursed into; other types are skipped. Already-seen objects -// (by interface identity) are skipped to avoid double-close. +// walkAndClose recursively walks a value and calls Close() on any +// objects that implement a Close() method. Only map[string]any and +// []any containers are recursed into (matching JSON-decoded DSL +// shapes); other types, including bare struct pointers that don't +// themselves implement Close(), are skipped. Already-seen objects +// (by interface identity) are skipped to avoid double-close.🤖 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/agent/canvas/canvas.go` around lines 95 - 120, The doc comment on walkAndClose overstates what the function actually traverses: the implementation only recurses into map[string]any and []any, while pointers are only handled if they directly satisfy Close(). Update the comment to match the real behavior in walkAndClose and the interface{ Close() } check, so future maintainers are not misled about support for bare pointer-wrapped structs in Params.internal/entity/models/openai.go (1)
1061-1104: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate usage-extraction logic vs.
tokenizer.UsageFromMap.
extractUsageFromMapreimplements a raw API response map, and returns (prompt_tokens, completion_tokens, total_tokens) parsing already implemented astokenizer.UsageFromMapininternal/tokenizer/usage.go(lines 144-163), including the identical fallback key names andtotal_tokens = pt+ctfallback. Sinceinternal/entity/modelsalready importsragflow/internal/tokenizerelsewhere (e.g.,chat_tools.go), consider replacing this private duplicate with a call to the shared helper to avoid maintaining two copies of the same parsing rules.♻️ Proposed refactor
-func extractUsageFromMap(raw map[string]interface{}) (int, int, int) { - if raw == nil { - return 0, 0, 0 - } - ru, ok := raw["usage"] - if !ok { - return 0, 0, 0 - } - usage, ok := ru.(map[string]interface{}) - if !ok { - return 0, 0, 0 - } - get := func(keys ...string) int { - for _, k := range keys { - v, ok := usage[k] - if !ok { - continue - } - switch val := v.(type) { - case float64: - return int(val) - case int: - return val - case json.Number: - n, err := val.Int64() - if err == nil { - return int(n) - } - } - } - return 0 - } - pt := get("prompt_tokens", "input_tokens") - ct := get("completion_tokens", "output_tokens") - tt := get("total_tokens") - if tt == 0 { - tt = pt + ct - } - return pt, ct, tt -} +func extractUsageFromMap(raw map[string]interface{}) (int, int, int) { + return tokenizer.UsageFromMap(raw) +}🤖 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/openai.go` around lines 1061 - 1104, The usage parsing in extractUsageFromMap duplicates the shared logic already implemented in tokenizer.UsageFromMap. Replace the private map-parsing and fallback handling in extractUsageFromMap with a call to tokenizer.UsageFromMap so the prompt/completion/total token rules live in one place and stay consistent across internal/entity/models/openai.go.
🤖 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/agent/canvas/canvas.go`:
- Around line 83-93: Add coverage for Canvas.Close() in canvas_test.go by
exercising the teardown path through Canvas.Close and its helper flow in
walkAndClose/safeClose. Include tests that verify duplicate references are only
closed once via the seen map, that panics from a closeable value are swallowed
by safeClose, and that nested map/slice structures are recursively traversed and
closed.
---
Outside diff comments:
In `@internal/entity/models/chat_tools.go`:
- Around line 141-154: The non-streaming tool loop in ChatWithTools is
estimating fallback tokens locally but never writing that estimate to the
run-level usage sink, so workflow_finished.usage can under-report. Update the
fallback paths in the ChatWithTools tool loop (both the no-tool-calls return
path and the exceeded-max-rounds final response path) to call the same usage
recording helper used elsewhere, such as recordUsageFromResponse or
tokenizer.RecordRunTokenUsage, whenever resp.Usage is missing or zero. Keep the
returned totalTokens unchanged, but ensure the sink receives the authoritative
usage when present or the tiktoken estimate when not, matching
runStreamToolLoop’s commitRound behavior.
---
Nitpick comments:
In `@internal/agent/canvas/canvas.go`:
- Around line 95-120: The doc comment on walkAndClose overstates what the
function actually traverses: the implementation only recurses into
map[string]any and []any, while pointers are only handled if they directly
satisfy Close(). Update the comment to match the real behavior in walkAndClose
and the interface{ Close() } check, so future maintainers are not misled about
support for bare pointer-wrapped structs in Params.
In `@internal/entity/models/openai.go`:
- Around line 1061-1104: The usage parsing in extractUsageFromMap duplicates the
shared logic already implemented in tokenizer.UsageFromMap. Replace the private
map-parsing and fallback handling in extractUsageFromMap with a call to
tokenizer.UsageFromMap so the prompt/completion/total token rules live in one
place and stay consistent across internal/entity/models/openai.go.
🪄 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
Run ID: 528e3830-8209-4a6d-b395-3a5a55712c0e
📒 Files selected for processing (8)
internal/agent/canvas/canvas.gointernal/agent/tool/mcp.gointernal/entity/models/chat_tools.gointernal/entity/models/llm.gointernal/entity/models/openai.gointernal/entity/models/types.gointernal/service/agent.gointernal/tokenizer/usage.go
| func (c *Canvas) Close() { | ||
| if c == nil { | ||
| return | ||
| } | ||
| seen := make(map[any]bool) | ||
| for _, comp := range c.Components { | ||
| for _, v := range comp.Obj.Params { | ||
| walkAndClose(v, seen) | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Check for existing test coverage of Canvas.Close / walkAndClose / safeClose.
rg -n 'Close|walkAndClose|safeClose' internal/agent/canvas/canvas_test.goRepository: infiniflow/ragflow
Length of output: 156
🏁 Script executed:
#!/bin/bash
set -euo pipefail
git ls-files 'internal/agent/canvas/*' | sort
echo '--- canvas.go ---'
wc -l internal/agent/canvas/canvas.go
cat -n internal/agent/canvas/canvas.go | sed -n '1,220p'
echo '--- canvas_test.go ---'
wc -l internal/agent/canvas/canvas_test.go
cat -n internal/agent/canvas/canvas_test.go | sed -n '1,260p'
echo '--- other canvas tests ---'
rg -n --hidden --glob '!**/node_modules/**' 'walkAndClose|safeClose|Canvas\.Close|Close\(' internal/agent/canvasRepository: infiniflow/ragflow
Length of output: 14203
Add tests for Canvas.Close() canvas_test.go only has the smoke test, so this teardown path still lacks coverage for seen deduplication, safeClose panic-swallowing, and recursive traversal of nested maps/slices.
🤖 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/agent/canvas/canvas.go` around lines 83 - 93, Add coverage for
Canvas.Close() in canvas_test.go by exercising the teardown path through
Canvas.Close and its helper flow in walkAndClose/safeClose. Include tests that
verify duplicate references are only closed once via the seen map, that panics
from a closeable value are swallowed by safeClose, and that nested map/slice
structures are recursively traversed and closed.
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/entity/models/openai.go`:
- Around line 260-271: The streaming request body in OpenAI request construction
unconditionally adds stream_options.include_usage, which can break providers
that do not support it. Update the request-building path in the openai model
code so stream_options is only added for compatible providers or when explicitly
enabled, and ensure the relevant request builder (where reqBody is assembled)
can fall back to sending stream without stream_options after a 400/422 response.
🪄 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
Run ID: fa78e932-2f68-4a80-9493-1241cf2d9f82
📒 Files selected for processing (8)
internal/agent/canvas/canvas.gointernal/agent/tool/mcp.gointernal/entity/models/chat_tools.gointernal/entity/models/llm.gointernal/entity/models/openai.gointernal/entity/models/types.gointernal/service/agent.gointernal/tokenizer/usage.go
🚧 Files skipped from review as they are similar to previous changes (7)
- internal/agent/tool/mcp.go
- internal/agent/canvas/canvas.go
- internal/entity/models/types.go
- internal/service/agent.go
- internal/tokenizer/usage.go
- internal/entity/models/llm.go
- internal/entity/models/chat_tools.go
| // Build request body with streaming on by default. | ||
| // stream_options.include_usage asks the provider to attach a | ||
| // usage block to the final streaming chunk (mirrors Python's | ||
| // chat_model.py _stream_options / stream_options.include_usage). | ||
| reqBody := map[string]interface{}{ | ||
| "model": modelName, | ||
| "messages": apiMessages, | ||
| "stream": true, | ||
| "stream_options": map[string]interface{}{ | ||
| "include_usage": true, | ||
| }, | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🌐 Web query:
Do OpenAI-compatible LLM proxy servers commonly reject unknown request body fields like stream_options.include_usage?
💡 Result:
Whether OpenAI-compatible LLM proxy servers reject unknown request body fields, such as stream_options.include_usage, depends entirely on the specific implementation of the proxy [1][2]. There is no industry-wide standard requiring proxies to either accept or reject these fields, and behavior varies significantly between different software projects [1][3]. Some proxies enforce strict schema validation for security or compatibility reasons and will return a 400 Bad Request error if they encounter unknown fields [4][5][2]. Others are designed with a passthrough philosophy, intended to forward all incoming parameters to the backend inference server regardless of whether the proxy recognizes them, effectively allowing the upstream model or API to decide how to handle the data [1][6][3]. Specific issues regarding stream_options.include_usage include: - Strict Rejection: Certain gateways and proxies (e.g., Databricks AI Gateway, specific legacy API endpoints like Codex) implement strict JSON validation and will reject requests containing unknown parameters, including stream_options [5][7][8]. - Automated Injection: Many modern proxies automatically inject stream_options.include_usage to enable token usage tracking for downstream analytics [9][7][10]. If this injection is applied to an endpoint that does not support the parameter, it can cause the request to fail [5][11][7]. - Configurable Behavior: Recognizing the conflict between strict backends and feature-rich proxies, developers often add configuration flags to opt out of such injections or to toggle strict validation [1][12][7]. Best practices for proxy development, particularly those following vLLM or OpenAI-compatibility guidelines, generally recommend that proxies should preserve and forward all request parameters, including unrecognized ones, to ensure maximum compatibility with future API updates and model-specific features [3]. However, as evidenced by common bug reports, many implementations still struggle with this when strict backend validation is involved [4][12][5][8].
Citations:
- 1: feat(proxy): optionally preserve unknown OpenAI request parameters for Provider mapping BerriAI/litellm#31697
- 2: https://documentation.gravitee.io/apim/ai-agent-management/llm-proxy/accepted-request-formats
- 3: https://gist.github.com/bbrowning/f9c00ea4b38a232abb66006b60867c63
- 4: Perplexity Agent provider fails with
unknown field "store"on/v1/responsesanomalyco/opencode#32108 - 5: api-proxy: stream_options.include_usage injected into OpenAI Responses API requests github/gh-aw-firewall#3804
- 6: victor-software-house/pi-openai-proxy@b65a00a
- 7: [Bug]: "stream_options" injected into OpenAI-compatible provider causing 400 Bad Request on Databricks AI Gateway anomalyco/opencode#31156
- 8: [Bug]: Internal metadata in litellm_params leaks to upstream API via Chat → Responses bridge BerriAI/litellm#20419
- 9: https://docs.aispendops.com/features/streaming
- 10: mnfst/llm-gateway@114e684
- 11: api-proxy: skip
stream_options.include_usageinjection on OpenAI Responses routes github/gh-aw-firewall#3697 - 12: OpenAI-compat providers: strip extra message keys before sending openclaw/openclaw#50374
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Map the relevant file and inspect the surrounding streaming code.
ast-grep outline internal/entity/models/openai.go --view expanded > /tmp/openai_outline.txt
sed -n '200,320p' internal/entity/models/openai.go | cat -n
printf '\n---\n'
sed -n '320,480p' internal/entity/models/openai.go | cat -n
printf '\n---\n'
sed -n '1040,1125p' internal/entity/models/openai.go | cat -n
printf '\n---\n'
# Find provider-specific config or mentions of OpenAI-compatible providers.
rg -n "OpenAI-compat|OpenAI compatible|stream_options|include_usage|base_url|provider" internal/entity/models internal -g '!**/*_test.go'Repository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Check whether the codebase has any provider-specific opt-in/feature detection around usage streaming.
rg -n "include_usage|stream_options|usage.*stream|stream.*usage|OpenAI-compatible|compat" . -g '!**/*_test.go' | sed -n '1,220p'Repository: infiniflow/ragflow
Length of output: 26612
Guard stream_options.include_usage for incompatible providers.
Sending this on every streaming request can break strict OpenAI-compatible backends that reject unknown fields. Make it opt-in per provider, or retry without stream_options on 400/422.
🧰 Tools
🪛 golangci-lint (2.12.2)
[error] 270-270: : # ragflow/internal/ingestion/compilation/extractor [ragflow/internal/ingestion/compilation/extractor.test]
internal/ingestion/compilation/extractor/dep_relation.go:270:9: undefined: Entity
internal/ingestion/compilation/extractor/dep_relation.go:281:69: undefined: Entity
internal/ingestion/compilation/extractor/dep_relation.go:281:109: undefined: Relation
internal/ingestion/compilation/extractor/dep_relation.go:353:27: undefined: Relation
internal/ingestion/compilation/extractor/dep_relation.go:401:37: undefined: Entity
internal/ingestion/compilation/extractor/dep_relation.go:416:56: undefined: Entity
internal/ingestion/compilation/extractor/dep_relation.go:430:97: undefined: Entity
internal/ingestion/compilation/extractor/dep_relation.go:505:90: undefined: Entity
internal/ingestion/compilation/extractor/dep_relation.go:505:113: undefined: Relation
internal/ingestion/compilation/extractor/dep_relation.go:604:88: undefined: Entity
internal/ingestion/compilation/extractor/dep_relation.go:604:88: too many errors
(typecheck)
🤖 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/openai.go` around lines 260 - 271, The streaming
request body in OpenAI request construction unconditionally adds
stream_options.include_usage, which can break providers that do not support it.
Update the request-building path in the openai model code so stream_options is
only added for compatible providers or when explicitly enabled, and ensure the
relevant request builder (where reqBody is assembled) can fall back to sending
stream without stream_options after a 400/422 response.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16565 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
### Summary Port the following PRs to GO in this PR infiniflow#16420 infiniflow#13295
### Summary Port the following PRs to GO in this PR infiniflow#16420 infiniflow#13295
Summary
Port the following PRs to GO in this PR
#16420
#13295