Skip to content

refactor: the request body build - #17286

Merged
JinHai-CN merged 4 commits into
infiniflow:mainfrom
Haruko386:major
Jul 23, 2026
Merged

JinHai-CN merged 4 commits into
infiniflow:mainfrom
Haruko386:major

Conversation

@Haruko386

Copy link
Copy Markdown
Member

Summary

As title

@Haruko386
Haruko386 marked this pull request as draft July 23, 2026 07:19
@Haruko386
Haruko386 marked this pull request as ready for review July 23, 2026 07:20
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jul 23, 2026
@Haruko386 Haruko386 added ci Continue Integration and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels Jul 23, 2026
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 90174d9a-e558-417a-a8bf-7a85cb8b5016

📥 Commits

Reviewing files that changed from the base of the PR and between 143c1a1 and bd214db.

📒 Files selected for processing (8)
  • internal/entity/models/astraflow.go
  • internal/entity/models/base_model.go
  • internal/entity/models/gpustack.go
  • internal/entity/models/hunyuan.go
  • internal/entity/models/mistral.go
  • internal/entity/models/novita.go
  • internal/entity/models/tokenhub.go
  • internal/entity/models/tokenpony.go
🚧 Files skipped from review as they are similar to previous changes (8)
  • internal/entity/models/tokenhub.go
  • internal/entity/models/hunyuan.go
  • internal/entity/models/tokenpony.go
  • internal/entity/models/mistral.go
  • internal/entity/models/novita.go
  • internal/entity/models/base_model.go
  • internal/entity/models/gpustack.go
  • internal/entity/models/astraflow.go

📝 Walkthrough

Walkthrough

Chat model integrations now use shared helpers for non-streaming and streaming request payloads. Provider-specific reasoning, thinking, tool, URL, and stream-option handling remains where required, while several legacy request builders and request types are removed.

Changes

Chat request refactor

