Skip to content

feat(go-models): migrate nvidia/siliconflow/groq/longcat to unified h… - #17643

Merged
JinHai-CN merged 5 commits into
infiniflow:mainfrom
jay77721:feat/migrate-openai-drivers
Aug 3, 2026
Merged

JinHai-CN merged 5 commits into
infiniflow:mainfrom
jay77721:feat/migrate-openai-drivers

Conversation

@jay77721

Copy link
Copy Markdown
Member

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 by deepseek in #17634.

  • Cut ~100 lines per driver (541 lines removed, 19 added across 4 files).
  • nvidia now extracts token usage (previously had none).
  • All four drivers produce the unified StreamUsage log.

Changes

File Before After Notes
nvidia.go ~170 lines ~30 lines +usage extraction
siliconflow.go ~170 lines ~30 lines simplified
groq.go ~150 lines ~30 lines simplified
longcat.go ~190 lines ~30 lines simplified

Testing

  • bash build.sh --test ./internal/entity/models/... passes.
  • Each driver's existing test suite continues to pass.

…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>>
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 31, 2026
@jay77721 jay77721 added ci Continue Integration and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 31, 2026
@dosubot dosubot Bot added the ☯️ refactor Pull request that refactor/refine code label Jul 31, 2026
@jay77721
jay77721 marked this pull request as draft July 31, 2026 11:04
@jay77721
jay77721 marked this pull request as ready for review July 31, 2026 11:04
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 31, 2026
@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Groq, LongCat, NVIDIA, and SiliconFlow now use shared BaseModel and OpenAI-compatible handlers for non-streaming and streaming chat responses. Provider-specific HTTP, SSE, usage, reasoning, and tool-call processing was removed.

Changes

Provider handler migration

Layer / File(s) Summary
Non-streaming handler migration
internal/entity/models/groq.go, internal/entity/models/longcat.go, internal/entity/models/nvidia.go, internal/entity/models/siliconflow.go
Non-streaming chat methods now use BaseModel.doRequest and HandleNonStreamingResponse.
Streaming handler migration
internal/entity/models/groq.go, internal/entity/models/longcat.go, internal/entity/models/nvidia.go, internal/entity/models/siliconflow.go
Streaming chat methods now use HandleStreamingResponse. Groq and NVIDIA request usage data explicitly. LongCat retains an explicit timeout context.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested reviewers: jinhai-cn, haruko386, dexterity104

Poem

A rabbit checks the streaming flow,
Shared handlers parse what providers show.
Groq and LongCat send requests bright,
NVIDIA and SiliconFlow follow right.
Less custom parsing fills the burrow tonight.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the four drivers migrated to unified handlers.
Description check ✅ Passed The description includes the required Summary section, purpose, implementation details, and testing results.

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 added ci Continue Integration and removed ci Continue Integration labels Jul 31, 2026
@jay77721
jay77721 marked this pull request as draft July 31, 2026 11:08
@jay77721
jay77721 marked this pull request as ready for review July 31, 2026 11:08

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

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

101-106: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Delete the unused LongCatChatResponse schema.

LongCatChatResponse is only declared and does not appear in any Go code path. The non-streaming response now goes through HandleNonStreamingResponse(... OpenAIParserConfig), so remove LongCatChatResponse and 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

📥 Commits

Reviewing files that changed from the base of the PR and between e1f724b and fd4bdab.

📒 Files selected for processing (4)
  • internal/entity/models/groq.go
  • internal/entity/models/longcat.go
  • internal/entity/models/nvidia.go
  • internal/entity/models/siliconflow.go

Comment on lines +126 to +131
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)

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

🧩 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:


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.

Comment thread internal/entity/models/groq.go Resolved
jay77721 and others added 3 commits July 31, 2026 19:21
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>>
@jay77721
jay77721 marked this pull request as draft July 31, 2026 11:21
@jay77721
jay77721 marked this pull request as ready for review July 31, 2026 11:22
@jay77721 jay77721 added ci Continue Integration and removed ci Continue Integration labels 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.

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 win

Keep StreamUsage logging independent of nullable ChatConfig.

Both shared handlers record usage but emit the unified log only inside the chatConfig != nil guard. 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 when chatModelConfig is nil.
  • internal/entity/models/nvidia.go#L164-L164: keep streaming usage logging active when modelConfig is 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

📥 Commits

Reviewing files that changed from the base of the PR and between fd4bdab and 6c9371b.

📒 Files selected for processing (4)
  • internal/entity/models/groq.go
  • internal/entity/models/longcat.go
  • internal/entity/models/nvidia.go
  • internal/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

JinHai-CN pushed a commit that referenced this pull request Aug 4, 2026
…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]>
@jay77721
jay77721 deleted the feat/migrate-openai-drivers branch August 5, 2026 07:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration ☯️ refactor Pull request that refactor/refine code size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants