Skip to content

feat(go-models): unify OpenAI-compatible token usage extraction - #17625

Closed
jay77721 wants to merge 8 commits into
infiniflow:mainfrom
jay77721:feat/openai-usage-parser
Closed

jay77721 wants to merge 8 commits into
infiniflow:mainfrom
jay77721:feat/openai-usage-parser

Conversation

@jay77721

@jay77721 jay77721 commented Jul 31, 2026 •

Copy link
Copy Markdown
Member

Summary

Related to #17284.

  • Add usage_parser.go with extractOpenAIUsage / extractOpenAIStreamUsage
    that try multiple field names (prompt_tokens/input_tokens,
    completion_tokens/output_tokens) for cross-provider compatibility.
  • Add parser_config.go with ParserConfig struct and OpenAIParserConfig
    constant to map protocols to parsers.
  • Add response_handler.go with HandleNonStreamingResponse and
    HandleStreamingResponse as single entry points that extract usage,
    populate chatConfig.UsageResult, and emit a StreamUsage log.
  • Extend base_model.go with doRequest / doStreamRequest to remove
    per-driver HTTP boilerplate.
  • Migrate deepseek, groq, longcat, nvidia, siliconflow drivers to the
    shared handlers, cutting ~100 lines per driver and adding a
    consistent StreamUsage log line (model + prompt + completion + total).
  • Add usage_parser_test.go covering standard format, total fallback,
    missing usage key, and multi-type numeric parsing.

Drivers not yet migrated continue to work unchanged; they can be
switched over incrementally by replacing their body of ChatWithMessages
/ ChatStreamlyWithSender with the shared handlers.

Testing

  • bash build.sh --test ./internal/entity/models/... passes.
  • Manual testing with deepseek/nvidia confirms StreamUsage log appears
    with correct model name and token counts.

Consolidate duplicate HTTP request, response parsing, and usage
extraction code across OpenAI-compatible drivers into shared helpers.

- Add usage_parser.go with extractOpenAIUsage / extractOpenAIStreamUsage
  that try multiple field names (prompt_tokens/input_tokens,
  completion_tokens/output_tokens) for cross-provider compatibility.
- Add parser_config.go with ParserConfig struct and OpenAIParserConfig
  constant to map protocols to parsers.
- Add response_handler.go with HandleNonStreamingResponse and
  HandleStreamingResponse as single entry points that extract usage,
  populate chatConfig.UsageResult, and emit a StreamUsage log.
- Extend base_model.go with doRequest / doStreamRequest to remove
  per-driver HTTP boilerplate.
- Migrate deepseek, groq, longcat, nvidia, siliconflow drivers to the
  shared handlers, cutting ~100 lines per driver and adding a
  consistent StreamUsage log line (model + prompt + completion + total).
- Add usage_parser_test.go covering standard format, total fallback,
  missing usage key, and multi-type numeric parsing.

Drivers not yet migrated continue to work unchanged; they can be
switched over incrementally by replacing their body of ChatWithMessages
/ ChatStreamlyWithSender with the shared handlers.

Co-authored-by: jay <<EMAIL>>
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code 💞 feature Feature request, pull request that fullfill a new feature. labels Jul 31, 2026
@jay77721 jay77721 added the ci Continue Integration label Jul 31, 2026
@jay77721
jay77721 requested review from Harry-Hz-Zhang and Haruko386 and removed request for Haruko386 July 31, 2026 08:03
@jay77721 jay77721 added ci Continue Integration and removed ci Continue Integration labels Jul 31, 2026
@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5eb34488-d302-48bb-a187-677e0985fdde

📥 Commits

Reviewing files that changed from the base of the PR and between c98b0e6 and 7588b53.

📒 Files selected for processing (1)
  • .gitignore

📝 Walkthrough

Walkthrough

The change adds shared authenticated request and response handling, OpenAI-compatible usage parsing, and provider migrations for five chat models. It also adds usage-parser tests and removes repository ignore rules.

Changes

Model response handling

Layer / File(s) Summary
Parser contracts and usage extraction
internal/entity/models/parser_config.go, internal/entity/models/usage_parser.go, internal/entity/models/usage_parser_test.go
Adds parser configuration, fallback token fields, numeric conversions, and table-driven usage-parser tests.
Shared request transport
internal/entity/models/base_model.go
Adds timed authenticated JSON request helpers, status validation, response-body cleanup, and mustMarshal.
Shared response handlers
internal/entity/models/response_handler.go
Adds common non-streaming and SSE handling for content, reasoning, tool calls, usage, request IDs, and completion signaling.
Provider integrations
internal/entity/models/deepseek.go, internal/entity/models/groq.go, internal/entity/models/longcat.go, internal/entity/models/nvidia.go, internal/entity/models/siliconflow.go
Replaces provider-specific request, parsing, usage, tool-call, and streaming logic with shared helpers.

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

Possibly related PRs

Suggested labels: 🧪 test

Suggested reviewers: hz-186

Poem

A rabbit checks each token stream,
Shared handlers keep responses clean.
Content, tools, and usage align,
Then [DONE] closes every line.
Hop by hop, the models shine.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 70.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 clearly describes the main change: unified OpenAI-compatible token usage extraction.
Description check ✅ Passed The description includes a clear summary, implementation details, migration scope, testing results, and related issue context.
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.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Fix failing CI checks

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 marked this pull request as draft July 31, 2026 08:07
@jay77721
jay77721 marked this pull request as ready for review July 31, 2026 08:07
@jay77721 jay77721 closed this Jul 31, 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: 8

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/entity/models/deepseek.go (2)

195-222: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Four drivers migrated the non-streaming transport but not the streaming transport. Each of these drivers now calls doRequest for the non-streaming path, then still hand-rolls marshaling, context.WithTimeout, request construction, Authorization headers, httpClient.Do, defer resp.Body.Close(), and status validation for the streaming path. internal/entity/models/longcat.go line 140 shows the shared doStreamRequest form. The shared and local transports now coexist in the same files, which the coding guidelines forbid.

  • internal/entity/models/deepseek.go#L195-L222: replace the block with d.baseModel.doStreamRequest(ctx, url, apiConfig, reqBody, streamCallTimeout, func(respBody io.ReadCloser) error { return HandleStreamingResponse(respBody, modelUsage, chatModelConfig, OpenAIParserConfig, sender) }), then drop the unused bytes, encoding/json, and net/http imports.
  • internal/entity/models/groq.go#L159-L186: replace the block with g.baseModel.doStreamRequest(...), and first confirm that doStreamRequest sets Accept: text/event-stream, which line 173 sets today.
  • internal/entity/models/nvidia.go#L137-L159: replace the block with n.baseModel.doStreamRequest(...), which also removes the mustMarshal panic path at line 140.
  • internal/entity/models/siliconflow.go#L155-L182: replace the block with s.baseModel.doStreamRequest(...), then drop the unused bytes, encoding/json, and net/http imports.