Layer / File(s) Summary
Shared request-body contract
internal/entity/models/base_model.go
Adds shared construction for model, messages, stream mode, generation settings, tool fields, and stream validation.
Provider chat migration
internal/entity/models/*.go
Updates provider chat and streaming entrypoints to use buildRequestBody while preserving request execution, response parsing, and SSE handling.
Provider-specific request overrides
internal/entity/models/*.go
Retains or centralizes reasoning, thinking, tool, usage, URL, and provider-specific payload adjustments.
Legacy builder replacement
internal/entity/models/*.go
Removes provider-specific payload structs and builders, and introduces direct JSON request construction where required.

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

Possibly related PRs

Poem

I’m a rabbit with payloads tucked neat,
One shared builder makes every call fleet.
Stream flags hop, tools bloom bright,
Thinking fields dance into flight.
Old maps rest beneath the moon.

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (1 warning, 2 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.18% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is related to the change, but it's vague and doesn't clearly say what request-body refactor was made. Use a specific title like 'refactor: centralize chat request body construction'.
Description check ❓ Inconclusive The description only repeats the title and lacks the required summary, purpose, and background context. Add a brief summary of the refactor, why it was needed, and any behavior changes or risks.
✅ Passed checks (2 passed)
Check name Status Explanation
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.

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.

@Haruko386 Haruko386 added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jul 23, 2026
@Haruko386
Haruko386 marked this pull request as draft July 23, 2026 07:21
@Haruko386
Haruko386 marked this pull request as ready for review July 23, 2026 07:21
@Haruko386 Haruko386 removed the ci Continue Integration label Jul 23, 2026
@Haruko386
Haruko386 marked this pull request as draft July 23, 2026 07:21
@Haruko386
Haruko386 marked this pull request as ready for review July 23, 2026 07:21
@Haruko386 Haruko386 added the ci Continue Integration label Jul 23, 2026
@Haruko386
Haruko386 marked this pull request as draft July 23, 2026 07:22
@Haruko386
Haruko386 marked this pull request as ready for review July 23, 2026 07:22

@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: 4

Caution

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

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

112-120: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Missing modelName validation in ChatWithMessages.

Unlike every sibling provider migrated in this same layer (avian, cometapi, n1n, ppio), ChatWithMessages no longer validates that modelName is non-empty before building the request. This was dropped during the request-building rewrite.

🤖 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/futurmix.go` around lines 112 - 120, Add a non-empty
modelName validation to FuturMixModel.ChatWithMessages before request
construction, matching the validation behavior used by the sibling provider
implementations. Return the established validation error for an empty modelName
while preserving the existing APIConfigCheck and messages validation.

180-188: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Validation guards dropped in FuturMix's request-building rewrite. Both ChatWithMessages and ChatStreamlyWithSender lost guards that every sibling provider (avian, cometapi, n1n, ppio, modelscope, xinference) retained after the same buildRequestBody migration.

  • internal/entity/models/futurmix.go#L180-L188: restore the sender == nil, modelName empty, and chatModelConfig.Stream == false guards in ChatStreamlyWithSender before building the request — sender is invoked unconditionally later (sender(nil, &r), sender(&endOfStream, nil)), so a nil sender will panic.
  • internal/entity/models/futurmix.go#L112-L120: restore the modelName non-empty validation in ChatWithMessages before building the request, matching the sibling providers.
🛡️ Proposed fix restoring the dropped guards
 func (f *FuturMixModel) ChatWithMessages(ctx context.Context, modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig, modelUsage *common.ModelUsage) (*ChatResponse, error) {
 	if err := f.baseModel.APIConfigCheck(apiConfig); err != nil {
 		return nil, err
 	}
+
+	if strings.TrimSpace(modelName) == "" {
+		return nil, fmt.Errorf("model name is required")
+	}
 	if len(messages) == 0 {
 		return nil, fmt.Errorf("messages is empty")
 	}
 func (f *FuturMixModel) ChatStreamlyWithSender(ctx context.Context, modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig, modelUsage *common.ModelUsage, sender func(*string, *string) error) error {
 	if err := f.baseModel.APIConfigCheck(apiConfig); err != nil {
 		return err
 	}
+
+	if sender == nil {
+		return fmt.Errorf("sender is required")
+	}
+	if strings.TrimSpace(modelName) == "" {
+		return fmt.Errorf("model name is required")
+	}
 	if len(messages) == 0 {
 		return fmt.Errorf("messages is empty")
 	}
+	if chatModelConfig != nil && chatModelConfig.Stream != nil && !*chatModelConfig.Stream {
+		return fmt.Errorf("stream must be true in ChatStreamlyWithSender")
+	}
🤖 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/futurmix.go` around lines 180 - 188, Restore the
dropped request validations in internal/entity/models/futurmix.go at
ChatStreamlyWithSender (lines 180-188): reject a nil sender, empty modelName,
and chatModelConfig.Stream == false before building the request. Also update
ChatWithMessages (lines 112-120) to reject an empty modelName before request
construction, matching sibling providers.
internal/entity/models/cohere.go (1)

70-89: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Remap Cohere generic-body fields to Cohere v2 payload names.

buildRequestBody writes top_p, stop, tools, and tool_choice before Cohere remapping. Cohere uses p for nucleus sampling and stop_sequences for stop strings, but the request only adds p while leaving top_p and sending stop/tools/tool_choice unchanged. Apply this remapping/removal in both ChatWithMessages and ChatStreamlyWithSender.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/entity/models/cohere.go` around lines 70 - 89, Update
ChatWithMessages and ChatStreamlyWithSender after buildRequestBody to remap
Cohere fields: move top_p to p, rename stop to stop_sequences, and map tools and
tool_choice to their Cohere v2 payload names, removing the generic keys so both
request paths send only the correct fields.
internal/entity/models/openrouter.go (1)

177-184: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

reasoning is overwritten when both Thinking and Effort are set.

Each if assigns a fresh map to reqBody["reasoning"], so when both are non-nil the Effort branch discards the {"enabled": ...} set by the Thinking branch. Merge into a single map instead of two independent assignments.

🔧 Merge reasoning fields
 	if modelConfig != nil {
-		if modelConfig.Thinking != nil {
-			reqBody["reasoning"] = map[string]interface{}{"enabled": *modelConfig.Thinking}
-		}
-		if modelConfig.Effort != nil {
-			reqBody["reasoning"] = map[string]interface{}{"effort": *modelConfig.Effort}
-		}
+		reasoning := map[string]interface{}{}
+		if modelConfig.Thinking != nil {
+			reasoning["enabled"] = *modelConfig.Thinking
+		}
+		if modelConfig.Effort != nil {
+			reasoning["effort"] = *modelConfig.Effort
+		}
+		if len(reasoning) > 0 {
+			reqBody["reasoning"] = reasoning
+		}
 	}
🤖 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/openrouter.go` around lines 177 - 184, Update the
reasoning construction in the model request body so Thinking and Effort fields
are merged into one map when both are non-nil. Initialize or reuse a single
reqBody["reasoning"] map, then assign each applicable field without replacing
previously added values.
internal/entity/models/ollama.go (1)

182-190: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Guard modelConfig before reading Effort / Thinking.

buildRequestBody accepts a nil ChatConfig, but the streaming block dereferences modelConfig.Effort before null checks, so a nil config can panic after request body construction. Wrap this section in if modelConfig != nil { ... }, like the non-streaming path.

🤖 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/ollama.go` around lines 182 - 190, Guard the
Effort/Thinking handling in buildRequestBody with a modelConfig != nil check
before accessing either field. Preserve the existing GPT-OSS effort and boolean
Thinking behavior inside this guard, matching the non-streaming path so nil
ChatConfig values do not panic.
🧹 Nitpick comments (3)
internal/entity/models/astraflow.go (1)

88-89: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove leftover empty if chatModelConfig != nil {} block.

This conditional is now a no-op after the refactor to buildRequestBody.

🧹 Suggested cleanup
 	reqBody := buildRequestBody(chatModelConfig, modelName, messages, false)
 
-	if chatModelConfig != nil {
-	}
-
 	jsonData, err := json.Marshal(reqBody)
As per coding guidelines, "Remove dead tests, commented-out code, stale documentation, and 'move later' notes."
🤖 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/astraflow.go` around lines 88 - 89, Remove the empty
no-op if chatModelConfig != nil conditional from buildRequestBody, leaving the
surrounding request-body construction unchanged.

Source: Coding guidelines

internal/entity/models/huaweicloud.go (1)

190-192: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Make Huawei Cloud tool configuration consistent between streaming and non-streaming requests.

buildRequestBody already sets tools and tool_choice, but both Huawei Cloud paths also call huaweiCloudApplyChatConfig. Remove the redundant calls from both paths, or add the missing stream path call before marshaling if that helper applies Huawei-specific tool semantics.

🤖 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/huaweicloud.go` around lines 190 - 192, Make tool
configuration consistent in both Huawei Cloud streaming and non-streaming
request paths: inspect huaweiCloudApplyChatConfig and buildRequestBody, then
either remove the redundant helper calls from both paths or invoke the helper in
the streaming path before marshaling if it applies required Huawei-specific tool
semantics. Preserve a single consistent source of tool and tool_choice
configuration.
internal/entity/models/openrouter.go (1)

72-78: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Nit: pass the dereferenced value for consistency. The non-stream path stores chatModelConfig.Effort (a *string) while the stream path stores *modelConfig.Effort. JSON marshaling dereferences the pointer so output is equivalent, but aligning the two avoids confusion.

🤖 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/openrouter.go` around lines 72 - 78, Update the
non-stream reasoning payload in the chatModelConfig handling to store the
dereferenced Effort value rather than the pointer, matching the stream path’s
use of *modelConfig.Effort while preserving the existing reasoning structure.
🤖 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 253-260: Converge HuaweiCloud tool configuration to a single
application point: update HuaweiCloudModel.ChatWithMessages and the
buildRequestBody/applyChatToolConfig flow so tool settings are not applied
twice. Preserve explicit and default "auto" ToolChoice values and the configured
tools, using one helper as the sole source of request-body tool configuration.
- Around line 225-239: Remove the hardcoded temperature: 1 entry from the shared
request body built by buildRequestBody, allowing cfg.Temperature to be included
only when explicitly configured. Preserve provider-specific defaults by applying
any required fallback in the relevant provider path rather than the generic
payload.

In `@internal/entity/models/deepseek.go`:
- Around line 78-108: Add a default branch to the non-stream effort switch that
returns the same unknown-effort error as the streaming path, preventing an empty
thinking.type from being sent. Remove the redundant break statements from the
switch cases while preserving the existing mappings for recognized efforts.

In `@internal/entity/models/siliconflow.go`:
- Around line 188-194: Update ChatStreamlyWithSender to forward an explicitly
configured chatModelConfig.Thinking value into reqBody["enable_thinking"],
matching ChatWithMessages and the corresponding provider implementations.
Preserve the existing qwen3 fallback that sets enable_thinking to false only
when Thinking is nil.

---

Outside diff comments:
In `@internal/entity/models/cohere.go`:
- Around line 70-89: Update ChatWithMessages and ChatStreamlyWithSender after
buildRequestBody to remap Cohere fields: move top_p to p, rename stop to
stop_sequences, and map tools and tool_choice to their Cohere v2 payload names,
removing the generic keys so both request paths send only the correct fields.

In `@internal/entity/models/futurmix.go`:
- Around line 112-120: Add a non-empty modelName validation to
FuturMixModel.ChatWithMessages before request construction, matching the
validation behavior used by the sibling provider implementations. Return the
established validation error for an empty modelName while preserving the
existing APIConfigCheck and messages validation.
- Around line 180-188: Restore the dropped request validations in
internal/entity/models/futurmix.go at ChatStreamlyWithSender (lines 180-188):
reject a nil sender, empty modelName, and chatModelConfig.Stream == false before
building the request. Also update ChatWithMessages (lines 112-120) to reject an
empty modelName before request construction, matching sibling providers.

In `@internal/entity/models/ollama.go`:
- Around line 182-190: Guard the Effort/Thinking handling in buildRequestBody
with a modelConfig != nil check before accessing either field. Preserve the
existing GPT-OSS effort and boolean Thinking behavior inside this guard,
matching the non-streaming path so nil ChatConfig values do not panic.

In `@internal/entity/models/openrouter.go`:
- Around line 177-184: Update the reasoning construction in the model request
body so Thinking and Effort fields are merged into one map when both are
non-nil. Initialize or reuse a single reqBody["reasoning"] map, then assign each
applicable field without replacing previously added values.

---

Nitpick comments:
In `@internal/entity/models/astraflow.go`:
- Around line 88-89: Remove the empty no-op if chatModelConfig != nil
conditional from buildRequestBody, leaving the surrounding request-body
construction unchanged.

In `@internal/entity/models/huaweicloud.go`:
- Around line 190-192: Make tool configuration consistent in both Huawei Cloud
streaming and non-streaming request paths: inspect huaweiCloudApplyChatConfig
and buildRequestBody, then either remove the redundant helper calls from both
paths or invoke the helper in the streaming path before marshaling if it applies
required Huawei-specific tool semantics. Preserve a single consistent source of
tool and tool_choice configuration.

In `@internal/entity/models/openrouter.go`:
- Around line 72-78: Update the non-stream reasoning payload in the
chatModelConfig handling to store the dereferenced Effort value rather than the
pointer, matching the stream path’s use of *modelConfig.Effort while preserving
the existing reasoning structure.
🪄 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: e76e504c-f623-4945-a6e2-28613e0a1a04

📥 Commits

Reviewing files that changed from the base of the PR and between e3e2d0a and 143c1a1.

📒 Files selected for processing (51)
  • internal/entity/models/302ai.go
  • internal/entity/models/aliyun.go
  • internal/entity/models/astraflow.go
  • internal/entity/models/avian.go
  • internal/entity/models/baichuan.go
  • internal/entity/models/baidu.go
  • internal/entity/models/base_model.go
  • internal/entity/models/cohere.go
  • internal/entity/models/cometapi.go
  • internal/entity/models/deepinfra.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/futurmix.go
  • internal/entity/models/gitee.go
  • internal/entity/models/gpustack.go
  • internal/entity/models/groq.go
  • internal/entity/models/huaweicloud.go
  • internal/entity/models/huggingface.go
  • internal/entity/models/hunyuan.go
  • internal/entity/models/jiekouai.go
  • internal/entity/models/jina.go
  • internal/entity/models/lmstudio.go
  • internal/entity/models/localai.go
  • internal/entity/models/longcat.go
  • internal/entity/models/minimax.go
  • internal/entity/models/mistral.go
  • internal/entity/models/modelscope.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/n1n.go
  • internal/entity/models/novita.go
  • internal/entity/models/nvidia.go
  • internal/entity/models/ollama.go
  • internal/entity/models/openai.go
  • internal/entity/models/openrouter.go
  • internal/entity/models/orcarouter.go
  • internal/entity/models/perplexity.go
  • internal/entity/models/ppio.go
  • internal/entity/models/qiniu.go
  • internal/entity/models/ragcon.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/stepfun.go
  • internal/entity/models/togetherai.go
  • internal/entity/models/tokenhub.go
  • internal/entity/models/tokenpony.go
  • internal/entity/models/upstage.go
  • internal/entity/models/vllm.go
  • internal/entity/models/volcengine.go
  • internal/entity/models/xai.go
  • internal/entity/models/xiaomi.go
  • internal/entity/models/xinference.go
  • internal/entity/models/xunfei.go
  • internal/entity/models/zhipu-ai.go

Comment thread internal/entity/models/base_model.go Resolved
Comment thread internal/entity/models/base_model.go Resolved
Comment thread internal/entity/models/deepseek.go Resolved
Comment thread internal/entity/models/siliconflow.go Resolved
@Haruko386 Haruko386 added ci Continue Integration ☯️ refactor Pull request that refactor/refine code size:XXL This PR changes 1000+ lines, ignoring generated files. labels Jul 23, 2026
@Haruko386
Haruko386 marked this pull request as draft July 23, 2026 07:44
@Haruko386
Haruko386 marked this pull request as ready for review July 23, 2026 07:44
@JinHai-CN
JinHai-CN merged commit efe6bca into infiniflow:main Jul 23, 2026
9 of 12 checks passed
@Haruko386
Haruko386 deleted the major branch July 24, 2026 01:50
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:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants