Repository navigation
feat(go-models): migrate nvidia/siliconflow/groq/longcat to unified h… - #17643
Conversation
…andlers Migrate four OpenAI-compatible drivers to use HandleNonStreamingResponse / HandleStreamingResponse, cutting ~100 lines per driver. - nvidia.go: 170 → 30 lines, now extracts usage (previously none) - siliconflow.go: 170 → 30 lines - groq.go: 150 → 30 lines - longcat.go: 190 → 30 lines Co-authored-by: jay <<EMAIL>>
📝 WalkthroughWalkthroughGroq, LongCat, NVIDIA, and SiliconFlow now use shared ChangesProvider handler migration
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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: 2
🧹 Nitpick comments (1)
internal/entity/models/longcat.go (1)
101-106: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDelete the unused
LongCatChatResponseschema.
LongCatChatResponseis only declared and does not appear in any Go code path. The non-streaming response now goes throughHandleNonStreamingResponse(... OpenAIParserConfig), so removeLongCatChatResponseand its unused doc comment.🤖 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 101 - 106, Remove the unused LongCatChatResponse type declaration and its associated documentation comment from the LongCat model definitions, leaving the HandleNonStreamingResponse path unchanged.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/groq.go`:
- Line 186: The Groq and NVIDIA streaming request builders do not enable
upstream usage payloads. In internal/entity/models/groq.go:158-186, update the
request body after applyGroqReasoningRequestParams; in
internal/entity/models/nvidia.go:124-163, update it after buildRequestBody; both
sites must set stream_options with include_usage enabled so
HandleStreamingResponse receives usage data.
- Around line 126-131: Update the Groq response parsing used by the
non-streaming path around HandleNonStreamingResponse, and the corresponding
streaming parser, so gpt-oss maps Groq’s reasoning field to the parser’s
reasoning output. Ensure the configuration supports include_reasoning and reads
reasoning rather than only reasoning_content for gpt-oss, while preserving
existing OpenAI behavior for other models.
---
Nitpick comments:
In `@internal/entity/models/longcat.go`:
- Around line 101-106: Remove the unused LongCatChatResponse type declaration
and its associated documentation comment from the LongCat model definitions,
leaving the HandleNonStreamingResponse path unchanged.
🪄 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: 3b4663e8-9703-410e-9e42-45f8ab0f17fb
📒 Files selected for processing (4)
internal/entity/models/groq.gointernal/entity/models/longcat.gointernal/entity/models/nvidia.gointernal/entity/models/siliconflow.go
| body, err := g.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, http.MethodPost, 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 := g.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) (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) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Inspect the shared parser config and the reasoning fields the old Groq code read.
fd -t f 'response_handler.go' -x rg -n -C4 'OpenAIParserConfig|reasoning' {}
git log -p -1 --unified=3 -- internal/entity/models/groq.go | rg -n 'reasoning'Repository: infiniflow/ragflow
Length of output: 2144
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== candidate response handler files =="
fd -t f 'response_handler.go'
echo
echo "== groq.go around reasoning params and return statement =="
sed -n '1,170p' internal/entity/models/groq.go
echo
echo "== streaming and non-streaming extract logic =="
sed -n '100,230p' internal/entity/models/response_handler.go
echo
echo "== all OpenAIParserConfig usages =="
rg -n 'OpenAIParserConfig|HandleNonStreamingResponse|HandleStreamingResponse' .Repository: infiniflow/ragflow
Length of output: 11200
🌐 Web query:
Groq gpt-oss include_reasoning reasoning_format parsed response reasoning reasoning_content
💡 Result:
In the Groq API, include_reasoning and reasoning_format are parameters used to control the output of model reasoning, and they are mutually exclusive [1][2]. 1. include_reasoning: This boolean parameter determines whether reasoning is included in the response [1][2]. When set to true (the default behavior), the response includes a dedicated reasoning field [2]. When set to false, reasoning is excluded from the response [1][2]. 2. reasoning_format: This parameter provides fine-grained control over how reasoning tokens are output [1][2]. It supports three values [2]: - parsed: Separates the model's reasoning into a dedicated field (often accessed as reasoning_content in SDKs like LangChain) while keeping the main response concise [2][3]. - raw: Includes the reasoning content directly within the main text content, typically enclosed in specific tags (e.g., tags) [2][3]. - hidden: Returns only the final answer, suppressing the reasoning content in the response [2][3]. Note that for specific models, such as openai/gpt-oss-20b and openai/gpt-oss-120b, the reasoning_format parameter is not supported [2]. These models include reasoning in the reasoning field by default, and you can control its visibility using include_reasoning [2]. Additionally, when using JSON mode or tool calling, the reasoning_format must be set to either parsed or hidden, as raw is not supported in those modes [2]. If you use libraries like LangChain, the parsed reasoning is commonly mapped to additional_kwargs.reasoning_content [3][4][5].
Citations:
- 1: https://console.groq.com/docs/api-reference
- 2: https://console.groq.com/docs/reasoning
- 3: https://reference.langchain.com/python/langchain-groq/chat_models/ChatGroq/reasoning_format
- 4: groq: add support for accessing reasoning output from Groq models langchain-ai/langchain#31662
- 5: https://github.com/langchain-ai/langchain/blob/master/libs/partners/groq/langchain_groq/chat_models.py
Use Groq’s reasoning output for gpt-oss.
gpt-oss supports only include_reasoning, and Groq returns that reasoning in reasoning; OpenAIParserConfig only reads reasoning_content. This drops gpt-oss reasoning in both streaming and non-streaming paths.
🤖 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 126 - 131, Update the Groq
response parsing used by the non-streaming path around
HandleNonStreamingResponse, and the corresponding streaming parser, so gpt-oss
maps Groq’s reasoning field to the parser’s reasoning output. Ensure the
configuration supports include_reasoning and reads reasoning rather than only
reasoning_content for gpt-oss, while preserving existing OpenAI behavior for
other models.
Groq and NVIDIA streaming request builders did not enable upstream usage payloads. Add stream_options.include_usage=true so HandleStreamingResponse receives usage data and can populate UsageResult + emit StreamUsage log. Co-authored-by: jay <<EMAIL>>
There was a problem hiding this comment.
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/nvidia.go (1)
97-101: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winKeep
StreamUsagelogging independent of nullableChatConfig.Both shared handlers record usage but emit the unified log only inside the
chatConfig != nilguard. The migrated methods accept nil configs, so valid requests can omit the log.
internal/entity/models/nvidia.go#L97-L101: keep non-streaming usage logging active whenchatModelConfigis nil.internal/entity/models/nvidia.go#L164-L164: keep streaming usage logging active whenmodelConfigis nil.internal/entity/models/siliconflow.go#L86-L90: apply the same non-streaming behavior.internal/entity/models/siliconflow.go#L149-L149: apply the same streaming behavior.Move
common.Info("StreamUsage", ...)outside the nullable-config guard in both shared handlers.Based on the shared handler contract and the PR objective, usage logging is part of this migration contract.
🤖 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` around lines 97 - 101, Update the shared non-streaming and streaming response handlers used by all four listed call sites so common.Info("StreamUsage", ...) executes independently of nullable ChatConfig/modelConfig guards. Ensure usage logging remains active when the config is nil; apply the root fix in the shared handlers, with no direct changes required at the four call sites: internal/entity/models/nvidia.go lines 97-101 and 164, and internal/entity/models/siliconflow.go lines 86-90 and 149.
🤖 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.
Outside diff comments:
In `@internal/entity/models/nvidia.go`:
- Around line 97-101: Update the shared non-streaming and streaming response
handlers used by all four listed call sites so common.Info("StreamUsage", ...)
executes independently of nullable ChatConfig/modelConfig guards. Ensure usage
logging remains active when the config is nil; apply the root fix in the shared
handlers, with no direct changes required at the four call sites:
internal/entity/models/nvidia.go lines 97-101 and 164, and
internal/entity/models/siliconflow.go lines 86-90 and 149.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ca8fa14a-b3f0-4f71-abd6-bc119593a950
📒 Files selected for processing (4)
internal/entity/models/groq.gointernal/entity/models/longcat.gointernal/entity/models/nvidia.gointernal/entity/models/siliconflow.go
🚧 Files skipped from review as they are similar to previous changes (2)
- internal/entity/models/longcat.go
- internal/entity/models/groq.go
…ding (#17775) ## Summary Relate to #17284. Completes the migration of the four non-OpenAI-compatible model drivers (`anthropic`, `cohere`, `google`, `bedrock`) onto the shared usage-recording path. Earlier batches (#17634, #17643, #17696–#17700) covered only the OpenAI-compatible cluster; these four providers ship wire formats that do not fit the OpenAI `choices[0].delta` / `usage` block template and so were left for a separate pass. Per the maintainer's guidance for this batch, each driver is migrated on its own terms rather than forced through a single template. The shared machinery used is intentionally small: `recordResponseUsage`, `parseChatCompletionResponse`, `BaseModel.newJSONPostRequest`, and the existing `authHeader` hook for non-Bearer auth. Co-authored-by: Haruko386 <[email protected]> Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Summary
Relate to #17284
Migrate four OpenAI-compatible drivers (
nvidia,siliconflow,groq,longcat) to use the unified response handlers (HandleNonStreamingResponse/HandleStreamingResponse), following the same pattern established bydeepseekin #17634.nvidianow extracts token usage (previously had none).StreamUsagelog.Changes
nvidia.gosiliconflow.gogroq.golongcat.goTesting
bash build.sh --test ./internal/entity/models/...passes.