Based on the coding guideline "When old and new implementations coexist, converge to one implementation path unless an external contract requires compatibility."

🤖 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/deepseek.go` around lines 195 - 222, Converge all
streaming transports on BaseModel.doStreamRequest instead of duplicating request
setup and response validation. In internal/entity/models/deepseek.go:195-222,
internal/entity/models/groq.go:159-186,
internal/entity/models/nvidia.go:137-159, and
internal/entity/models/siliconflow.go:155-182, replace each hand-rolled block
with the corresponding model’s doStreamRequest and a HandleStreamingResponse
callback; verify the Groq helper preserves the text/event-stream Accept header.
Remove imports made unused in deepseek.go and siliconflow.go, and ensure the
Nvidia change eliminates the mustMarshal panic path.

Source: Coding guidelines


158-158: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use d.baseModel.URLSuffix.Chat in the streaming path.

ChatWithMessages uses the configured URLSuffix.Chat, while ChatStreamlyWithSender hard-codes /chat/completions. If the provider overrides url_suffix.chat, streaming requests hit a different endpoint than non-streaming requests; make the streaming path use d.baseModel.URLSuffix.Chat.

🤖 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/deepseek.go` at line 158, Update the URL construction
in ChatStreamlyWithSender to append the configured d.baseModel.URLSuffix.Chat
instead of hard-coding "/chat/completions", matching the endpoint behavior used
by ChatWithMessages.
🧹 Nitpick comments (5)
internal/entity/models/base_model.go (1)

151-159: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Converge the three request helpers into one.

doRequest, doStreamRequest, and the pre-existing PostJSONRequest (line 379) each build the same POST request. The two new helpers differ only in body handling. Extract the shared marshal-plus-build step, or build the new helpers on top of PostJSONRequest, so header and timeout policy has one owner.

Also applies to: 196-204

🤖 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/base_model.go` around lines 151 - 159, Consolidate
request construction across BaseModel.doRequest, BaseModel.doStreamRequest, and
PostJSONRequest so a single helper owns JSON marshaling, POST setup, headers,
and timeout policy. Refactor the two new helpers to reuse that shared path,
preserving their distinct response/body handling while removing duplicated
request-building logic.

Source: Coding guidelines

internal/entity/models/usage_parser.go (2)

42-60: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Collapse the duplicate usage parsers.

extractOpenAIStreamUsage is identical to extractOpenAIUsage except for the rawUsage == nil test. That test is unreachable in practice: if event["usage"] holds nil, the type assertion already sets ok to false, and reads on a nil map are safe. Keep one implementation and reference it from both ParserConfig fields.

♻️ Proposed refactor
-// extractOpenAIStreamUsage extracts token usage from one OpenAI-compatible
-// streaming event. A missing or null usage field is not an error.
-func extractOpenAIStreamUsage(event map[string]any) (*TokenUsage, bool) {
-	rawUsage, ok := event["usage"].(map[string]any)
-	if !ok || rawUsage == nil {
-		return nil, false
-	}
-
-	usage := &TokenUsage{}
-	usage.PromptTokens = extractToken(rawUsage, "prompt_tokens", "input_tokens")
-	usage.CompletionTokens = extractToken(rawUsage, "completion_tokens", "output_tokens")
-	usage.TotalTokens = extractToken(rawUsage, "total_tokens")
-
-	if usage.TotalTokens == 0 {
-		usage.TotalTokens = usage.PromptTokens + usage.CompletionTokens
-	}
-
-	return usage, true
-}
+// extractOpenAIStreamUsage extracts token usage from one OpenAI-compatible
+// streaming event. A missing or null usage field is not an error.
+func extractOpenAIStreamUsage(event map[string]any) (*TokenUsage, bool) {
+	return extractOpenAIUsage(event)
+}
🤖 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/usage_parser.go` around lines 42 - 60, Remove the
duplicate extractOpenAIStreamUsage function and eliminate the unreachable
rawUsage == nil check it contains, since a nil value at event["usage"] already
causes the type assertion to set ok to false. Keep the extractOpenAIUsage
implementation and update both ParserConfig field references to use the single
unified function instead of maintaining two identical implementations.

Source: Coding guidelines


64-82: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Continue to the next key when the value is not numeric.

extractToken returns 0 as soon as the first listed key exists, even if its value has an unsupported type. If a provider sends "prompt_tokens": "10" together with "input_tokens": 10, the result is 0 and the usage record is wrong. Move the fallback inside the type switch default.

♻️ Proposed fix
 	for _, k := range keys {
 		if v, ok := m[k]; ok {
 			switch val := v.(type) {
 			case float64:
 				return int(val)
 			case int:
 				return val
 			case int64:
 				return int(val)
 			case json.Number:
 				if n, err := val.Int64(); err == nil {
 					return int(n)
 				}
 			}
 		}
 	}

Keep the loop, but do not treat a present-but-unusable value as final; the code above already falls through to the next key only for json.Number parse failures. Add the same behavior for other types by removing the early return semantics, for example:

+			if n, ok := toInt(v); ok {
+				return n
+			}

where toInt performs the type switch and reports success.

🤖 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/usage_parser.go` around lines 64 - 82, The
extractToken function returns 0 when a key exists but its value cannot be
converted to a numeric type, instead of continuing to check the remaining keys.
Restructure the type switch statement by removing the early return pattern and
instead capturing successful numeric conversions, then explicitly continue to
the next key iteration only when a value cannot be converted. Ensure that all
unsupported types (string, bool, etc.) fall through to the next key in the loop,
not just json.Number parse failures, so that a key like "prompt_tokens": "10"
allows the loop to continue and check the next key like "input_tokens": 10.
internal/entity/models/usage_parser_test.go (1)

14-45: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add cases for the fallback keys and json.Number.

The fallback keys input_tokens and output_tokens are the new behavior in this PR, and json.Number is a supported branch in extractToken. Neither is covered.

💚 Proposed test additions
 		{
 			name: "no usage key",
 			body: map[string]any{
 				"choices": []any{map[string]any{"message": map[string]any{"content": "hi"}}},
 			},
 			want:   nil,
 			wantOK: false,
 		},
+		{
+			name: "input/output token aliases",
+			body: map[string]any{
+				"usage": map[string]any{
+					"input_tokens":  float64(7),
+					"output_tokens": float64(3),
+				},
+			},
+			want:   &TokenUsage{PromptTokens: 7, CompletionTokens: 3, TotalTokens: 10},
+			wantOK: true,
+		},
 	if got := extractToken(m, "missing", "a"); got != 1 {
 		t.Fatalf("extractToken(missing, a) = %d, want 1", got)
 	}
+	if got := extractToken(map[string]any{"d": json.Number("4")}, "d"); got != 4 {
+		t.Fatalf("extractToken(d) = %d, want 4", got)
+	}
 }

Add "encoding/json" to the test imports for the json.Number case.

Also applies to: 120-142

🤖 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/usage_parser_test.go` around lines 14 - 45, Add two
new test cases to the test table in usage_parser_test.go to cover the fallback
behavior: one test case that provides input_tokens and output_tokens keys
instead of prompt_tokens and completion_tokens to verify the fallback parsing
works correctly, and another test case that uses json.Number values instead of
float64 for the token counts to verify that numeric type is properly handled.
Include "encoding/json" in the test file imports to support constructing
json.Number values for the test case.
internal/entity/models/groq.go (1)

90-106: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the unused per-provider response structs. These definitions have no remaining Go references and do not participate in the migrated handlers; delete them, including groqChatResponse, groqChatUsage, groqChatMessage, groqChatChoice, LongCatChatResponse, and SiliconflowChatResponse.

🤖 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/groq.go` around lines 90 - 106, Remove the unused
provider-specific response model definitions: groqChatResponse, groqChatUsage,
groqChatMessage, and groqChatChoice from internal/entity/models/groq.go:90-106;
LongCatChatResponse from internal/entity/models/longcat.go:55-78; and
SiliconflowChatResponse from internal/entity/models/siliconflow.go:61-88. Ensure
no replacement code is added.

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/base_model.go`:
- Around line 187-194: Remove mustMarshal from base_model.go and update NVIDIA’s
request path in the relevant method to call baseModel.doStreamRequest with the
existing context, URL, API config, request body, timeout, and streaming response
callback. Preserve the prior wrapped-error behavior through the shared helper so
marshal failures return to the caller rather than panicking.

In `@internal/entity/models/groq.go`:
- Around line 127-131: Update the non-streaming response extraction used by the
Groq request flow around HandleNonStreamingResponse so extractContentAndChoices
preserves message.reasoning when reasoning_content is absent, allowing it to
populate ChatResponse.ReasonContent while retaining the existing
reasoning_content behavior.

In `@internal/entity/models/longcat.go`:
- Around line 100-105: Update the request flow in the caller around
baseModel.doRequest and align its response-size protection with
longCatMaxListModelsResponseBytes used by ListModels. Ensure doRequest applies
an io.LimitReader or equivalent maximum-body bound before reading the response,
while preserving the existing error handling and HandleNonStreamingResponse
behavior.

In `@internal/entity/models/nvidia.go`:
- Line 140: Replace mustMarshal in the request construction near the NVIDIA
request flow with explicit JSON marshaling of reqBody, check the marshal error,
and return that error before calling http.NewRequestWithContext. Preserve the
existing request behavior for successfully serialized bodies while ensuring
invalid values such as NaN or Inf produce an error rather than a panic.

In `@internal/entity/models/response_handler.go`:
- Around line 30-35: Rename HandleNonStreamingResponse and
HandleStreamingResponse to the unexported handleNonStreamingResponse and
handleStreamingResponse, then update every call site within package models to
use the new names while preserving their existing behavior.
- Around line 41-58: In HandleNonStreamingResponse, guard the ResponseParser
callback so nil cfg or a config without ResponseParser is skipped without
panicking, while retaining usage extraction when available. Move the usage info
log outside the chatConfig != nil block so it always runs when usage is present,
update its event label to distinguish non-streaming responses from StreamUsage,
and keep chatConfig.UsageResult assignment conditional.
- Around line 81-134: After the ParseSSEStream loop in the streaming response
handler, convert accumulatedToolCalls into chatConfig.ToolCallsResult when
chatConfig is non-nil, ordering entries by their delta index. Add the required
sort import and match the existing ChatConfig.ToolCallsResult element type,
preserving the accumulated tool-call data for all streaming providers.
- Around line 128-137: Update HandleStreamingResponse to preserve the done state
and upstream event["id"] returned by ParseSSEStream. Pass the event id to
recordResponseUsage, falling back to that id when [DONE] is absent; when the
stream ends before usage or completion, record usage with an empty request id
only without a completion terminal, otherwise return the incomplete-stream error
instead of always sending [DONE].

---

Outside diff comments:
In `@internal/entity/models/deepseek.go`:
- Around line 195-222: Converge all streaming transports on
BaseModel.doStreamRequest instead of duplicating request setup and response
validation. In internal/entity/models/deepseek.go:195-222,
internal/entity/models/groq.go:159-186,
internal/entity/models/nvidia.go:137-159, and
internal/entity/models/siliconflow.go:155-182, replace each hand-rolled block
with the corresponding model’s doStreamRequest and a HandleStreamingResponse
callback; verify the Groq helper preserves the text/event-stream Accept header.
Remove imports made unused in deepseek.go and siliconflow.go, and ensure the
Nvidia change eliminates the mustMarshal panic path.
- Line 158: Update the URL construction in ChatStreamlyWithSender to append the
configured d.baseModel.URLSuffix.Chat instead of hard-coding
"/chat/completions", matching the endpoint behavior used by ChatWithMessages.

---

Nitpick comments:
In `@internal/entity/models/base_model.go`:
- Around line 151-159: Consolidate request construction across
BaseModel.doRequest, BaseModel.doStreamRequest, and PostJSONRequest so a single
helper owns JSON marshaling, POST setup, headers, and timeout policy. Refactor
the two new helpers to reuse that shared path, preserving their distinct
response/body handling while removing duplicated request-building logic.

In `@internal/entity/models/groq.go`:
- Around line 90-106: Remove the unused provider-specific response model
definitions: groqChatResponse, groqChatUsage, groqChatMessage, and
groqChatChoice from internal/entity/models/groq.go:90-106; LongCatChatResponse
from internal/entity/models/longcat.go:55-78; and SiliconflowChatResponse from
internal/entity/models/siliconflow.go:61-88. Ensure no replacement code is
added.

In `@internal/entity/models/usage_parser_test.go`:
- Around line 14-45: Add two new test cases to the test table in
usage_parser_test.go to cover the fallback behavior: one test case that provides
input_tokens and output_tokens keys instead of prompt_tokens and
completion_tokens to verify the fallback parsing works correctly, and another
test case that uses json.Number values instead of float64 for the token counts
to verify that numeric type is properly handled. Include "encoding/json" in the
test file imports to support constructing json.Number values for the test case.

In `@internal/entity/models/usage_parser.go`:
- Around line 42-60: Remove the duplicate extractOpenAIStreamUsage function and
eliminate the unreachable rawUsage == nil check it contains, since a nil value
at event["usage"] already causes the type assertion to set ok to false. Keep the
extractOpenAIUsage implementation and update both ParserConfig field references
to use the single unified function instead of maintaining two identical
implementations.
- Around line 64-82: The extractToken function returns 0 when a key exists but
its value cannot be converted to a numeric type, instead of continuing to check
the remaining keys. Restructure the type switch statement by removing the early
return pattern and instead capturing successful numeric conversions, then
explicitly continue to the next key iteration only when a value cannot be
converted. Ensure that all unsupported types (string, bool, etc.) fall through
to the next key in the loop, not just json.Number parse failures, so that a key
like "prompt_tokens": "10" allows the loop to continue and check the next key
like "input_tokens": 10.
🪄 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: 99e1bf88-6baf-40c4-8536-0b295ec98a1d

📥 Commits

Reviewing files that changed from the base of the PR and between 93513eb and c98b0e6.

📒 Files selected for processing (11)
  • .gitignore
  • internal/entity/models/base_model.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/groq.go
  • internal/entity/models/longcat.go
  • internal/entity/models/nvidia.go
  • internal/entity/models/parser_config.go
  • internal/entity/models/response_handler.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/usage_parser.go
  • internal/entity/models/usage_parser_test.go

Comment on lines +187 to +194
// mustMarshal marshals v to JSON, panicking on error.
func mustMarshal(v any) []byte {
b, err := json.Marshal(v)
if err != nil {
panic(fmt.Sprintf("failed to marshal: %v", err))
}
return b
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Do not panic on marshal failure in the request path.

mustMarshal converts a recoverable error into a process-level panic. The only call site is internal/entity/models/nvidia.go line 140, which previously returned a wrapped error. buildRequestBody places caller-controlled values into the map, so an unmarshalable value (for example a channel or a NaN float64 in a config field) crashes the request goroutine instead of returning an error to the caller.

Delete mustMarshal and let NVIDIA use doStreamRequest, which already marshals and returns the error. That also removes the duplicated request setup in nvidia.go.

🛠️ Proposed fix
-// mustMarshal marshals v to JSON, panicking on error.
-func mustMarshal(v any) []byte {
-	b, err := json.Marshal(v)
-	if err != nil {
-		panic(fmt.Sprintf("failed to marshal: %v", err))
-	}
-	return b
-}

In internal/entity/models/nvidia.go, replace the manual request block with the shared helper:

return n.baseModel.doStreamRequest(ctx, url, apiConfig, reqBody, streamCallTimeout, func(respBody io.ReadCloser) error {
	return HandleStreamingResponse(respBody, modelUsage, modelConfig, OpenAIParserConfig, sender)
})
📝 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
// mustMarshal marshals v to JSON, panicking on error.
func mustMarshal(v any) []byte {
b, err := json.Marshal(v)
if err != nil {
panic(fmt.Sprintf("failed to marshal: %v", err))
}
return b
}
🤖 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/base_model.go` around lines 187 - 194, Remove
mustMarshal from base_model.go and update NVIDIA’s request path in the relevant
method to call baseModel.doStreamRequest with the existing context, URL, API
config, request body, timeout, and streaming response callback. Preserve the
prior wrapped-error behavior through the shared helper so marshal failures
return to the caller rather than panicking.

Source: Coding guidelines

Comment on lines +127 to +131
body, err := g.baseModel.doRequest(ctx, url, apiConfig, reqBody, nonStreamCallTimeout)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
return nil, err
}

return parseChatCompletionResponse(body, chatModelConfig, modelUsage, func(body []byte, _ *ChatConfig) (chatResponseParts, error) {
var result groqChatResponse
if err := json.Unmarshal(body, &result); err != nil {
return chatResponseParts{}, fmt.Errorf("failed to parse response: %w", err)
}
if result.Error != nil {
return chatResponseParts{}, fmt.Errorf("groq: upstream error: %v", result.Error)
}
if len(result.Choices) == 0 {
return chatResponseParts{}, fmt.Errorf("no choices in response")
}

content := result.Choices[0].Message.Content
reasonContent := result.Choices[0].Message.ReasoningContent
if reasonContent == "" {
reasonContent = result.Choices[0].Message.Reasoning
}

parts := chatResponseParts{
RequestID: result.ID,
Content: &content,
ReasonContent: &reasonContent,
}
if result.Usage != nil {
parts.Usage = &TokenUsage{
PromptTokens: result.Usage.PromptTokens,
CompletionTokens: result.Usage.CompletionTokens,
TotalTokens: result.Usage.TotalTokens,
}
}
return parts, nil
})
return HandleNonStreamingResponse(body, modelUsage, chatModelConfig, OpenAIParserConfig)

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 | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Confirm the removed Groq parsing read the `reasoning` field and that nothing else reads it now.
set -euo pipefail

echo "===== current readers of the reasoning field ====="
rg -n -C3 '"reasoning"|\breasoning\b' internal/entity/models --glob '!*_test.go'

echo "===== removed Groq parsing ====="
p=$(fd -t f 'groq.go' internal/entity/models)
git diff HEAD~1 -- "$p" | rg -n '^-' | rg -n 'Reasoning|reasoning' || echo "(no removed reasoning handling found)"

echo "===== groqChatMessage / groqChatResponse consumers ====="
rg -n -C3 'groqChatResponse|groqChatMessage|groqChatChoice|groqChatUsage' internal/entity/models

Repository: infiniflow/ragflow

Length of output: 48829


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "===== groq.go relevant sections ====="
sed -n '60,140p' internal/entity/models/groq.go

echo "===== response_handler.go relevant extraction section ====="
sed -n '140,185p' internal/entity/models/response_handler.go

echo "===== all direct usages of groq structs/message fields ====="
rg -n 'ReasoningContent|Reasoning|reasoning_content|reasoning|groqChatResponse|groqChatChoice|groqChatMessage' internal --glob '!*_test.go'

Repository: infiniflow/ragflow

Length of output: 50374


Preserve Groq reasoning as fallback.

Groq gpt-oss models request include_reasoning and can return reasoning in message.reasoning. extractContentAndChoices currently only reads reasoning_content, so that reasoning is dropped before ChatResponse.ReasonContent is set. Add a reasoning fallback in the non-streaming extractor, or use a Groq-specific extraction step.

🤖 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/groq.go` around lines 127 - 131, Update the
non-streaming response extraction used by the Groq request flow around
HandleNonStreamingResponse so extractContentAndChoices preserves
message.reasoning when reasoning_content is absent, allowing it to populate
ChatResponse.ReasonContent while retaining the existing reasoning_content
behavior.

Comment on lines +100 to +105
body, err := l.baseModel.doRequest(ctx, url, apiConfig, reqBody, nonStreamCallTimeout)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}

