Repository navigation
feat(go-models): migrate batch 5 model drivers to unified handlers - #17700
Conversation
Migrate 7 model drivers to use shared doRequest/HandleNonStreamingResponse/HandleStreamingResponse helpers: - vllm (VLLMModel) - volcengine (VolcengineModel) - xai (XAIModel) - xiaomi (XiaomiModel) - xinference (XinferenceModel) - xunfei (XunfeiModel) - zhipu-ai (ZhipuAIModel)
|
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:
📝 WalkthroughWalkthroughSeven model drivers now use shared ChangesProvider handler migration
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant ProviderModel
participant BaseModel
participant ResponseHandler
participant Sender
ProviderModel->>BaseModel: Build authenticated chat request
BaseModel->>ResponseHandler: Pass non-streaming or streaming response
ResponseHandler->>Sender: Send reasoning and content callbacks
ResponseHandler-->>ProviderModel: Return parsed response or stream status
Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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: 4
🧹 Nitpick comments (1)
internal/entity/models/zhipu-ai.go (1)
160-160: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winStreaming transport is still built inline.
Lines 133-158 duplicate
doStreamRequest: JSON marshal, timeout context, POST construction, Bearer header,Do, and status check. The non-streaming path in the same file already uses the shared helper. See the consolidated comment for the shared fix.🤖 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/zhipu-ai.go` at line 160, Replace the inline streaming request setup in the surrounding streaming method with the existing doStreamRequest helper, passing the same request payload, configuration, and authentication inputs. Remove the duplicated marshal, timeout, POST, header, Do, and status-check logic while preserving the existing HandleStreamingResponse call and response handling.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/xai.go`:
- Line 136: Update ChatStreamlyWithSender to enable stream_options.include_usage
before sending the xAI streaming request, matching the configuration used by the
other streaming drivers. Keep HandleStreamingResponse unchanged so it can
populate modelUsage from the emitted usage payload.
In `@internal/entity/models/xiaomi.go`:
- Line 197: Update the Xiaomi streaming request construction to set
stream_options.include_usage to true, matching the other drivers, so
HandleStreamingResponse receives a usage payload and populates modelUsage.
Locate the request-body setup associated with the return call in the Xiaomi
streaming flow and preserve the existing parser and sender behavior.
In `@internal/entity/models/xunfei.go`:
- Around line 172-175: Update XunFei’s ListModels request flow around
baseModel.doRequest so it uses HTTP GET rather than the helper’s default POST
behavior. Add a narrowly scoped GET-capable helper or allow the shared helper to
accept a method, then invoke it from this ListModels path while preserving the
existing URL, configuration, response handling, and timeout.
In `@internal/entity/models/zhipu-ai.go`:
- Line 160: Remove the provider-local HTTP request construction in
internal/entity/models/zhipu-ai.go lines 133-158 and route the streaming flow
through z.baseModel.doStreamRequest, keeping HandleStreamingResponse in its
callback; make the equivalent replacement in internal/entity/models/xai.go lines
109-134 using x.baseModel.doStreamRequest. In internal/entity/models/xiaomi.go
lines 95-124 and 170-195, extend the shared request builder to accept the
driver's api-key authentication header, then route both paths through doRequest
and doStreamRequest respectively.
---
Nitpick comments:
In `@internal/entity/models/zhipu-ai.go`:
- Line 160: Replace the inline streaming request setup in the surrounding
streaming method with the existing doStreamRequest helper, passing the same
request payload, configuration, and authentication inputs. Remove the duplicated
marshal, timeout, POST, header, Do, and status-check logic while preserving the
existing HandleStreamingResponse call and response handling.
🪄 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: 7735187a-e5c6-46b4-8f5a-0947c4775def
📒 Files selected for processing (7)
internal/entity/models/vllm.gointernal/entity/models/volcengine.gointernal/entity/models/xai.gointernal/entity/models/xiaomi.gointernal/entity/models/xinference.gointernal/entity/models/xunfei.gointernal/entity/models/zhipu-ai.go
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 (2)
internal/entity/models/xunfei.go (2)
257-260: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick winDo not log raw streaming events at info level.
Each event can contain generated content, reasoning, and tool-call arguments. This writes that data to application logs. Remove the log block or log only non-sensitive metadata behind an explicit debug setting.
🤖 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/xunfei.go` around lines 257 - 260, Remove the raw event logging block inside the ParseSSEStream callback in xunfei.go, or gate a metadata-only log behind an explicit debug setting; do not serialize or emit the full event payload through common.Info.
124-192: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick winComplete the direct-request migration.
The file does not compile because it removes dependencies and request setup while retaining code that requires them.
internal/entity/models/xunfei.go#L124-L192: Delete the stale non-streaming request, response parsing, and unusedchatResponseblock afterdoRequest.internal/entity/models/xunfei.go#L20-L26: Keepbytesandnet/httpimports until the streaming path no longer uses direct HTTP requests.internal/entity/models/xunfei.go#L228-L253: Complete the shared streaming migration, or retain the imports required by the direct streaming request path.internal/entity/models/xunfei.go#L359-L375: Delete the stale model-list request code afterdoRequest;reqis no longer defined.Static analysis reports the resulting undefined identifiers and invalid redeclaration.
🤖 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/xunfei.go` around lines 124 - 192, Complete the direct-request migration in internal/entity/models/xunfei.go: remove the stale non-streaming request/response parsing and chatResponse block after doRequest, and remove the obsolete model-list request code after doRequest. At internal/entity/models/xunfei.go lines 20-26 and 228-253, either retain bytes/net/http and the direct streaming request path where still used, or finish migrating that streaming path so those imports and setup are no longer needed; ensure no undefined req references or invalid redeclarations remain.Source: Linters/SAST tools
🧹 Nitpick comments (1)
internal/entity/models/xunfei.go (1)
28-30: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the migration-history reference.
Keep this comment limited to the current Go implementation. Remove
Mirrors SparkChat.model2version in rag/llm/chat_model.py.As per coding guidelines, “keep package and doc comments aligned with the current runtime path rather than migration history.”
🤖 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/xunfei.go` around lines 28 - 30, Update the comment above sparkModelVersions to remove the reference to SparkChat.model2version and rag/llm/chat_model.py, keeping only the description of the current Go mapping and XunFei Spark HTTP API behavior.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.
Outside diff comments:
In `@internal/entity/models/xunfei.go`:
- Around line 257-260: Remove the raw event logging block inside the
ParseSSEStream callback in xunfei.go, or gate a metadata-only log behind an
explicit debug setting; do not serialize or emit the full event payload through
common.Info.
- Around line 124-192: Complete the direct-request migration in
internal/entity/models/xunfei.go: remove the stale non-streaming
request/response parsing and chatResponse block after doRequest, and remove the
obsolete model-list request code after doRequest. At
internal/entity/models/xunfei.go lines 20-26 and 228-253, either retain
bytes/net/http and the direct streaming request path where still used, or finish
migrating that streaming path so those imports and setup are no longer needed;
ensure no undefined req references or invalid redeclarations remain.
---
Nitpick comments:
In `@internal/entity/models/xunfei.go`:
- Around line 28-30: Update the comment above sparkModelVersions to remove the
reference to SparkChat.model2version and rag/llm/chat_model.py, keeping only the
description of the current Go mapping and XunFei Spark HTTP API behavior.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 0656cb24-d0ad-40c7-ac08-e704cf8b0f52
📒 Files selected for processing (1)
internal/entity/models/xunfei.go
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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 110-112: The stream-reasoning setup in the response handling flow
references undefined ParserConfig and default extractor symbols. Restore the
hook by defining ExtractStreamReasoning on ParserConfig and implementing
extractDefaultStreamReasoning, or replace this logic with the existing
ResponseParser while preserving the intended reasoning extraction behavior.
- Around line 190-200: Update the reasoning-only fallback in
HandleNonStreamingResponse so messages using the top-level "reasoning" field
receive the same empty Answer value already applied to "reasoning_content"-only
messages. Preserve the existing reasoning extraction and ensure responses
without content or tool_calls no longer return “no choices in response”.
🪄 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: e8e511ce-1353-4224-87b8-7d5cb7bf8949
📒 Files selected for processing (1)
internal/entity/models/response_handler.go
… drop dead stream usage decoder - BaseModel gains an optional authHeader hook so drivers with non-standard authentication (Xiaomi's api-key header, Xunfei's spark_api_password bundle) can share doRequest/doStreamRequest instead of inlining HTTP. - newJSONPostRequest becomes a BaseModel method; auth is applied via the hook with the default "Authorization: Bearer <key>" unchanged. - Add doGetRequest for shared GET calls (xAI/Xunfei ListModels). - Remove decodeOpenAICompatibleStreamUsage (no callers) and its mapstructure dependency. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…in stream handler A terminal SSE event carrying only a root-level finish_reason (no choices, no [DONE]) was skipped by the choices guard, leaving sawTerminal false and failing the stream with "stream ended before [DONE] or finish_reason". Hoist the root-level finish_reason check above the choices guard so such events terminate the stream cleanly, and add tests for both the bare finish_reason event and a genuinely truncated stream. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
No driver calls these anymore after the batch migrations; only extractThinkContent (used by the shared response handler) is kept. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…e compile errors The remote half-migrated xunfei.go did not compile: ChatWithMessages and ListModels kept dead inline HTTP code referencing undefined jsonData/req, with a duplicate body declaration and a double return. Finish the migration: - ChatWithMessages: doRequest + HandleNonStreamingResponse only. - ChatStreamlyWithSender: doStreamRequest + HandleStreamingResponse; drop the per-event payload logging and manual [DONE]/tool-call handling. - ListModels: shared doGetRequest (GET) instead of the broken POST path. - Auth via the new BaseModel authHeader hook (spark_api_password bundle). Xunfei does not document stream_options support, but its streaming responses carry usage in the final chunk by default, so usage reporting works without include_usage; the stream test asserts this. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…d handlers ChatStreamlyWithSender moves to doStreamRequest + HandleStreamingResponse and requests stream_options.include_usage so streaming reports token usage. ListModels uses the shared doGetRequest; the duplicated "Parse response" comment is dropped. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…pi-key auth hook Xiaomi authenticates with the non-standard "api-key" header, which the shared helpers previously could not produce. The new BaseModel authHeader hook lets it use doRequest/doStreamRequest like every other driver: - ChatWithMessages: doRequest + HandleNonStreamingResponse. - ChatStreamlyWithSender: doStreamRequest + HandleStreamingResponse with stream_options.include_usage so streaming reports token usage. - ASR/TTS requests apply the same auth hook. Also drop the xinference idle-timeout test: the idle-timeout mechanism was removed when the driver moved to the shared doStreamRequest, which enforces the streamCallTimeout total deadline instead. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
ChatStreamlyWithSender hardcoded "/chat/completions" while ChatWithMessages used URLSuffix.Chat. Build the streaming URL from the suffix too, and harden the stream test to use a non-default suffix and assert the request path. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/entity/models/response_handler_test.go (1)
26-30: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the migration-history text from the test comment.
Keep the comment limited to the current behavior that the test verifies.
Proposed change
-// TestHandleStreamingResponseBareRootFinishReason verifies the shared handler -// terminates the stream when an event carries only a root-level finish_reason -// with no choices and no trailing [DONE]. Before the fix this event was -// skipped by the choices guard and the handler returned "stream ended before -// [DONE] or finish_reason". +// TestHandleStreamingResponseBareRootFinishReason verifies the shared handler +// accepts a root-level finish_reason event with no choices and emits its +// terminal marker.🤖 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_test.go` around lines 26 - 30, Update the comment for TestHandleStreamingResponseBareRootFinishReason to describe only the current behavior being verified: terminating the stream on a root-level finish_reason event without choices or trailing [DONE]. Remove the historical “Before the fix” explanation and prior failure details.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/xunfei_test.go`:
- Around line 137-165: Both HTTP test handlers currently accept any request
path; assert the configured chat endpoint before processing requests. In
internal/entity/models/xunfei_test.go lines 137-165, add a check that r.URL.Path
is "/v1/chat/completions" before decoding the non-streaming body, and apply the
same assertion in lines 191-206 before writing the streaming response.
---
Nitpick comments:
In `@internal/entity/models/response_handler_test.go`:
- Around line 26-30: Update the comment for
TestHandleStreamingResponseBareRootFinishReason to describe only the current
behavior being verified: terminating the stream on a root-level finish_reason
event without choices or trailing [DONE]. Remove the historical “Before the fix”
explanation and prior failure details.
🪄 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: 1c95a035-a99d-4ffd-a925-dafc6d42ce12
📒 Files selected for processing (14)
internal/entity/models/base_model.gointernal/entity/models/common.gointernal/entity/models/common_test.gointernal/entity/models/response_handler.gointernal/entity/models/response_handler_test.gointernal/entity/models/volcengine.gointernal/entity/models/volcengine_test.gointernal/entity/models/xai.gointernal/entity/models/xai_test.gointernal/entity/models/xiaomi.gointernal/entity/models/xiaomi_test.gointernal/entity/models/xinference_test.gointernal/entity/models/xunfei.gointernal/entity/models/xunfei_test.go
💤 Files with no reviewable changes (3)
- internal/entity/models/common.go
- internal/entity/models/common_test.go
- internal/entity/models/xinference_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
- internal/entity/models/volcengine.go
- internal/entity/models/xiaomi.go
|
@coderabbitai review |
|
✅ Action performedReview finished.
|
…equest ChatStreamlyWithSender still built the HTTP request inline; move it onto the shared doStreamRequest + HandleStreamingResponse path used by the other batch-5 drivers, keeping the existing stream_options.include_usage. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
| httpClient: NewDriverHTTPClient(false), | ||
| // Xiaomi authenticates with the non-standard "api-key" header | ||
| // instead of "Authorization: Bearer". | ||
| authHeader: func(cfg *APIConfig) (string, string) { |
…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. Completes the batch 5 migration of 7 OpenAI-compatible drivers (
vllm,volcengine,xai,xiaomi,xinference,xunfei,zhipu-ai) onto the unified request/response helpers (doRequest/doStreamRequest+HandleNonStreamingResponse/HandleStreamingResponse+ParserConfig), established bydeepseekin #17634.This branch is rebased on the current
pr/migrate-models-batch5and fixes the issues in the previous state of the PR.Fixes
xai,xiaomi,xunfei, andzhipu-aipreviously still built their chat HTTP requests inline; they now all ridedoRequest/doStreamRequest+ the shared response handlers. (vllm,volcengine,xinferencealready did.)jsonData/req(withnet/http/bytesnever imported) and a duplicatebodydeclaration.ChatWithMessages,ChatStreamlyWithSender, andListModelsnow fully use the shared helpers.BaseModelgains an optionalauthHeaderhook (default behavior unchanged:Authorization: Bearer <key>). Xiaomi's non-standardapi-keyheader and Xunfei'sspark_api_passwordbundle now ride the shareddoRequest/doStreamRequestinstead of inlining HTTP per driver. xAI and ZhipuAI use the default hook.xai,xiaomi, andzhipu-aistreaming now requeststream_options.include_usageso token usage is reported. Xunfei does not documentstream_optionssupport, but its streaming responses carryusagein the final chunk by default — usage reporting works without it (covered by a test).HandleStreamingResponse: a terminal SSE event carrying only a root-levelfinish_reason(no choices, no[DONE]) was rejected as "stream ended before [DONE] or finish_reason"; the check now runs before the choices guard./chat/completionsinstead ofURLSuffix.Chat; it now uses the suffix like the non-streaming path.GetThinkingAndAnswer/NormalizeModelFamily,decodeOpenAICompatibleStreamUsage(mapstructure), and the xinference idle-timeout test (the mechanism no longer exists).Net: 8 commits on top of the branch base, ~350 insertions / ~520 deletions across the batch-5 drivers and shared helpers.