Repository navigation
feat(go-models): migrate batch 3 model drivers to unified handlers - #17698
Conversation
Migrate 10 model drivers (and add shared Chat methods to OpenAIAPICompatible): - minimax (MiniMaxModel) - mistral (MistralModel) - modelscope (ModelScopeModel) - moonshot (MoonshotModel) - n1n (N1nModel) - novita (NovitaModel) - ollama (OllamaModel) - openai (OpenAIModel) - openai_api_compatible (OpenAIAPICompatibleModel) - also adds new ChatWithMessages + ChatStreamlyWithSender - openrouter (OpenRouterModel) OpenAIAPICompatible's new shared methods are included here as they are used by the unified handler infrastructure.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughProvider models now use shared request, non-streaming, and streaming handlers. MiniMax and Novita retain provider-specific stream processing. Mistral normalizes structured content. OpenAI-compatible models gain chat methods. Obsolete response types and tests are removed. ChangesChat handler migration
Estimated code review effort: 4 (Complex) | ~60 minutes Possibly related PRs
Suggested labels: 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: 3
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/moonshot.go (1)
148-162: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winAdd
stream_options.include_usageto the Moonshot streaming request.Every other migrated driver sets
reqBody["stream_options"] = map[string]interface{}{"include_usage": true}before the stream call.HandleStreamingResponserecords usage only when the stream carries a usage chunk. Without this option,modelUsageandchatModelConfig.UsageResultstay empty for Moonshot streams.🐛 Proposed fix
reqBody := buildRequestBody(chatModelConfig, modelName, messages, true) + reqBody["stream_options"] = map[string]interface{}{"include_usage": true}🤖 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/moonshot.go` around lines 148 - 162, Add reqBody["stream_options"] with include_usage enabled in the Moonshot streaming request construction near buildRequestBody, before the stream call, so HandleStreamingResponse receives usage chunks and populates modelUsage and chatModelConfig.UsageResult.internal/entity/models/openai.go (1)
134-158: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winUse
doStreamRequestfor OpenAI streaming.
OpenAIModelcreateshttpClientwithNewDriverHTTPClient(false)and this path uses the callerctx. SinceNewDriverHTTPClient(false)leavesClient.Timeoutunset, a stalled stream can stay open while the caller context has no deadline. Useo.baseModel.doStreamRequest(ctx, url, apiConfig, reqBody, streamCallTimeout, ...)and keep the per-provider handling in the callback.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/openai.go` around lines 134 - 158, Replace the manual streaming HTTP request flow in OpenAIModel with o.baseModel.doStreamRequest, passing ctx, url, apiConfig, reqBody, streamCallTimeout, and a callback that preserves the existing OpenAI response handling via HandleStreamingResponse and its provider-specific configuration. Remove the duplicated request construction, status handling, and direct response-body management.
🧹 Nitpick comments (4)
internal/entity/models/openai.go (2)
118-123: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReplace the inline stream check with
validateStreamConfig.
validateStreamConfig(base_model.go:490-495) returns the same error text. ModelScope and Novita already call it. Move the check above the request body construction to keep the validation order consistent with the other drivers.♻️ Proposed refactor
+ if err := validateStreamConfig(chatModelConfig); err != nil { + return err + } + reqBody := buildRequestBody(chatModelConfig, modelName, messages, true) reqBody["stream_options"] = map[string]interface{}{ "include_usage": true, } - if chatModelConfig != nil { - if 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/openai.go` around lines 118 - 123, Replace the inline Stream check in ChatStreamlyWithSender with a call to validateStreamConfig, placing it before request body construction. Preserve the existing validation behavior and error text, while retaining the surrounding chatModelConfig handling as needed.
97-104: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAdd a
sendernil check.
HandleStreamingResponsereturnssender is requiredwhensenderis nil, but only after the HTTP request completes. Mistral, ModelScope, Novita, and N1n reject a nilsenderbefore the call. Add the same guard to fail fast and to avoid a wasted upstream request.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/openai.go` around lines 97 - 104, Update OpenAIModel.ChatStreamlyWithSender to validate sender before initiating any upstream request, returning the established “sender is required” error when it is nil. Place this guard alongside the existing API configuration and empty-messages validation, preserving the current behavior for valid senders.internal/entity/models/moonshot.go (1)
164-192: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
doStreamRequestfor the Moonshot streaming transport.Mistral, ModelScope, Novita, Ollama, OpenRouter, and N1n now call
doStreamRequest. This method still marshals the body, sets the timeout, sets headers, and checks the status inline. The duplicate transport code diverges over time.♻️ Proposed refactor
- jsonData, err := json.Marshal(reqBody) - if err != nil { - return fmt.Errorf("failed to marshal request: %w", err) - } - - ctx, cancel := context.WithTimeout(ctx, streamCallTimeout) - defer cancel() - - req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData)) - if err != nil { - return fmt.Errorf("failed to create request: %w", err) - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey)) - req.Header.Set("Accept", "text/event-stream") - - resp, err := m.baseModel.httpClient.Do(req) - if err != nil { - return fmt.Errorf("failed to send request: %w", err) - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - body, _ := io.ReadAll(resp.Body) - return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body)) - } - - return HandleStreamingResponse(resp.Body, modelUsage, chatModelConfig, OpenAIParserConfig, sender) + return m.baseModel.doStreamRequest(ctx, url, apiConfig, reqBody, streamCallTimeout, func(body io.ReadCloser) error { + return HandleStreamingResponse(body, modelUsage, chatModelConfig, OpenAIParserConfig, sender) + })The local
apiKeyvariable at line 131 then becomes unused and must also be removed.🤖 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/moonshot.go` around lines 164 - 192, Replace the inline Moonshot streaming HTTP transport with the shared doStreamRequest helper, passing the request body, URL, context, and required authentication/configuration so it retains the current streaming behavior. Remove the now-unused local apiKey variable and preserve HandleStreamingResponse for processing the returned response body.internal/entity/models/minimax.go (1)
213-234: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoffConsider routing the MiniMax stream through
doStreamRequest.The other migrated drivers call
m.baseModel.doStreamRequest(...)and receive the body asio.ReadCloser. This path still builds the request, sets headers, and checks the status inline. The MiniMax-specificbase_respscanning can run inside thedoStreamRequesthandler callback, which keeps one transport path across drivers.One behavior difference to preserve: the inline path reports errors through
extractMinimaxErrorBody, whiledoStreamRequestreturns the raw body.🤖 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/minimax.go` around lines 213 - 234, Refactor the MiniMax streaming request in the surrounding method to use m.baseModel.doStreamRequest instead of constructing the request, setting headers, and checking the response inline. Configure the request with the existing POST URL, JSON payload, and required headers, and perform MiniMax-specific base_resp scanning in the handler callback. Preserve the current error behavior by applying extractMinimaxErrorBody to the raw response body returned on non-success status.
🤖 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/minimax.go`:
- Around line 236-272: Update the streaming response flow around
HandleStreamingResponse to defer pr.Close() immediately after creating the pipe,
ensuring early handler returns unblock the producer and release resp.Body. Also
revise the goroutine to send a result to streamErr on every exit path, including
pw.Write failures, so the final streamErr receive cannot block.
In `@internal/entity/models/openai_api_compatible.go`:
- Around line 82-158: Restore the internal/entity/models test build by updating
tests that reference splitNovitaThink, novitaThinkExtractor,
extractMistralContent, or modelscopeStreamIdleTimeout. Replace retained behavior
coverage with tests for the shared streaming/non-streaming handlers used by
ChatWithMessages and ChatStreamlyWithSender, and remove tests covering only the
deleted compatibility helpers. Run the package-scoped build.sh check to verify
the package passes.
- Line 122: Validate that sender is non-nil at the start of
OpenAIAPICompatibleModel.ChatStreamlyWithSender, returning the existing "sender
is required" error before invoking doStreamRequest or opening the upstream
stream.
---
Outside diff comments:
In `@internal/entity/models/moonshot.go`:
- Around line 148-162: Add reqBody["stream_options"] with include_usage enabled
in the Moonshot streaming request construction near buildRequestBody, before the
stream call, so HandleStreamingResponse receives usage chunks and populates
modelUsage and chatModelConfig.UsageResult.
In `@internal/entity/models/openai.go`:
- Around line 134-158: Replace the manual streaming HTTP request flow in
OpenAIModel with o.baseModel.doStreamRequest, passing ctx, url, apiConfig,
reqBody, streamCallTimeout, and a callback that preserves the existing OpenAI
response handling via HandleStreamingResponse and its provider-specific
configuration. Remove the duplicated request construction, status handling, and
direct response-body management.
---
Nitpick comments:
In `@internal/entity/models/minimax.go`:
- Around line 213-234: Refactor the MiniMax streaming request in the surrounding
method to use m.baseModel.doStreamRequest instead of constructing the request,
setting headers, and checking the response inline. Configure the request with
the existing POST URL, JSON payload, and required headers, and perform
MiniMax-specific base_resp scanning in the handler callback. Preserve the
current error behavior by applying extractMinimaxErrorBody to the raw response
body returned on non-success status.
In `@internal/entity/models/moonshot.go`:
- Around line 164-192: Replace the inline Moonshot streaming HTTP transport with
the shared doStreamRequest helper, passing the request body, URL, context, and
required authentication/configuration so it retains the current streaming
behavior. Remove the now-unused local apiKey variable and preserve
HandleStreamingResponse for processing the returned response body.
In `@internal/entity/models/openai.go`:
- Around line 118-123: Replace the inline Stream check in ChatStreamlyWithSender
with a call to validateStreamConfig, placing it before request body
construction. Preserve the existing validation behavior and error text, while
retaining the surrounding chatModelConfig handling as needed.
- Around line 97-104: Update OpenAIModel.ChatStreamlyWithSender to validate
sender before initiating any upstream request, returning the established “sender
is required” error when it is nil. Place this guard alongside the existing API
configuration and empty-messages validation, preserving the current behavior for
valid senders.
🪄 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: 1d136841-9f3b-447e-b7eb-86b37bcd69d9
📒 Files selected for processing (10)
internal/entity/models/minimax.gointernal/entity/models/mistral.gointernal/entity/models/modelscope.gointernal/entity/models/moonshot.gointernal/entity/models/n1n.gointernal/entity/models/novita.gointernal/entity/models/ollama.gointernal/entity/models/openai.gointernal/entity/models/openai_api_compatible.gointernal/entity/models/openrouter.go
…st build minimax.go: close pr immediately after creating the pipe so an early return from HandleStreamingResponse unblocks the producer goroutine (pw.Write fails) and releases resp.Body. Ensure the goroutine sends a result to streamErr on every exit path, including pw.Write failures and CloseWithError returns, so the final streamErr receive cannot block. tests: batch 3 migration removed the splitNovitaThink/novitaThinkExtractor, extractMistralContent and modelscopeStreamIdleTimeout helpers, leaving the internal/entity/models test build broken. Remove the unit tests that covered only those deleted helpers. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
@coderabbitai review |
✅ Action performedReview finished.
|
…atch-3 migration
The batch-3 migration routed Mistral, Novita and OpenRouter through the
shared HandleStreamingResponse, which dropped three provider-specific
behaviors their tests rely on:
- Mistral magistral returns content as a structured array
([{type:text}, {type:thinking, thinking:[{type:text}]}]). Teach
extractContentAndChoices to concatenate text parts into Answer and
thinking parts into ReasonContent.
- Novita qwen3 embeds <think>...</think> inline in delta.content. Add a
streaming think-tag splitter (streamThinkSplitter) to the shared
handler so those blocks route to the sender's reasoning arg.
- OpenRouter emits reasoning under delta.reasoning (not
delta.reasoning_content). Give OpenRouter its own event loop
(openRouterHandleStream) that forwards delta.reasoning, since the
shared handler cannot (Groq uses delta.reasoning for something else).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
internal/entity/models/response_handler.go (1)
202-208: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRename
novitaThinkSegmentto a provider-neutral name.The type lives in the shared handler and is used by every driver that calls
HandleStreamingResponse, and also byopenRouterHandleStreamininternal/entity/models/openrouter.go. Thenovitaprefix names one provider and no longer matches the owning abstraction. Rename it tothinkSegment.♻️ Proposed rename
-// novitaThinkSegment is one routing decision: emit `content` via the +// thinkSegment is one routing decision: emit `content` via the // sender's first arg, or emit `reasoning` via the second. Exactly one of // the two fields is non-empty. -type novitaThinkSegment struct { +type thinkSegment struct { content string reasoning string }Update the three uses in
feedand the two inflush, plus the loop inopenRouterHandleStream.🤖 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 202 - 208, Rename the shared type novitaThinkSegment to thinkSegment, and update all references in feed, flush, and the openRouterHandleStream loop to use the provider-neutral name.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/openrouter.go`:
- Around line 134-258: Consolidate OpenRouter streaming onto the shared
HandleStreamingResponse path: add handling for delta["reasoning"] before the
existing reasoning_content handling, remove openRouterHandleStream, and update
ChatStreamlyWithSender to call the shared handler. Preserve the existing
streaming behavior and remove the now-unused zap import from openrouter.go.
In `@internal/entity/models/response_handler.go`:
- Around line 320-346: Update the structured-content handling around answer and
reasoning extraction so structuredReason is assigned only when reasoning.Len() >
0, rather than whenever either answer or reasoning has content. Preserve content
assignment when answer text exists, and allow top-level reasoning_content or
reasoning to remain the fallback when no thinking part produced text.
---
Nitpick comments:
In `@internal/entity/models/response_handler.go`:
- Around line 202-208: Rename the shared type novitaThinkSegment to
thinkSegment, and update all references in feed, flush, and the
openRouterHandleStream loop to use the provider-neutral name.
🪄 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: 8e0acad7-d9c2-4663-8593-a9447a0825ea
📒 Files selected for processing (2)
internal/entity/models/openrouter.gointernal/entity/models/response_handler.go
…d handler The previous fix put Mistral structured-content parsing and Novita inline <think>-tag splitting into the shared HandleStreamingResponse, which defeats the purpose of a generic handler. Move each provider's special handling back into its own file: - mistral.go: normalizeMistralStructuredContent rewrites the magistral content array into flat string content + top-level reasoning_content before the shared handler runs. - novita.go: novitaHandleStream splits inline <think>...</think> in delta.content across SSE deltas, routing reasoning to the sender's second arg. - openrouter.go: keep the existing openRouterHandleStream for delta.reasoning (moved here from the shared handler, which cannot forward it without breaking Groq). The shared response_handler.go is now generic again. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Return "sender is required" at the start of ChatStreamlyWithSender before doStreamRequest opens the upstream stream, so a nil sender fails fast instead of after the HTTP request. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add delta["reasoning"] fallback to the shared HandleStreamingResponse (only when delta.reasoning_content is absent), so OpenRouter no longer needs its own event loop. Remove openRouterHandleStream and the now unused zap import from openrouter.go. The fallback is gated on reasoning_content being empty so providers that carry both fields with different meanings (e.g. Groq) are unaffected. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/entity/models/response_handler.go`:
- Around line 122-130: Update the reasoning fallback in the response handling
logic so delta["reasoning"] is considered only when the reasoning_content key is
entirely absent, not when it is empty, null, or non-string; check key presence
separately before evaluating the fallback. Add a regression test covering a
present-empty reasoning_content value and verify that provider reasoning is not
emitted.
🪄 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: f18c5222-0dad-4b5f-bd00-2433021d2093
📒 Files selected for processing (3)
internal/entity/models/openai_api_compatible.gointernal/entity/models/openrouter.gointernal/entity/models/response_handler.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/entity/models/openai_api_compatible.go
Replace the hardcoded delta.reasoning_content read in the shared HandleStreamingResponse with a provider-configurable hook so each provider can name its reasoning field differently (reasoning_content, reasoning, ...) without the shared handler knowing which. - ParserConfig gains ExtractStreamReasoning func(delta) string - extractDefaultStreamReasoning reads delta.reasoning_content - OpenAIParserConfig wires the default - OpenRouterParserConfig reads delta.reasoning (OpenRouter's field) - openrouter.go switches to OpenRouterParserConfig Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
@coderabbitai review |
✅ Action performedReview finished.
|
Summary
Relate to #17284
Migrate 10 OpenAI-compatible drivers (
minimax,mistral,modelscope,moonshot,n1n,novita,ollama,openai,openai_api_compatible,openrouter) to use the unified response handlers (HandleNonStreamingResponse/HandleStreamingResponse), following the same pattern established bydeepseekin #17634.openai_api_compatiblegainsChatWithMessages+ChatStreamlyWithSenderrequired by the unified handler infrastructure.openaidriver preservesreasoning_contentextraction for o-series models.