ctx, cancel := context.WithTimeout(ctx, nonStreamCallTimeout)
defer cancel()

req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}

req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))

resp, err := l.baseModel.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}

if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
return nil, err
}

return parseChatCompletionResponse(body, chatModelConfig, modelUsage, func(body []byte, chatConfig *ChatConfig) (chatResponseParts, error) {
var result LongCatChatResponse
if err := json.Unmarshal(body, &result); err != nil {
return chatResponseParts{}, fmt.Errorf("failed to parse response: %w", err)
}
if len(result.Choices) == 0 {
return chatResponseParts{}, fmt.Errorf("no choices in response")
}

choice := &result.Choices[0]
content := choice.Message.Content
// LongCat-Flash-Thinking may emit all output as reasoning_content
// with content left empty. That is a valid response — only reject when
// there is neither content, reasoning, nor tool calls.
if content == "" && choice.Message.ReasoningContent == "" && len(choice.Message.ToolCalls) == 0 {
return chatResponseParts{}, fmt.Errorf("invalid content format")
}

// reasoning_content is typically prefixed with a leading newline.
reasonContent := choice.Message.ReasoningContent
if reasonContent != "" && reasonContent[0] == '\n' {
reasonContent = reasonContent[1:]
}

usage := &TokenUsage{
PromptTokens: result.Usage.PromptTokens,
CompletionTokens: result.Usage.CompletionTokens,
TotalTokens: result.Usage.TotalTokens,
}

return chatResponseParts{
RequestID: result.ID,
Content: &content,
ReasonContent: &reasonContent,
ToolCalls: choice.Message.ToolCalls,
Usage: usage,
}, nil
})
return HandleNonStreamingResponse(body, modelUsage, chatModelConfig, OpenAIParserConfig)

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check whether doRequest bounds the response body read.
set -euo pipefail
p=$(fd -t f 'base_model.go' internal/entity/models)
rg -n -C6 'io.ReadAll|LimitReader|MaxBytes' "$p"

Repository: infiniflow/ragflow

Length of output: 1366


Bounds the response body in doRequest.

baseModel.doRequest reads the entire HTTP body with io.ReadAll and does not apply an io.LimitReader. Add a maximum response-size limit here, consistent with longCatMaxListModelsResponseBytes in ListModels, so large or hostile upstream responses cannot exhaust memory.

🤖 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/longcat.go` around lines 100 - 105, Update the request
flow in the caller around baseModel.doRequest and align its response-size
protection with longCatMaxListModelsResponseBytes used by ListModels. Ensure
doRequest applies an io.LimitReader or equivalent maximum-body bound before
reading the response, while preserving the existing error handling and
HandleNonStreamingResponse behavior.

defer cancel()

req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(mustMarshal(reqBody)))

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Inspect mustMarshal and check which numeric fields reach reqBody via buildRequestBody.
set -euo pipefail

echo "===== mustMarshal definition ====="
rg -n -B2 -A12 'func mustMarshal' internal/entity/models

echo "===== buildRequestBody ====="
rg -n -A60 'func buildRequestBody' internal/entity/models

echo "===== other mustMarshal call sites ====="
rg -n 'mustMarshal\(' internal/entity/models

Repository: infiniflow/ragflow

Length of output: 5585


🏁 Script executed:

#!/bin/bash
# Inspect the request-handling path around mustMarshal and inspect ChatConfig numeric field types.
set -euo pipefail

echo "===== nvidia doStreamRequest slice ====="
sed -n '120,160p' internal/entity/models/nvidia.go

echo "===== BaseModel doStreamRequest and json usage ====="
sed -n '186,245p' internal/entity/models/base_model.go
rg -n -n '"encoding/json"|json\.Marshal|json\.Unmarshal' internal/entity/models internal -g '*.go' | head -80

echo "===== ChatConfig type ====="
rg -n -B5 -A25 'type ChatConfig struct|Temperature.*float|TopP.*float|MaxTokens.*float|max_tokens|stream_mode' internal/entity models -g '*.go' | head -220

echo "===== JSON float invalid values behavior ====="
node - <<'JS'
console.log(require('node:util').format(JSON.stringify({nan:NaN}) === '[{"nan":null}]\n'));
JS
python3 - <<'PY'
import json
import math
print("NaN:", json.JSONEncoder().encode({"nan": float('nan')}))
print("Inf:", json.JSONEncoder().encode({"inf": float('inf')}))
try:
    json.dumps({"nan": float("nan")}")
    print("valid")
except Exception as e:
    print("exception:", type(e).__name__, str(e))
PY

Repository: infiniflow/ragflow

Length of output: 25796


🏁 Script executed:

#!/bin/bash
# Inspect the request-handling path around mustMarshal and inspect ChatConfig numeric field types.
set -euo pipefail

echo "===== nvidia doStreamRequest slice ====="
sed -n '120,160p' internal/entity/models/nvidia.go

echo "===== BaseModel doStreamRequest and json usage ====="
sed -n '186,245p' internal/entity/models/base_model.go
rg -n '"encoding/json"|json\.Marshal|json\.Unmarshal' internal/entity models -g '*.go' | head -80

echo "===== ChatConfig type ====="
rg -n -B5 -A25 'type ChatConfig struct|Temperature.*float|TopP.*float|MaxTokens.*float|max_tokens|stream_mode' internal/entity models -g '*.go' | head -220

echo "===== JSON float invalid values behavior ====="
node - <<'JS'
console.log(JSON.stringify({nan:NaN}) === '{"nan":null}');
try {
  JSON.stringify({nan: NaN});
  console.log("stringify ok");
} catch (e) {
  console.log("stringify exception:", e.message);
}
PY
python3 - <<'PY'
import json
print("NaN:", json.JSONEncoder().encode({"nan": float('nan')}))
print("Inf:", json.JSONEncoder().encode({"inf": float('inf')}))
try:
    json.dumps({"nan": float("nan")})
    print("valid")
except Exception as e:
    print("exception:", type(e).__name__, str(e))
PY

Repository: infiniflow/ragflow

Length of output: 9704


mustMarshal turns JSON serialization failures into a panic.

mustMarshal is defined to panic when json.Marshal fails, while reqBody receives caller-supplied chat config values such as temperature and top_p. Invalid values, such as a NaN/Inf float in those fields, should return an error instead of panicking the request goroutine.

Restore explicit error handling here.

🛠️ Proposed fix
-	req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(mustMarshal(reqBody)))
+	jsonData, err := json.Marshal(reqBody)
+	if err != nil {
+		return fmt.Errorf("failed to marshal request: %w", err)
+	}
+
+	req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))
 	if err != nil {
 		return fmt.Errorf("failed to create request: %w", err)
 	}
📝 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
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(mustMarshal(reqBody)))
jsonData, err := json.Marshal(reqBody)
if err != nil {
return fmt.Errorf("failed to marshal request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
🤖 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/nvidia.go` at line 140, Replace mustMarshal in the
request construction near the NVIDIA request flow with explicit JSON marshaling
of reqBody, check the marshal error, and return that error before calling
http.NewRequestWithContext. Preserve the existing request behavior for
successfully serialized bodies while ensuring invalid values such as NaN or Inf
produce an error rather than a panic.

Comment on lines +30 to +35
func HandleNonStreamingResponse(
body []byte,
modelUsage *common.ModelUsage,
chatConfig *ChatConfig,
cfg *ParserConfig,
) (*ChatResponse, error) {

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 | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Confirm no references to the two handlers exist outside package models.
set -euo pipefail
rg -n --type=go 'Handle(Non)?StreamingResponse' | rg -v '^internal/entity/models/' || echo "no external references"

Repository: infiniflow/ragflow

Length of output: 179


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Handler definitions:\n'
rg -n 'func Handle(Non)?StreamingResponse|--' internal/entity/models/response_handler.go || true

printf '\nCall sites across repository:\n'
rg -n 'Handle(Non)?StreamingResponse' --type=go || true

printf '\nPackage declaration for files listing references:\n'
for f in $(rg -l 'Handle(Non)?StreamingResponse' --type=go); do
  echo "$f: $(sed -n '1p' "$f")"
done

Repository: infiniflow/ragflow

Length of output: 277


Unexport the handlers.

HandleNonStreamingResponse and HandleStreamingResponse are only called from package models, so rename them to handleNonStreamingResponse and handleStreamingResponse and update the call sites.

🤖 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/response_handler.go` around lines 30 - 35, Rename
HandleNonStreamingResponse and HandleStreamingResponse to the unexported
handleNonStreamingResponse and handleStreamingResponse, then update every call
site within package models to use the new names while preserving their existing
behavior.

Source: Coding guidelines

Comment on lines +41 to +58
// Extract usage via the protocol-specific parser.
var usage *TokenUsage
if u, ok := cfg.ResponseParser(result); ok {
usage = u
}

// Extract content / reasoning_content / tool_calls.
content, reasonContent, toolCalls := extractContentAndChoices(result)

if usage != nil {
recordResponseUsage(modelUsage, extractRequestID(result), usage, "chat")
if chatConfig != nil {
chatConfig.UsageResult = usage
if model, ok := result["model"].(string); ok {
common.Info("StreamUsage", zap.String("model", model), zap.Int("prompt", usage.PromptTokens), zap.Int("completion", usage.CompletionTokens), zap.Int("total", usage.TotalTokens))
}
}
}

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Guard the parser callbacks and fix the log label.

Two points in this block:

  1. Line 43 calls cfg.ResponseParser without checking cfg or the field. A nil cfg, or a ParserConfig that only sets StreamParser, panics. HandleNonStreamingResponse is exported, so callers outside this file can construct a partial config.
  2. Line 55 logs the event name StreamUsage in the non-streaming path. The label is wrong here, and it collides with the streaming log at line 132. Log filters cannot separate the two paths.

Also, the log call sits inside if chatConfig != nil. Usage logging does not depend on chatConfig. Move it out so usage is logged for callers that pass a nil chatConfig.

🛠️ Proposed fix
 	// Extract usage via the protocol-specific parser.
 	var usage *TokenUsage
-	if u, ok := cfg.ResponseParser(result); ok {
-		usage = u
-	}
+	if cfg != nil && cfg.ResponseParser != nil {
+		if u, ok := cfg.ResponseParser(result); ok {
+			usage = u
+		}
+	}
 
 	// Extract content / reasoning_content / tool_calls.
 	content, reasonContent, toolCalls := extractContentAndChoices(result)
 
 	if usage != nil {
 		recordResponseUsage(modelUsage, extractRequestID(result), usage, "chat")
+		model, _ := result["model"].(string)
+		common.Info("ChatUsage", zap.String("model", model), zap.Int("prompt", usage.PromptTokens), zap.Int("completion", usage.CompletionTokens), zap.Int("total", usage.TotalTokens))
 		if chatConfig != nil {
 			chatConfig.UsageResult = usage
-			if model, ok := result["model"].(string); ok {
-				common.Info("StreamUsage", zap.String("model", model), zap.Int("prompt", usage.PromptTokens), zap.Int("completion", usage.CompletionTokens), zap.Int("total", usage.TotalTokens))
-			}
 		}
 	}
📝 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
// Extract usage via the protocol-specific parser.
var usage *TokenUsage
if u, ok := cfg.ResponseParser(result); ok {
usage = u
}
// Extract content / reasoning_content / tool_calls.
content, reasonContent, toolCalls := extractContentAndChoices(result)
if usage != nil {
recordResponseUsage(modelUsage, extractRequestID(result), usage, "chat")
if chatConfig != nil {
chatConfig.UsageResult = usage
if model, ok := result["model"].(string); ok {
common.Info("StreamUsage", zap.String("model", model), zap.Int("prompt", usage.PromptTokens), zap.Int("completion", usage.CompletionTokens), zap.Int("total", usage.TotalTokens))
}
}
}
// Extract usage via the protocol-specific parser.
var usage *TokenUsage
if cfg != nil && cfg.ResponseParser != nil {
if u, ok := cfg.ResponseParser(result); ok {
usage = u
}
}
// Extract content / reasoning_content / tool_calls.
content, reasonContent, toolCalls := extractContentAndChoices(result)
if usage != nil {
recordResponseUsage(modelUsage, extractRequestID(result), usage, "chat")
model, _ := result["model"].(string)
common.Info("ChatUsage", zap.String("model", model), zap.Int("prompt", usage.PromptTokens), zap.Int("completion", usage.CompletionTokens), zap.Int("total", usage.TotalTokens))
if chatConfig != nil {
chatConfig.UsageResult = usage
}
}
🤖 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/response_handler.go` around lines 41 - 58, In
HandleNonStreamingResponse, guard the ResponseParser callback so nil cfg or a
config without ResponseParser is skipped without panicking, while retaining
usage extraction when available. Move the usage info log outside the chatConfig
!= nil block so it always runs when usage is present, update its event label to
distinguish non-streaming responses from StreamUsage, and keep
chatConfig.UsageResult assignment conditional.

Comment on lines +81 to +134
var streamUsage *TokenUsage
accumulatedToolCalls := make(map[int]map[string]any)

var streamModel string
_, err := ParseSSEStream[map[string]any](body, func(event map[string]any) error {
if u, ok := cfg.StreamParser(event); ok {
streamUsage = u
}
if m, ok := event["model"].(string); ok {
streamModel = m
}

choices, ok := event["choices"].([]any)
if !ok || len(choices) == 0 {
return nil
}

firstChoice, ok := choices[0].(map[string]any)
if !ok {
return nil
}

delta, ok := firstChoice["delta"].(map[string]any)
if !ok {
return nil
}

accumulateToolCallDeltas(delta, accumulatedToolCalls)

if reasoningContent, ok := delta["reasoning_content"].(string); ok && reasoningContent != "" {
if err := sender(nil, &reasoningContent); err != nil {
return err
}
}

if content, ok := delta["content"].(string); ok && content != "" {
if err := sender(&content, nil); err != nil {
return err
}
}

return nil
})
if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}

if streamUsage != nil {
recordResponseUsage(modelUsage, "", streamUsage, "chat")
if chatConfig != nil {
chatConfig.UsageResult = streamUsage
common.Info("StreamUsage", zap.String("model", streamModel), zap.Int("prompt", streamUsage.PromptTokens), zap.Int("completion", streamUsage.CompletionTokens), zap.Int("total", streamUsage.TotalTokens))
}
}

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 | 🔴 Critical | ⚡ Quick win

Accumulated streaming tool calls are discarded.

Line 82 creates accumulatedToolCalls, and line 108 fills it from each delta. After the stream ends, nothing reads the map. chatConfig.ToolCallsResult is never set.

The callers depend on this handler to set the field. internal/entity/models/longcat.go line 136 and internal/entity/models/siliconflow.go line 146 clear chatModelConfig.ToolCallsResult before the request. The change details for the five migrated drivers state that provider-local tool-call accumulation moved into this handler. The result is that streaming tool calls now return empty for DeepSeek, Groq, LongCat, NVIDIA, and SiliconFlow.

Flush the accumulated map into chatConfig.ToolCallsResult after the loop, ordered by the delta index.

🐛 Proposed fix
 	if err != nil {
 		return fmt.Errorf("failed to scan response body: %w", err)
 	}
 
+	if chatConfig != nil && len(accumulatedToolCalls) > 0 {
+		indexes := make([]int, 0, len(accumulatedToolCalls))
+		for idx := range accumulatedToolCalls {
+			indexes = append(indexes, idx)
+		}
+		sort.Ints(indexes)
+		toolCalls := make([]map[string]any, 0, len(indexes))
+		for _, idx := range indexes {
+			toolCalls = append(toolCalls, accumulatedToolCalls[idx])
+		}
+		chatConfig.ToolCallsResult = toolCalls
+	}
+
 	if streamUsage != nil {

Add "sort" to the import block. Confirm the element type of ChatConfig.ToolCallsResult before applying this diff.

📝 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
var streamUsage *TokenUsage
accumulatedToolCalls := make(map[int]map[string]any)
var streamModel string
_, err := ParseSSEStream[map[string]any](body, func(event map[string]any) error {
if u, ok := cfg.StreamParser(event); ok {
streamUsage = u
}
if m, ok := event["model"].(string); ok {
streamModel = m
}
choices, ok := event["choices"].([]any)
if !ok || len(choices) == 0 {
return nil
}
firstChoice, ok := choices[0].(map[string]any)
if !ok {
return nil
}
delta, ok := firstChoice["delta"].(map[string]any)
if !ok {
return nil
}
accumulateToolCallDeltas(delta, accumulatedToolCalls)
if reasoningContent, ok := delta["reasoning_content"].(string); ok && reasoningContent != "" {
if err := sender(nil, &reasoningContent); err != nil {
return err
}
}
if content, ok := delta["content"].(string); ok && content != "" {
if err := sender(&content, nil); err != nil {
return err
}
}
return nil
})
if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
if streamUsage != nil {
recordResponseUsage(modelUsage, "", streamUsage, "chat")
if chatConfig != nil {
chatConfig.UsageResult = streamUsage
common.Info("StreamUsage", zap.String("model", streamModel), zap.Int("prompt", streamUsage.PromptTokens), zap.Int("completion", streamUsage.CompletionTokens), zap.Int("total", streamUsage.TotalTokens))
}
}
var streamUsage *TokenUsage
accumulatedToolCalls := make(map[int]map[string]any)
var streamModel string
_, err := ParseSSEStream[map[string]any](body, func(event map[string]any) error {
if u, ok := cfg.StreamParser(event); ok {
streamUsage = u
}
if m, ok := event["model"].(string); ok {
streamModel = m
}
choices, ok := event["choices"].([]any)
if !ok || len(choices) == 0 {
return nil
}
firstChoice, ok := choices[0].(map[string]any)
if !ok {
return nil
}
delta, ok := firstChoice["delta"].(map[string]any)
if !ok {
return nil
}
accumulateToolCallDeltas(delta, accumulatedToolCalls)
if reasoningContent, ok := delta["reasoning_content"].(string); ok && reasoningContent != "" {
if err := sender(nil, &reasoningContent); err != nil {
return err
}
}
if content, ok := delta["content"].(string); ok && content != "" {
if err := sender(&content, nil); err != nil {
return err
}
}
return nil
})
if err != nil {
return fmt.Errorf("failed to scan response body: %w", err)
}
if chatConfig != nil && len(accumulatedToolCalls) > 0 {
indexes := make([]int, 0, len(accumulatedToolCalls))
for idx := range accumulatedToolCalls {
indexes = append(indexes, idx)
}
sort.Ints(indexes)
toolCalls := make([]map[string]any, 0, len(indexes))
for _, idx := range indexes {
toolCalls = append(toolCalls, accumulatedToolCalls[idx])
}
chatConfig.ToolCallsResult = toolCalls
}
if streamUsage != nil {
recordResponseUsage(modelUsage, "", streamUsage, "chat")
if chatConfig != nil {
chatConfig.UsageResult = streamUsage
common.Info("StreamUsage", zap.String("model", streamModel), zap.Int("prompt", streamUsage.PromptTokens), zap.Int("completion", streamUsage.CompletionTokens), zap.Int("total", streamUsage.TotalTokens))
}
}
🤖 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/response_handler.go` around lines 81 - 134, After the
ParseSSEStream loop in the streaming response handler, convert
accumulatedToolCalls into chatConfig.ToolCallsResult when chatConfig is non-nil,
ordering entries by their delta index. Add the required sort import and match
the existing ChatConfig.ToolCallsResult element type, preserving the accumulated
tool-call data for all streaming providers.

Comment on lines +128 to +137
if streamUsage != nil {
recordResponseUsage(modelUsage, "", streamUsage, "chat")
if chatConfig != nil {
chatConfig.UsageResult = streamUsage
common.Info("StreamUsage", zap.String("model", streamModel), zap.Int("prompt", streamUsage.PromptTokens), zap.Int("completion", streamUsage.CompletionTokens), zap.Int("total", streamUsage.TotalTokens))
}
}

endOfStream := "[DONE]"
return sender(&endOfStream, 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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check what terminal-event validation the migrated drivers used before delegating to
# HandleStreamingResponse, and whether ParseSSEStream reports stream termination.
set -euo pipefail

echo "===== ParseSSEStream signature and return value ====="
ast-grep run --pattern 'func ParseSSEStream[$$$]($$$) ($$$) { $$$ }' --lang go internal/entity/models || \
  rg -n -A30 'func ParseSSEStream' internal/entity/models

echo "===== previous terminal-event checks in migrated drivers ====="
for f in deepseek groq longcat nvidia siliconflow; do
  p=$(fd -t f "${f}.go" internal/entity/models || true)
  [ -z "$p" ] && continue
  echo "--- $p ---"
  git diff HEAD~1 -- "$p" | rg -n 'DONE|finish_reason|terminal|stop|incomplete' || echo "(no terminal-related delta found)"
done

echo "===== remaining terminal validation elsewhere in the package ====="
rg -n -C3 'finish_reason|\[DONE\]' internal/entity/models --glob '!*_test.go'

Repository: infiniflow/ragflow

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "===== response_handler.go locations ====="
rg -n -C4 'recordResponseUsage|extractRequestID|streamUsage|ParseSSEStream|HandleStreamingResponse|sender\(&endOfStream' internal/entity/models/response_handler.go

echo "===== response_handler.go imports / relevant struct types ====="
sed -n '1,180p' internal/entity/models/response_handler.go

echo "===== candidate SSE/chat events with String() id fields ====="
rg -n -C3 'type .*SSE|type .*event|func \(.*\) String\(\) string|String\(\) string' internal/entity/models --glob '*.go' --glob '!*_test.go' | head -n 220

echo "===== relevant ChatStreamlyWithSender calls using ParseSSEStream ====="
python3 - <<'PY'
from pathlib import Path
import re
patterns = [r'ParseSSEStream\(\s*resp\.Body\s*,\s*func\s*\(([^)]+)\)\s*error\s*\{', r'func \(\w+\) ChatSteamlyWithSender[^{]*\{', r'func\s+ChatStreamlyWithSender[^{]*\{']
for path in sorted(Path('internal/entity/models').glob('*.go')):
    text = path.read_text(errors='ignore')
    # basic outline: functions and first ~45 lines after each call
    for m in re.finditer(r'ParseSSEStream\(', text):
        start=max(0,m.start()-220); end=m.start()+350
        snippet=text[start:end].splitlines()
        first_lines=[]; found=0
        for i, line in enumerate(snippet):
            if 'func ' in line: first_lines.append(line.strip()); found=1
            if i>25: break
        print(f'\n--- {path}:{text[:m.start()].count(chr(10))+1} ---')
        print('\n'.join([f'{i}: {line}' for i,line in enumerate(snippet[:50], start=text[:start].count(chr(10))+1)]))
PY

Repository: infiniflow/ragflow

Length of output: 7924


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "===== base_model.ParseSSEStream implementation ====="
sed -n '250,310p' internal/entity/models/base_model.go

echo "===== deepseek/groq/longcat/siliconflow call sites and imports/configs ====="
for f in deepseek groq longcat siliconflow; do
  path="internal/entity/models/${f}.go"
  echo "--- $path ---"
  rg -n -C3 'ChatStreamlyWithSender|HandleStreamingResponse|ParseSSEStream|ParserConfig|APIConfig|client|stream' "$path" | head -n 200
done

echo "===== recordResponseUsage and ModelUsage definitions/usages ====="
rg -n -C4 'func recordResponseUsage|recordResponseUsage\(|type ModelUsage|type.*UsageResult|UsageResult' internal/internal internal/common internal/entity internal/rag flow deepseek groq longcat siliconflow --glob '!*_test.go' || true

Repository: infiniflow/ragflow

Length of output: 50374


Propagate SSE completion state and request id into stream usage recording.

ParseSSEStream returns done when it sees terminal [DONE], but HandleStreamingResponse ignores it and always calls sender(&endOfStream, nil). If the stream ends before the first usage or completion event, record usage with an empty request id only when there is no completion terminal, otherwise return the incomplete-stream error. Pass the upstream event["id"] into recordResponseUsage and use that id if [DONE] is missing.

🤖 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/response_handler.go` around lines 128 - 137, Update
HandleStreamingResponse to preserve the done state and upstream event["id"]
returned by ParseSSEStream. Pass the event id to recordResponseUsage, falling
back to that id when [DONE] is absent; when the stream ends before usage or
completion, record usage with an empty request id only without a completion
terminal, otherwise return the incomplete-stream error instead of always sending
[DONE].

- Fix content extraction to handle nil content with tool_calls or
  reasoning_content (return empty string pointer instead of nil).
- Add <think> tag parsing for SiliconFlow-style inline thinking.
- Add error event handling in SSE stream parsing.
- Add setSortedToolCallsResult call in HandleStreamingResponse.
- Handle total token fallback when field is missing.

Co-authored-by: jay <<EMAIL>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. ☯️ refactor Pull request that refactor/refine code size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant