Repository navigation
feat(models): add shared HTTP client, SSE parser, and stub helpers for Go model drivers - #15821
Conversation
|
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:
📝 WalkthroughWalkthroughAdds NewDriverHTTPClient, PostJSONRequest, ReadErrorBody, and ParseSSEStream; migrates all model constructors to use the shared HTTP client and replaces scanner-based SSE streaming with ParseSSEStream callbacks across providers. ChangesShared Utilities
Provider migrations
🎯 4 (Complex) | ⏱️ ~60 minutes
Suggested reviewers
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15821 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Haruko386
left a comment
There was a problem hiding this comment.
@JPette1783 do these changes
| func (a *AvianModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) { | ||
| return nil, fmt.Errorf("%s, no such method", a.Name()) | ||
| } | ||
|
|
||
| func (a *AvianModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) { | ||
| return nil, fmt.Errorf("%s, no such method", a.Name()) | ||
| } | ||
|
|
||
| func (a *AvianModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) { | ||
| return nil, fmt.Errorf("%s, no such method", a.Name()) | ||
| } | ||
|
|
||
| func (a *AvianModel) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) { | ||
| return nil, fmt.Errorf("%s, no such method", a.Name()) | ||
| } | ||
|
|
||
| func (a *AvianModel) TranscribeAudioWithSender(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig, sender func(*string, *string) error) error { | ||
| return fmt.Errorf("%s, no such method", a.Name()) | ||
| } | ||
|
|
||
| func (a *AvianModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) { | ||
| return nil, fmt.Errorf("%s, no such method", a.Name()) | ||
| } | ||
|
|
||
| func (a *AvianModel) AudioSpeechWithSender(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig, sender func(*string, *string) error) error { | ||
| return fmt.Errorf("%s, no such method", a.Name()) | ||
| } | ||
|
|
||
| func (a *AvianModel) OCRFile(modelName *string, content []byte, url *string, apiConfig *APIConfig, ocrConfig *OCRConfig) (*OCRFileResponse, error) { | ||
| return nil, fmt.Errorf("%s, no such method", a.Name()) | ||
| } | ||
|
|
||
| func (a *AvianModel) ParseFile(modelName *string, content []byte, url *string, apiConfig *APIConfig, parseFileConfig *ParseFileConfig) (*ParseFileResponse, error) { | ||
| return nil, fmt.Errorf("%s, no such method", a.Name()) | ||
| } | ||
|
|
||
| func (a *AvianModel) ListTasks(apiConfig *APIConfig) ([]ListTaskStatus, error) { | ||
| return nil, fmt.Errorf("%s, no such method", a.Name()) | ||
| } | ||
|
|
||
| func (a *AvianModel) ShowTask(taskID string, apiConfig *APIConfig) (*TaskResponse, error) { | ||
| return nil, fmt.Errorf("%s, no such method", a.Name()) | ||
| } |
| // AvianModel implements ModelDriver for Avian (https://api.avian.io/docs/). | ||
| type AvianModel struct { | ||
| baseModel BaseModel | ||
| UnimplementedModelDriver |
There was a problem hiding this comment.
no need UnimplementedModelDriver for now, we shall do model provider refactor internal
| transport := http.DefaultTransport.(*http.Transport).Clone() | ||
| transport.MaxIdleConns = 100 | ||
| transport.MaxIdleConnsPerHost = 10 | ||
| transport.IdleConnTimeout = 90 * time.Second | ||
| transport.DisableCompression = false | ||
| transport.ResponseHeaderTimeout = 60 * time.Second | ||
|
|
There was a problem hiding this comment.
you delete http settting and not use another way to set it
| func ParseSSEStream(r io.Reader, onEvent func(event map[string]interface{}) error) error { | ||
| scanner := bufio.NewScanner(r) | ||
| scanner.Buffer(make([]byte, 64*1024), 1024*1024) | ||
| for scanner.Scan() { | ||
| line := scanner.Text() | ||
| if !strings.HasPrefix(line, "data:") { | ||
| continue | ||
| } | ||
| data := strings.TrimSpace(line[5:]) | ||
| if data == "[DONE]" { | ||
| return nil | ||
| } | ||
| var event map[string]interface{} | ||
| if err := json.Unmarshal([]byte(data), &event); err != nil { | ||
| continue | ||
| } | ||
| if err := onEvent(event); err != nil { | ||
| return err | ||
| } | ||
| } | ||
| return scanner.Err() | ||
| } |
There was a problem hiding this comment.
could you implement this in all provider and provide your test output in RAGFlow CLI ?
… drivers Address PR infiniflow#15821 reviewer feedback: - Remove UnimplementedModelDriver from avian.go; restore explicit no-op stubs - Delete driver_stubs.go (UnimplementedModelDriver rejected for now) - Make ParseSSEStream generic [T any], returning (done bool, err error) to allow typed event structs and expose whether [DONE] was received - Apply ParseSSEStream to all 48 OpenAI-compatible SSE streaming methods across every provider (avian, openai, deepseek, volcengine, and 44 others) - ollama.go and replicate.go intentionally left unchanged: ollama uses NDJSON (no data: prefix) and replicate uses non-standard multi-field SSE with plain-text data — both are incompatible with ParseSSEStream - NewDriverHTTPClient() in driver_http.go preserves the same transport settings that were previously inline in each constructor
|
Please review this again @Haruko386. |
There was a problem hiding this comment.
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 (6)
internal/entity/models/qiniu.go (1)
350-389:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winMissing termination tracking; premature stream end goes undetected.
Unlike other refactored drivers (longcat, openai, upstage), this implementation ignores the
donereturn value and doesn't tracksawTerminal. Consider adding termination tracking for consistency:- if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { + sawTerminal := false + done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { common.Info(fmt.Sprintf("%v", event)) choices, ok := event["choices"].([]interface{}) @@ ... extract delta ... + finishReason, ok := firstChoice["finish_reason"].(string) + if ok && finishReason != "" { + sawTerminal = true + } return nil }); err != nil { return fmt.Errorf("failed to scan response body: %w", err) } + if !done && !sawTerminal { + return fmt.Errorf("qiniu: stream ended before [DONE] or finish_reason") + }🤖 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/qiniu.go` around lines 350 - 389, The ParseSSEStream call currently ignores the returned done flag and doesn't track stream termination; modify the call to capture both the return values (e.g., done, err := ParseSSEStream...) and set a local sawTerminal boolean to true when done is true (or when you receive a terminal event inside the callback), then only send the endOfStream "[DONE]" marker via sender if sawTerminal is false; ensure error handling still returns fmt.Errorf(...) when err != nil and keep existing sender usage for content/reasoning_content.internal/entity/models/302ai.go (1)
336-373:⚠️ Potential issue | 🟠 MajorHandle premature SSE termination for 302ai stream
internal/entity/models/302ai.go’sChatStreamlyWithSenderdiscards the(done)return fromParseSSEStreamand never trackssawTerminal/ checksfinish_reason, then unconditionally sends a synthetic"[DONE]".ParseSSEStreamreturns(done=false, err=nil)when the upstream reader exhausts without receiving thedata: [DONE]sentinel, so an early/partial upstream close will currently be treated as success.- Some drivers (e.g.,
groq.go,huaweicloud.go,moonshot.go,n1n.go,tokenpony.go) error on!done && !sawTerminal, whilezhipu-ai.gofollows the “ignore done” pattern too—should 302ai align with the stricter behavior, or is EOF-without-[DONE] expected for this provider?🤖 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/302ai.go` around lines 336 - 373, ChatStreamlyWithSender currently ignores the boolean "done" returned by ParseSSEStream and always emits a synthetic "[DONE]" even when the upstream closed early; update ChatStreamlyWithSender to capture the (done, err) result from ParseSSEStream (call to ParseSSEStream[map[string]interface{}](...)) and, on success (err == nil), check done and any sawTerminal/finish_reason state (as exposed by ParseSSEStream or the event parsing logic) and return an error when the stream ended without the expected terminal sentinel (i.e., !done && !sawTerminal) instead of sending a synthetic end-of-stream marker; only emit the "[DONE]" marker when done is true (or when the provider's contract explicitly expects EOF-without-[DONE], in which case document that behavior). Ensure you reference ChatStreamlyWithSender, ParseSSEStream, sender, and the endOfStream ("[DONE]") variable when making the change.internal/entity/models/lmstudio.go (1)
250-284:⚠️ Potential issue | 🟠 Major | ⚡ Quick winNil pointer dereference:
modelConfigaccessed without nil check.If
modelConfigis nil, accessingmodelConfig.Streamat line 250 will cause a panic. The non-streamingChatWithMessagesmethod (line 102) correctly wraps similar accesses inif chatModelConfig != nil.🐛 Proposed fix
+ if modelConfig != nil { if modelConfig.Stream != nil { reqBody["stream"] = *modelConfig.Stream } // ... rest of field accesses + }🤖 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/lmstudio.go` around lines 250 - 284, The code accesses modelConfig fields directly and can panic when modelConfig is nil; wrap the entire block that checks modelConfig.Stream, MaxTokens, Temperature, DoSample, TopP, Stop, and Thinking inside a nil check (e.g., if modelConfig != nil { ... }) so each field is only dereferenced when modelConfig is non-nil; update the same enclosing function that builds reqBody (the section using modelConfig in lmstudio.go) to mirror the guard used in ChatWithMessages to prevent nil pointer dereference.internal/entity/models/huggingface.go (1)
226-260:⚠️ Potential issue | 🟠 Major | ⚡ Quick winNil pointer dereference:
modelConfigaccessed without nil check.This method accesses
modelConfigfields directly without verifying it's non-nil. IfmodelConfigis nil, line 226 will panic.🐛 Proposed fix
+ if modelConfig != nil { if modelConfig.Stream != nil { reqBody["stream"] = *modelConfig.Stream } // ... rest of modelConfig field accesses + }🤖 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/huggingface.go` around lines 226 - 260, The code accesses modelConfig fields (e.g., modelConfig.Stream, MaxTokens, Temperature, DoSample, TopP, Stop, Thinking) without checking for nil which can panic; add a nil-check for modelConfig at the start of the block (or return/skip the block when modelConfig == nil) and only perform the existing reqBody assignments when modelConfig is non-nil — you can wrap the existing lines in if modelConfig != nil { ... } (ensuring the Thinking handling remains inside that guard).internal/entity/models/aliyun.go (1)
238-268:⚠️ Potential issue | 🟠 Major | ⚡ Quick winNil pointer dereference:
chatModelConfigaccessed without nil check.Unlike
ChatWithMessages(line 96), this method accesseschatModelConfigfields directly without first checking if it's nil. IfchatModelConfigis nil, line 238 will panic.🐛 Proposed fix
- if chatModelConfig.Stream != nil { - reqBody["stream"] = *chatModelConfig.Stream - } - - if chatModelConfig.MaxTokens != nil { + if chatModelConfig != nil { + if chatModelConfig.Stream != nil { + reqBody["stream"] = *chatModelConfig.Stream + } + + if chatModelConfig.MaxTokens != nil { ...Or wrap the entire block in
if chatModelConfig != nil { ... }similar toChatWithMessages.🤖 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/aliyun.go` around lines 238 - 268, The block that reads fields from chatModelConfig (checking Stream, MaxTokens, Temperature, DoSample, TopP, Stop, Thinking) can panic if chatModelConfig is nil; wrap the entire block in a nil-check like if chatModelConfig != nil { ... } (matching the pattern used in ChatWithMessages) so all dereferences of chatModelConfig are guarded and the function (e.g., the method containing this code) will not cause a nil pointer dereference.internal/entity/models/openrouter.go (1)
301-344:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winMissing terminal condition tracking.
Unlike other drivers in this PR (cohere, cometapi, deepinfra, deepseek, futurmix, gitee), this implementation doesn't track
finish_reasonviasawTerminaland doesn't validate that the stream completed properly before sending[DONE].If the server closes the connection prematurely (without sending
[DONE]or afinish_reason), this will silently emit[DONE]to the sender instead of returning an error, potentially masking incomplete responses.🔧 Suggested fix to match other drivers
+ sawTerminal := false if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { common.Info(fmt.Sprintf("%v", event)) choices, ok := event["choices"].([]interface{}) if !ok || len(choices) == 0 { return nil } firstChoice, ok := choices[0].(map[string]interface{}) if !ok { return nil } delta, ok := firstChoice["delta"].(map[string]interface{}) if !ok { return nil } reasoningContent, ok := delta["reasoning"].(string) if ok && reasoningContent != "" { if err := sender(nil, &reasoningContent); err != nil { return err } } content, ok := delta["content"].(string) if ok && content != "" { if err := sender(&content, nil); err != nil { return err } } + if fr, ok := firstChoice["finish_reason"].(string); ok && fr != "" { + sawTerminal = true + } return nil }); err != nil { return fmt.Errorf("failed to scan response body: %w", err) } + if !sawTerminal { + return fmt.Errorf("openrouter: stream ended before [DONE] or finish_reason") + }🤖 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 301 - 344, The stream handler using ParseSSEStream should track a sawTerminal boolean (like other drivers) and set it true when a finish_reason or terminal event is observed (inspect firstChoice["finish_reason"] or equivalent, and/or when the final event indicates completion), instead of blindly sending the OpenAI-style "[DONE]"; after ParseSSEStream returns, if sawTerminal is false return an error indicating premature stream closure and only call sender with endOfStream = "[DONE]" when sawTerminal is true; update symbols ParseSSEStream, sender, and any references to firstChoice/delta/finish_reason to perform the tracking and validation so incomplete streams are not masked.
🧹 Nitpick comments (5)
internal/entity/models/xiaomi.go (3)
791-805: 💤 Low valueTTS stream ignores done flag and doesn't send [DONE] marker.
Unlike
readXiaomiASRStream(which sends[DONE]at line 611-612) andChatStreamlyWithSender(lines 354-357), this function returnsnildirectly without sending a[DONE]marker. If callers depend on receiving the[DONE]signal for stream termination, this inconsistency could cause issues.🤖 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/xiaomi.go` around lines 791 - 805, readXiaomiTTSStream never emits the stream termination marker; after successfully parsing the SSE stream with ParseSSEStream in readXiaomiTTSStream you must send a "[DONE]" marker via the existing sender callback just like readXiaomiASRStream and ChatStreamlyWithSender do; update readXiaomiTTSStream to call sender(&doneMarker, nil) (where doneMarker := "[DONE]") after ParseSSEStream returns nil and propagate any sender error instead of discarding it.
318-359: ⚡ Quick winInconsistent stream termination validation compared to other drivers.
Unlike baichuan, ppio, siliconflow, and xai drivers which all check
if !done && !sawTerminalto detect truncated streams, this implementation ignores thedonereturn value and doesn't trackfinish_reason. If the provider terminates the stream unexpectedly (without[DONE]orfinish_reason), this driver will silently succeed while others would return an error.Consider adding the same validation pattern for consistency:
- if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { + sawTerminal := false + done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { choices, ok := event["choices"].([]interface{}) ... + finishReason, ok := firstChoice["finish_reason"].(string) + if ok && finishReason != "" { + sawTerminal = true + } return nil }); err != nil { return fmt.Errorf("failed to scan response body: %w", err) } + if !done && !sawTerminal { + return fmt.Errorf("xiaomi: stream ended before [DONE] or finish_reason") + }🤖 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/xiaomi.go` around lines 318 - 359, Parse and honor the ParseSSEStream boolean result and track terminal indications (finish_reason) before sending the explicit "[DONE]": capture the first return value from ParseSSEStream into a done variable instead of discarding it, add a sawTerminal boolean that you set to true whenever you encounter a non-empty finish_reason in the delta (e.g., check delta["finish_reason"] and set sawTerminal = true), then after ParseSSEStream completes validate with the same pattern used by other drivers (if !done && !sawTerminal { return fmt.Errorf("truncated stream") }) prior to calling sender("[DONE]", nil); keep references to ParseSSEStream, sender, done, sawTerminal, and finish_reason to locate the changes.
594-613: 💤 Low valueASR stream also ignores done flag.
Same inconsistency as the chat streaming:
readXiaomiASRStreamignores thedonereturn value. For consistency with other drivers, consider validating proper stream termination.🤖 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/xiaomi.go` around lines 594 - 613, readXiaomiASRStream currently calls sender(&done, nil) but ignores whether the sender signals stream termination or returns an error; update the function to handle the sender's termination/error the same way other drivers do: after creating done := "[DONE]" call sender(&done, nil) and check its return value, returning that error if non-nil, and if your sender implementation exposes a termination flag (as in other drivers) respect that flag to stop further processing; modify readXiaomiASRStream to return the sender's result instead of unconditionally returning nil so stream termination and errors propagate correctly.internal/entity/models/cometapi.go (1)
226-236: 💤 Low value
parseCometAPIStreamEventis now unused.This helper function is no longer called after migrating to
ParseSSEStreamwith an inline callback. Consider removing it to reduce dead code.🤖 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/cometapi.go` around lines 226 - 236, The function parseCometAPIStreamEvent is now unused after migrating to ParseSSEStream with an inline callback; remove the dead function definition (parseCometAPIStreamEvent) from the codebase, ensure there are no remaining references to it (grep/search for parseCometAPIStreamEvent), and run a build/tests to confirm nothing else depended on it; if any logic in parseCometAPIStreamEvent is still needed, move that specific logic into the inline callback used by ParseSSEStream instead of keeping the standalone helper.internal/entity/models/fishaudio.go (1)
303-320: 💤 Low valueConsider extracting the inline struct to avoid duplication.
The anonymous struct is defined identically in both the type parameter and callback parameter. A named type would be cleaner:
♻️ Suggested refactor
+type fishAudioTTSEvent struct { + AudioBase64 string `json:"audio_base64"` +} + func (f *FishAudioModel) AudioSpeechWithSender(...) error { // ... existing code ... - if _, err := ParseSSEStream[struct { - AudioBase64 string `json:"audio_base64"` - }](resp.Body, func(event struct { - AudioBase64 string `json:"audio_base64"` - }) error { + if _, err := ParseSSEStream[fishAudioTTSEvent](resp.Body, func(event fishAudioTTSEvent) error { if event.AudioBase64 != "" {🤖 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/fishaudio.go` around lines 303 - 320, The code uses the same anonymous struct twice in the ParseSSEStream call (both as the type parameter and the callback parameter); define a single named type (e.g., type audioEvent struct { AudioBase64 string `json:"audio_base64"` }) and replace the anonymous struct in the ParseSSEStream[...](...) generic and the callback signature with that named type; keep the existing logic inside the callback (base64 decode, build chunk string, call sender) but reference audioEvent in ParseSSEStream and the callback to remove duplication and improve clarity.
🤖 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/baidu.go`:
- Line 361: The call common.Info(event) is failing because common.Info requires
a string but event is a map[string]interface{}; convert or format event to a
string before logging (e.g., marshal event to JSON or use fmt.Sprintf) and pass
that string to common.Info; update the code where event is used in
internal/entity/models/baidu.go (the variable named event) to produce a string
(mirroring the pattern used in volcengine.go) and call common.Info with that
string.
In `@internal/entity/models/orcarouter.go`:
- Around line 295-296: The code currently discards the termination tracking
variables `done` and `sawTerminal`; update the loop or reader where they are
referenced (the block with `_ = done` and `_ = sawTerminal`) to perform an
explicit termination check like other drivers: listen on the `done` channel (or
check its closed state) and break/return when it signals, and respect
`sawTerminal` by stopping processing and closing the stream when it becomes
true. Replace the ignored assignments with a select/if that monitors `done` and
`sawTerminal`, performs any necessary cleanup, and exits the loop to avoid
processing after premature stream closure.
In `@internal/entity/models/vllm.go`:
- Line 317: The call common.Info(event) passes event (a map[string]interface{})
but common.Info expects a string; update the vllm.go code around the event
variable to serialize event to a string before logging (e.g.,
json.Marshal(event) and convert to string) and handle marshal errors (fall back
to fmt.Sprintf("%v", event) if marshal fails) so you call
common.Info(serializedEventString) instead of passing the map directly;
reference the event variable and common.Info call in the vllm.go diff.
In `@internal/entity/models/zhipu-ai.go`:
- Line 312: common.Info is being passed a map[string]interface{} (the variable
event) but it expects a string; convert event to a string before calling
common.Info. Replace the direct call common.Info(event) in zhipu-ai.go with code
that marshals event to JSON (using json.Marshal) and handles the marshal error
(fallback to fmt.Sprintf("%v") or a clear error message), then pass the
resulting string to common.Info; ensure you import encoding/json (and fmt if
needed) and keep the log call as common.Info(jsonStr).
---
Outside diff comments:
In `@internal/entity/models/302ai.go`:
- Around line 336-373: ChatStreamlyWithSender currently ignores the boolean
"done" returned by ParseSSEStream and always emits a synthetic "[DONE]" even
when the upstream closed early; update ChatStreamlyWithSender to capture the
(done, err) result from ParseSSEStream (call to
ParseSSEStream[map[string]interface{}](...)) and, on success (err == nil), check
done and any sawTerminal/finish_reason state (as exposed by ParseSSEStream or
the event parsing logic) and return an error when the stream ended without the
expected terminal sentinel (i.e., !done && !sawTerminal) instead of sending a
synthetic end-of-stream marker; only emit the "[DONE]" marker when done is true
(or when the provider's contract explicitly expects EOF-without-[DONE], in which
case document that behavior). Ensure you reference ChatStreamlyWithSender,
ParseSSEStream, sender, and the endOfStream ("[DONE]") variable when making the
change.
In `@internal/entity/models/aliyun.go`:
- Around line 238-268: The block that reads fields from chatModelConfig
(checking Stream, MaxTokens, Temperature, DoSample, TopP, Stop, Thinking) can
panic if chatModelConfig is nil; wrap the entire block in a nil-check like if
chatModelConfig != nil { ... } (matching the pattern used in ChatWithMessages)
so all dereferences of chatModelConfig are guarded and the function (e.g., the
method containing this code) will not cause a nil pointer dereference.
In `@internal/entity/models/huggingface.go`:
- Around line 226-260: The code accesses modelConfig fields (e.g.,
modelConfig.Stream, MaxTokens, Temperature, DoSample, TopP, Stop, Thinking)
without checking for nil which can panic; add a nil-check for modelConfig at the
start of the block (or return/skip the block when modelConfig == nil) and only
perform the existing reqBody assignments when modelConfig is non-nil — you can
wrap the existing lines in if modelConfig != nil { ... } (ensuring the Thinking
handling remains inside that guard).
In `@internal/entity/models/lmstudio.go`:
- Around line 250-284: The code accesses modelConfig fields directly and can
panic when modelConfig is nil; wrap the entire block that checks
modelConfig.Stream, MaxTokens, Temperature, DoSample, TopP, Stop, and Thinking
inside a nil check (e.g., if modelConfig != nil { ... }) so each field is only
dereferenced when modelConfig is non-nil; update the same enclosing function
that builds reqBody (the section using modelConfig in lmstudio.go) to mirror the
guard used in ChatWithMessages to prevent nil pointer dereference.
In `@internal/entity/models/openrouter.go`:
- Around line 301-344: The stream handler using ParseSSEStream should track a
sawTerminal boolean (like other drivers) and set it true when a finish_reason or
terminal event is observed (inspect firstChoice["finish_reason"] or equivalent,
and/or when the final event indicates completion), instead of blindly sending
the OpenAI-style "[DONE]"; after ParseSSEStream returns, if sawTerminal is false
return an error indicating premature stream closure and only call sender with
endOfStream = "[DONE]" when sawTerminal is true; update symbols ParseSSEStream,
sender, and any references to firstChoice/delta/finish_reason to perform the
tracking and validation so incomplete streams are not masked.
In `@internal/entity/models/qiniu.go`:
- Around line 350-389: The ParseSSEStream call currently ignores the returned
done flag and doesn't track stream termination; modify the call to capture both
the return values (e.g., done, err := ParseSSEStream...) and set a local
sawTerminal boolean to true when done is true (or when you receive a terminal
event inside the callback), then only send the endOfStream "[DONE]" marker via
sender if sawTerminal is false; ensure error handling still returns
fmt.Errorf(...) when err != nil and keep existing sender usage for
content/reasoning_content.
---
Nitpick comments:
In `@internal/entity/models/cometapi.go`:
- Around line 226-236: The function parseCometAPIStreamEvent is now unused after
migrating to ParseSSEStream with an inline callback; remove the dead function
definition (parseCometAPIStreamEvent) from the codebase, ensure there are no
remaining references to it (grep/search for parseCometAPIStreamEvent), and run a
build/tests to confirm nothing else depended on it; if any logic in
parseCometAPIStreamEvent is still needed, move that specific logic into the
inline callback used by ParseSSEStream instead of keeping the standalone helper.
In `@internal/entity/models/fishaudio.go`:
- Around line 303-320: The code uses the same anonymous struct twice in the
ParseSSEStream call (both as the type parameter and the callback parameter);
define a single named type (e.g., type audioEvent struct { AudioBase64 string
`json:"audio_base64"` }) and replace the anonymous struct in the
ParseSSEStream[...](...) generic and the callback signature with that named
type; keep the existing logic inside the callback (base64 decode, build chunk
string, call sender) but reference audioEvent in ParseSSEStream and the callback
to remove duplication and improve clarity.
In `@internal/entity/models/xiaomi.go`:
- Around line 791-805: readXiaomiTTSStream never emits the stream termination
marker; after successfully parsing the SSE stream with ParseSSEStream in
readXiaomiTTSStream you must send a "[DONE]" marker via the existing sender
callback just like readXiaomiASRStream and ChatStreamlyWithSender do; update
readXiaomiTTSStream to call sender(&doneMarker, nil) (where doneMarker :=
"[DONE]") after ParseSSEStream returns nil and propagate any sender error
instead of discarding it.
- Around line 318-359: Parse and honor the ParseSSEStream boolean result and
track terminal indications (finish_reason) before sending the explicit "[DONE]":
capture the first return value from ParseSSEStream into a done variable instead
of discarding it, add a sawTerminal boolean that you set to true whenever you
encounter a non-empty finish_reason in the delta (e.g., check
delta["finish_reason"] and set sawTerminal = true), then after ParseSSEStream
completes validate with the same pattern used by other drivers (if !done &&
!sawTerminal { return fmt.Errorf("truncated stream") }) prior to calling
sender("[DONE]", nil); keep references to ParseSSEStream, sender, done,
sawTerminal, and finish_reason to locate the changes.
- Around line 594-613: readXiaomiASRStream currently calls sender(&done, nil)
but ignores whether the sender signals stream termination or returns an error;
update the function to handle the sender's termination/error the same way other
drivers do: after creating done := "[DONE]" call sender(&done, nil) and check
its return value, returning that error if non-nil, and if your sender
implementation exposes a termination flag (as in other drivers) respect that
flag to stop further processing; modify readXiaomiASRStream to return the
sender's result instead of unconditionally returning nil so stream termination
and errors propagate correctly.
🪄 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
Run ID: e363c1cf-527b-4450-bd02-478c80b2cdc0
📒 Files selected for processing (50)
internal/entity/models/302ai.gointernal/entity/models/aliyun.gointernal/entity/models/astraflow.gointernal/entity/models/avian.gointernal/entity/models/azure_openai.gointernal/entity/models/baichuan.gointernal/entity/models/baidu.gointernal/entity/models/cohere.gointernal/entity/models/cometapi.gointernal/entity/models/deepinfra.gointernal/entity/models/deepseek.gointernal/entity/models/fishaudio.gointernal/entity/models/futurmix.gointernal/entity/models/gitee.gointernal/entity/models/gpustack.gointernal/entity/models/groq.gointernal/entity/models/huaweicloud.gointernal/entity/models/huggingface.gointernal/entity/models/hunyuan.gointernal/entity/models/jiekouai.gointernal/entity/models/lmstudio.gointernal/entity/models/localai.gointernal/entity/models/longcat.gointernal/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/nvidia.gointernal/entity/models/openai.gointernal/entity/models/openrouter.gointernal/entity/models/orcarouter.gointernal/entity/models/perplexity.gointernal/entity/models/ppio.gointernal/entity/models/qiniu.gointernal/entity/models/siliconflow.gointernal/entity/models/sse_stream.gointernal/entity/models/stepfun.gointernal/entity/models/togetherai.gointernal/entity/models/tokenhub.gointernal/entity/models/tokenpony.gointernal/entity/models/upstage.gointernal/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
| _ = done | ||
| _ = sawTerminal |
There was a problem hiding this comment.
Unused termination tracking may hide premature stream closure.
Unlike other refactored drivers (e.g., longcat, openai, upstage), this code explicitly discards both done and sawTerminal. Consider adding a termination check consistent with other drivers:
- _ = done
- _ = sawTerminal
+ if !done && !sawTerminal {
+ return fmt.Errorf("orcarouter: stream ended before [DONE] or finish_reason")
+ }🤖 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/orcarouter.go` around lines 295 - 296, The code
currently discards the termination tracking variables `done` and `sawTerminal`;
update the loop or reader where they are referenced (the block with `_ = done`
and `_ = sawTerminal`) to perform an explicit termination check like other
drivers: listen on the `done` channel (or check its closed state) and
break/return when it signals, and respect `sawTerminal` by stopping processing
and closing the stream when it becomes true. Replace the ignored assignments
with a select/if that monitors `done` and `sawTerminal`, performs any necessary
cleanup, and exits the loop to avoid processing after premature stream closure.
|
@JPette1783 fix the CI error first |
|
Hi, @Haruko386 , |
Haruko386
left a comment
There was a problem hiding this comment.
Hi @JPette1783 plz do some changes
There was a problem hiding this comment.
Refactor this for all model provider
There was a problem hiding this comment.
I suggest put this func in base_model.go
…ove ParseSSEStream to base_model Addresses review feedback on PR infiniflow#15821: - "Refactor this for all model provider" (driver_http.go): every OpenAI-compatible driver now builds its HTTP client via NewDriverHTTPClient() instead of an inline &http.Client{Transport: &http.Transport{...}} block. 58 constructors updated. The helper clones http.DefaultTransport (inheriting HTTP_PROXY/HTTPS_PROXY/NO_PROXY) and applies the standard pool settings (MaxIdleConns=100, MaxIdleConnsPerHost=10, IdleConnTimeout=90s, DisableCompression=false, ResponseHeaderTimeout=60s), so the previous per-file boilerplate — including a few drivers with inverted pool values (302ai, baidu, openrouter, paddleocr_local, xunfei) or missing ResponseHeaderTimeout (xai) — is now standardized. Drivers that carried a redundant http.Client.Timeout (jina 90s, jiekouai 120s) drop it; each request is already bounded by context.WithTimeout. - "I suggest put this func in base_model.go" (sse_stream.go): ParseSSEStream moved into base_model.go and sse_stream.go deleted. builtin.go is intentionally left untouched: its client uses a deliberate 30s overall Timeout and 10s ResponseHeaderTimeout for the local TEI server (documented), does not embed BaseModel, and is not one of the OpenAI-compatible drivers this boilerplate targeted. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
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 (6)
internal/entity/models/aliyun.go (1)
230-260:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winNil pointer dereference:
chatModelConfigaccessed without nil check.
ChatStreamlyWithSenderaccesseschatModelConfig.Stream,chatModelConfig.MaxTokens, etc. without first checking ifchatModelConfigis nil. If a caller passesnil, this will panic. Compare withChatWithMessages(line 88) which wraps the entire block inif chatModelConfig != nil.🐛 Proposed fix
- if chatModelConfig.Stream != nil { - reqBody["stream"] = *chatModelConfig.Stream - } - - if chatModelConfig.MaxTokens != nil { + if chatModelConfig != nil { + if chatModelConfig.Stream != nil { + reqBody["stream"] = *chatModelConfig.Stream + } + + if chatModelConfig.MaxTokens != nil { ... + }Wrap lines 230-260 in
if chatModelConfig != nil { ... }to match the pattern used inChatWithMessages.🤖 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/aliyun.go` around lines 230 - 260, The block in ChatStreamlyWithSender that dereferences chatModelConfig (accessing Stream, MaxTokens, Temperature, DoSample, TopP, Stop, Thinking) must be guarded against nil like ChatWithMessages; wrap the entire series of if checks in a single if chatModelConfig != nil { ... } so you only access chatModelConfig fields when it's non-nil, preserving the existing behavior for each field (including setting enable_thinking based on Thinking).internal/entity/models/azure_openai.go (1)
243-246:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMissing timeout on streaming request.
This streaming request uses
context.Background()without a timeout, unlike other drivers (302ai, aliyun, baidu) which usecontext.WithTimeout(context.Background(), streamCallTimeout). SinceNewDriverHTTPClient()doesn't set a client-levelTimeout, this request has no overall deadline and could hang indefinitely.🛡️ Proposed fix
- req, err := http.NewRequestWithContext(context.Background(), "POST", url, bytes.NewBuffer(jsonData)) + ctx, cancel := context.WithTimeout(context.Background(), streamCallTimeout) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))🤖 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/azure_openai.go` around lines 243 - 246, The streaming request currently uses context.Background() when calling http.NewRequestWithContext which leaves no timeout; change it to create a context with timeout using context.WithTimeout(context.Background(), streamCallTimeout), use that timed context when building the request, and ensure you call the returned cancel function (defer cancel()) so the deadline is enforced; reference the request creation site (http.NewRequestWithContext(...)) and the streamCallTimeout constant so the behavior matches the other drivers and compensates for NewDriverHTTPClient() not setting a client-level Timeout.internal/entity/models/volcengine.go (1)
251-311:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winNil pointer dereference risks in
ChatStreamlyWithSender.Two issues in this config-handling block:
Line 251+:
modelConfigis dereferenced without a nil guard. If the caller passesnilformodelConfig, accessingmodelConfig.Streamwill panic. Compare withChatWithMessages(line 87) which correctly wraps inif chatModelConfig != nil.Line 279:
*modelConfig.Effortis dereferenced unconditionally inside theThinkingblock. IfEffortis nil, this will panic. The non-streaming path (lines 108-130 inChatWithMessages) has a defaulteffort := "medium"fallback that protects against this.Proposed fix
+ if modelConfig == nil { + modelConfig = &ChatConfig{} + } + if modelConfig.Stream != nil { reqBody["stream"] = *modelConfig.Stream } // ... other field checks ... // TODO VolcEngine has `auto` mode if modelConfig.Thinking != nil { if *modelConfig.Thinking { var thinkingFlag string + effort := "medium" + if modelConfig.Effort != nil { + effort = *modelConfig.Effort + } - switch *modelConfig.Effort { + switch effort { case "none", "minimal":🤖 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/volcengine.go` around lines 251 - 311, In ChatStreamlyWithSender, guard against nil modelConfig before dereferencing its fields (e.g., check if modelConfig == nil then skip setting stream/max_tokens/etc. or initialize a default struct), and inside the Thinking handling use a safe effort value instead of unconditionally dereferencing modelConfig.Effort (e.g., set effort := "medium"; if modelConfig.Effort != nil { effort = *modelConfig.Effort } then switch on effort to set reasoning_effort and thinkingFlag). Update references in the block that currently read modelConfig.Stream, modelConfig.Effort, and modelConfig.Thinking accordingly so no field is dereferenced without a nil check.internal/entity/models/upstage.go (1)
232-232:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winMissing timeout for streaming request.
Same issue as TokenPony: the streaming request uses
context.Background()without a timeout, unlike TogetherAI which usesstreamCallTimeout. This could leave the request hanging indefinitely.Proposed fix
- req, err := http.NewRequestWithContext(context.Background(), "POST", url, bytes.NewBuffer(jsonData)) + ctx, cancel := context.WithTimeout(context.Background(), streamCallTimeout) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))🤖 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/upstage.go` at line 232, Replace the use of context.Background() in the http.NewRequestWithContext call with a cancellable context that applies the existing streamCallTimeout (e.g., ctx, cancel := context.WithTimeout(context.Background(), streamCallTimeout); defer cancel()). Update the call to use ctx so the streaming HTTP request respects streamCallTimeout and ensure cancel() is deferred to free resources.internal/entity/models/tokenpony.go (1)
220-220:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winMissing timeout for streaming request.
The streaming request uses
context.Background()without a timeout, unlike the other drivers in this batch (e.g., TogetherAI at line 224) which usestreamCallTimeout. This could leave the request hanging indefinitely if the server never responds or the connection stalls.Proposed fix
- req, err := http.NewRequestWithContext(context.Background(), "POST", url, bytes.NewBuffer(jsonData)) + ctx, cancel := context.WithTimeout(context.Background(), streamCallTimeout) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))🤖 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/tokenpony.go` at line 220, Replace the use of context.Background() when building the streaming HTTP request with a cancellable timeout context: create a ctx using context.WithTimeout(context.Background(), streamCallTimeout), pass that ctx into http.NewRequestWithContext (the line creating req), and defer the cancel() to ensure the request is bounded by streamCallTimeout; update the request creation in tokenpony.go accordingly so the streaming request cannot hang indefinitely.internal/entity/models/tokenhub.go (1)
273-315:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winMissing stream termination validation.
Unlike the TogetherAI and TokenPony drivers in this batch, TokenHub doesn't track
finish_reasonor validate thedonereturn value fromParseSSEStream. The method unconditionally sends[DONE]even if the stream ended prematurely without a[DONE]sentinel or terminalfinish_reason.For consistency and reliability, consider adding termination validation:
Proposed fix
+ sawTerminal := false - if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { + done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { choices, ok := event["choices"].([]interface{}) if !ok || len(choices) == 0 { return nil } firstChoice, ok := choices[0].(map[string]interface{}) if !ok { return nil } delta, ok := firstChoice["delta"].(map[string]interface{}) if !ok { return nil } reasoningContent, ok := delta["reasoning_content"].(string) if !ok || reasoningContent == "" { reasoningContent, _ = delta["reasoning"].(string) } if reasoningContent != "" { if err := sender(nil, &reasoningContent); err != nil { return err } } content, ok := delta["content"].(string) if ok && content != "" { if err := sender(&content, nil); err != nil { return err } } + if fr, ok := firstChoice["finish_reason"].(string); ok && fr != "" { + sawTerminal = true + } return nil }); err != nil { return fmt.Errorf("failed to scan response body: %w", err) } + if !done && !sawTerminal { + return fmt.Errorf("tokenhub: stream ended before [DONE] or finish_reason") + } // Send [DONE] marker for OpenAI compatibility endOfStream := "[DONE]" return sender(&endOfStream, nil)🤖 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/tokenhub.go` around lines 273 - 315, ParseSSEStream's returned "done" flag and the per-event "finish_reason" are not being checked in the TokenHub stream handling, so the code always emits the "[DONE]" sentinel even if the stream ended prematurely; modify the ParseSSEStream call in the TokenHub handler to capture both the returned done boolean and error (e.g., done, err := ParseSSEStream[...](...)), inspect each event's choices[*].finish_reason (treat "stop" or equivalent terminal reasons as terminal), and only send the endOfStream "[DONE]" via sender when the stream was confirmed finished (done == true or a terminal finish_reason was observed); if the stream ended without a terminal signal, return an error instead of unconditionally sending "[DONE]".
🧹 Nitpick comments (8)
internal/entity/models/huggingface.go (1)
289-328: 💤 Low valueConsider adding terminal-state validation for consistency with other drivers.
The
donereturn value fromParseSSEStreamis discarded. If the upstream terminates abnormally (no[DONE]sentinel and nofinish_reason), this code silently proceeds to send[DONE]to the client anyway. Other drivers in this batch (hunyuan, localai, longcat) check!done && !sawTerminaland return an error in that case.If this is intentional for HuggingFace compatibility, it's fine. Otherwise, consider aligning with the stricter pattern:
sawTerminal := false done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { // ... existing callback, plus: if finish, ok := firstChoice["finish_reason"].(string); ok && finish != "" { sawTerminal = true } return nil }) if err != nil { return fmt.Errorf("failed to scan response body: %w", err) } if !done && !sawTerminal { return fmt.Errorf("huggingface: stream ended before [DONE] or finish_reason") }🤖 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/huggingface.go` around lines 289 - 328, Capture the boolean done returned by ParseSSEStream and track a sawTerminal flag inside its callback by inspecting firstChoice["finish_reason"] (string) and setting sawTerminal = true when present; after ParseSSEStream returns, if err != nil return it, then if !done && !sawTerminal return an error like "huggingface: stream ended before [DONE] or finish_reason" instead of unconditionally sending the "[DONE]" sentinel, otherwise call sender(&endOfStream, nil) as currently implemented (refer to ParseSSEStream, resp.Body, firstChoice, finish_reason, sender).internal/entity/models/jiekouai.go (1)
284-326: 💤 Low valueMissing terminal-state validation.
Similar to the HuggingFace driver, the
donereturn value is discarded. If the stream ends without[DONE]orfinish_reason, the code silently sends[DONE]to the client. Consider adding terminal validation for consistency with other drivers in this batch.🤖 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/jiekouai.go` around lines 284 - 326, The ParseSSEStream callback currently discards the terminal "done" signal and always sends an OpenAI-style "[DONE]" marker; update the code around ParseSSEStream and sender so you capture and check the boolean done value returned by ParseSSEStream (or detect a terminal finish by checking firstChoice["finish_reason"] when present) and only send endOfStream = "[DONE]" via sender if the stream actually terminated (done==true or a non-empty finish_reason); if the stream returns without a terminal indication, return an error instead of silently sending "[DONE]" to keep behavior consistent with the HuggingFace driver and avoid duplicate termination markers.internal/entity/models/lmstudio.go (1)
308-352: 💤 Low valueMissing terminal-state validation.
Same pattern as HuggingFace and JiekouAI - the
donereturn value is discarded. Consider adding terminal validation for consistency with hunyuan/localai/longcat drivers.🤖 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/lmstudio.go` around lines 308 - 352, Capture the boolean terminal indicator returned by ParseSSEStream instead of discarding it (change if _, err := ParseSSEStream... to done, err := ParseSSEStream...) and validate it after the call; if err != nil return it, and if done is false return a descriptive error (e.g., "stream closed without terminal state") to match the terminal-state checks used in hunyuan/localai/longcat drivers; keep sending the OpenAI-compatible endOfStream marker via sender only after verifying the terminal state.internal/entity/models/nvidia.go (1)
276-317: 💤 Low valueMissing terminal condition check for premature stream end.
Unlike other drivers in this batch (Mistral, ModelScope, Moonshot, N1N, OpenAI), this implementation discards the
donereturn value and doesn't trackfinish_reason. If the stream ends prematurely without[DONE]orfinish_reason, no error is returned.Consider adding terminal tracking for consistency:
♻️ Suggested fix
+ sawTerminal := false - if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { + done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { choices, ok := event["choices"].([]interface{}) if !ok || len(choices) == 0 { return nil } firstChoice, ok := choices[0].(map[string]interface{}) if !ok { return nil } delta, ok := firstChoice["delta"].(map[string]interface{}) if !ok { return nil } reasoningContent, ok := delta["reasoning_content"].(string) if ok && reasoningContent != "" { if err := sender(nil, &reasoningContent); err != nil { return err } } content, ok := delta["content"].(string) if ok && content != "" { if err := sender(&content, nil); err != nil { return err } } + if finishReason, ok := firstChoice["finish_reason"].(string); ok && finishReason != "" { + sawTerminal = true + } return nil - }); err != nil { + }) + if err != nil { return fmt.Errorf("failed to scan response body: %w", err) } + if !done && !sawTerminal { + return fmt.Errorf("nvidia: stream ended before [DONE] or finish_reason") + }🤖 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 276 - 317, The SSE parsing loop in ParseSSEStream currently ignores the parsed "done" flag and doesn't track "finish_reason", so premature stream termination without the "[DONE]" sentinel or a finish_reason isn't detected; update the ParseSSEStream callback (and surrounding logic) to capture and return the boolean done value from ParseSSEStream, track a finishReason local variable when delta["finish_reason"] (or equivalent) is present, and only send the final endOfStream "[DONE]" if done is true; if the stream ends with done==false and no finishReason, return an error indicating a premature end (adjust callers of ParseSSEStream and the sender invocation accordingly, referencing ParseSSEStream, sender, endOfStream, and finish_reason).internal/entity/models/openrouter.go (1)
293-337: 💤 Low valueMissing terminal condition check and verbose logging.
Two observations:
The
donereturn value is discarded and there's nofinish_reasontracking. If the stream ends prematurely, no error is returned (inconsistent with Mistral, ModelScope, Moonshot, N1N, OpenAI drivers).Line 294 logs every SSE event with
common.Info, which could be very verbose in production.♻️ Suggested fix for terminal check
+ sawTerminal := false - if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { + done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { common.Info(fmt.Sprintf("%v", event)) choices, ok := event["choices"].([]interface{}) if !ok || len(choices) == 0 { return nil } firstChoice, ok := choices[0].(map[string]interface{}) if !ok { return nil } delta, ok := firstChoice["delta"].(map[string]interface{}) if !ok { return nil } reasoningContent, ok := delta["reasoning"].(string) if ok && reasoningContent != "" { if err := sender(nil, &reasoningContent); err != nil { return err } } content, ok := delta["content"].(string) if ok && content != "" { if err := sender(&content, nil); err != nil { return err } } + if finishReason, ok := firstChoice["finish_reason"].(string); ok && finishReason != "" { + sawTerminal = true + } return nil - }); err != nil { + }) + if err != nil { return fmt.Errorf("failed to scan response body: %w", err) } + if !done && !sawTerminal { + return fmt.Errorf("openrouter: stream ended before [DONE] or finish_reason") + }🤖 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 293 - 337, The SSE loop currently ignores the boolean done returned from ParseSSEStream and logs every event at Info level; update the ParseSSEStream call to capture the returned (done, err) and inside the event handler inspect the finish reason (e.g., check firstChoice["finish_reason"] as a string) when done is true: if finish_reason indicates an error or is not "stop"/"completed" return a descriptive error, otherwise end the stream normally (call sender with "[DONE]" as before). Also change the noisy common.Info(fmt.Sprintf("%v", event)) to a lower verbosity (common.Debug or remove it) so production logs aren’t flooded; keep references to ParseSSEStream, sender, event, choices, firstChoice, delta, reasoningContent, content, and finish_reason to locate the changes.internal/entity/models/qiniu.go (1)
342-382: ⚡ Quick winMissing stream termination validation.
Unlike other drivers in this batch (Perplexity, PPIO, Siliconflow, StepFun), this implementation discards the
donereturn value and doesn't tracksawTerminal. If the Qiniu API prematurely closes the connection without sending[DONE]or afinish_reason, the method will still succeed, potentially masking truncated responses.Consider aligning with the pattern used elsewhere:
Suggested termination check
+ sawTerminal := false - if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { + done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { common.Info(fmt.Sprintf("%v", event)) choices, ok := event["choices"].([]interface{}) @@ + finishReason, ok := firstChoice["finish_reason"].(string) + if ok && finishReason != "" { + sawTerminal = true + } return nil }); err != nil { return fmt.Errorf("failed to scan response body: %w", err) } + if !done && !sawTerminal { + return fmt.Errorf("qiniu: stream ended before [DONE] or finish_reason") + }🤖 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/qiniu.go` around lines 342 - 382, ParseSSEStream's returned done value and the stream events aren't being validated for terminal markers, so update the qiniu streaming logic to track the ParseSSEStream(done) return and a sawTerminal bool (like other drivers): inside the ParseSSEStream callback (used in this file) detect terminal indicators (e.g., a choice with finish_reason or when ParseSSEStream signals done) and set sawTerminal = true; after ParseSSEStream completes, check both the returned done and sawTerminal and return an error if neither indicates a proper termination (i.e., treat as truncated); only send the final endOfStream "[DONE]" via sender if you did not already observe a terminal marker.internal/entity/models/stepfun.go (1)
511-519: 💤 Low valueConsider logging base64 decode failures.
When
base64.StdEncoding.DecodeStringfails, the error is silently discarded and the audio chunk is skipped. This could mask upstream API issues or data corruption without any visibility.Optional: Add debug logging
if event.Type == "speech.audio.delta" && event.Audio != "" { audioBytes, err := base64.StdEncoding.DecodeString(event.Audio) - if err == nil && len(audioBytes) > 0 { + if err != nil { + // Log but continue - partial audio delivery is better than failing entirely + common.Warn(fmt.Sprintf("stepfun: failed to decode audio chunk: %v", err)) + } else if len(audioBytes) > 0 { chunk := string(audioBytes)🤖 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/stepfun.go` around lines 511 - 519, The base64 decode error from base64.StdEncoding.DecodeString is currently ignored which drops audio silently; update the handler around the DecodeString call to check for err != nil and log the failure (including the error value and relevant event metadata such as event.Type and any event ID/timestamp or event.Audio length) before skipping sending, using the project logger (or the standard log package if no logger is available), and only call sender(&chunk, nil) when decoding succeeds and len(audioBytes) > 0; reference the DecodeString call and the sender(&chunk, nil) invocation to locate where this change should be made.internal/entity/models/togetherai.go (1)
754-777: 💤 Low valueAudioSpeechWithSender ignores stream termination status.
The
donereturn value fromParseSSEStreamis discarded. UnlikeChatStreamlyWithSender, this method doesn't verify the stream ended properly (either via[DONE]or a terminal event type). If the upstream closes the connection prematurely, callers won't be notified.Consider adding termination validation for consistency with the chat streaming path, or document why silent completion is acceptable for TTS streams.
🤖 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/togetherai.go` around lines 754 - 777, AudioSpeechWithSender is discarding the done value from ParseSSEStream; capture its (done, err) return and validate stream termination similarly to ChatStreamlyWithSender by ensuring the stream completed with a terminal event or received the "[DONE]" sentinel. Update the ParseSSEStream call in AudioSpeechWithSender to read both the done boolean and error (e.g., done, err := ParseSSEStream[...](...)) and if err != nil return it, and if done is false return a descriptive error indicating premature stream close so callers (and sender) are notified of incomplete TTS streams.
🤖 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/aliyun.go`:
- Around line 230-260: The block in ChatStreamlyWithSender that dereferences
chatModelConfig (accessing Stream, MaxTokens, Temperature, DoSample, TopP, Stop,
Thinking) must be guarded against nil like ChatWithMessages; wrap the entire
series of if checks in a single if chatModelConfig != nil { ... } so you only
access chatModelConfig fields when it's non-nil, preserving the existing
behavior for each field (including setting enable_thinking based on Thinking).
In `@internal/entity/models/azure_openai.go`:
- Around line 243-246: The streaming request currently uses context.Background()
when calling http.NewRequestWithContext which leaves no timeout; change it to
create a context with timeout using context.WithTimeout(context.Background(),
streamCallTimeout), use that timed context when building the request, and ensure
you call the returned cancel function (defer cancel()) so the deadline is
enforced; reference the request creation site (http.NewRequestWithContext(...))
and the streamCallTimeout constant so the behavior matches the other drivers and
compensates for NewDriverHTTPClient() not setting a client-level Timeout.
In `@internal/entity/models/tokenhub.go`:
- Around line 273-315: ParseSSEStream's returned "done" flag and the per-event
"finish_reason" are not being checked in the TokenHub stream handling, so the
code always emits the "[DONE]" sentinel even if the stream ended prematurely;
modify the ParseSSEStream call in the TokenHub handler to capture both the
returned done boolean and error (e.g., done, err := ParseSSEStream[...](...)),
inspect each event's choices[*].finish_reason (treat "stop" or equivalent
terminal reasons as terminal), and only send the endOfStream "[DONE]" via sender
when the stream was confirmed finished (done == true or a terminal finish_reason
was observed); if the stream ended without a terminal signal, return an error
instead of unconditionally sending "[DONE]".
In `@internal/entity/models/tokenpony.go`:
- Line 220: Replace the use of context.Background() when building the streaming
HTTP request with a cancellable timeout context: create a ctx using
context.WithTimeout(context.Background(), streamCallTimeout), pass that ctx into
http.NewRequestWithContext (the line creating req), and defer the cancel() to
ensure the request is bounded by streamCallTimeout; update the request creation
in tokenpony.go accordingly so the streaming request cannot hang indefinitely.
In `@internal/entity/models/upstage.go`:
- Line 232: Replace the use of context.Background() in the
http.NewRequestWithContext call with a cancellable context that applies the
existing streamCallTimeout (e.g., ctx, cancel :=
context.WithTimeout(context.Background(), streamCallTimeout); defer cancel()).
Update the call to use ctx so the streaming HTTP request respects
streamCallTimeout and ensure cancel() is deferred to free resources.
In `@internal/entity/models/volcengine.go`:
- Around line 251-311: In ChatStreamlyWithSender, guard against nil modelConfig
before dereferencing its fields (e.g., check if modelConfig == nil then skip
setting stream/max_tokens/etc. or initialize a default struct), and inside the
Thinking handling use a safe effort value instead of unconditionally
dereferencing modelConfig.Effort (e.g., set effort := "medium"; if
modelConfig.Effort != nil { effort = *modelConfig.Effort } then switch on effort
to set reasoning_effort and thinkingFlag). Update references in the block that
currently read modelConfig.Stream, modelConfig.Effort, and modelConfig.Thinking
accordingly so no field is dereferenced without a nil check.
---
Nitpick comments:
In `@internal/entity/models/huggingface.go`:
- Around line 289-328: Capture the boolean done returned by ParseSSEStream and
track a sawTerminal flag inside its callback by inspecting
firstChoice["finish_reason"] (string) and setting sawTerminal = true when
present; after ParseSSEStream returns, if err != nil return it, then if !done &&
!sawTerminal return an error like "huggingface: stream ended before [DONE] or
finish_reason" instead of unconditionally sending the "[DONE]" sentinel,
otherwise call sender(&endOfStream, nil) as currently implemented (refer to
ParseSSEStream, resp.Body, firstChoice, finish_reason, sender).
In `@internal/entity/models/jiekouai.go`:
- Around line 284-326: The ParseSSEStream callback currently discards the
terminal "done" signal and always sends an OpenAI-style "[DONE]" marker; update
the code around ParseSSEStream and sender so you capture and check the boolean
done value returned by ParseSSEStream (or detect a terminal finish by checking
firstChoice["finish_reason"] when present) and only send endOfStream = "[DONE]"
via sender if the stream actually terminated (done==true or a non-empty
finish_reason); if the stream returns without a terminal indication, return an
error instead of silently sending "[DONE]" to keep behavior consistent with the
HuggingFace driver and avoid duplicate termination markers.
In `@internal/entity/models/lmstudio.go`:
- Around line 308-352: Capture the boolean terminal indicator returned by
ParseSSEStream instead of discarding it (change if _, err := ParseSSEStream...
to done, err := ParseSSEStream...) and validate it after the call; if err != nil
return it, and if done is false return a descriptive error (e.g., "stream closed
without terminal state") to match the terminal-state checks used in
hunyuan/localai/longcat drivers; keep sending the OpenAI-compatible endOfStream
marker via sender only after verifying the terminal state.
In `@internal/entity/models/nvidia.go`:
- Around line 276-317: The SSE parsing loop in ParseSSEStream currently ignores
the parsed "done" flag and doesn't track "finish_reason", so premature stream
termination without the "[DONE]" sentinel or a finish_reason isn't detected;
update the ParseSSEStream callback (and surrounding logic) to capture and return
the boolean done value from ParseSSEStream, track a finishReason local variable
when delta["finish_reason"] (or equivalent) is present, and only send the final
endOfStream "[DONE]" if done is true; if the stream ends with done==false and no
finishReason, return an error indicating a premature end (adjust callers of
ParseSSEStream and the sender invocation accordingly, referencing
ParseSSEStream, sender, endOfStream, and finish_reason).
In `@internal/entity/models/openrouter.go`:
- Around line 293-337: The SSE loop currently ignores the boolean done returned
from ParseSSEStream and logs every event at Info level; update the
ParseSSEStream call to capture the returned (done, err) and inside the event
handler inspect the finish reason (e.g., check firstChoice["finish_reason"] as a
string) when done is true: if finish_reason indicates an error or is not
"stop"/"completed" return a descriptive error, otherwise end the stream normally
(call sender with "[DONE]" as before). Also change the noisy
common.Info(fmt.Sprintf("%v", event)) to a lower verbosity (common.Debug or
remove it) so production logs aren’t flooded; keep references to ParseSSEStream,
sender, event, choices, firstChoice, delta, reasoningContent, content, and
finish_reason to locate the changes.
In `@internal/entity/models/qiniu.go`:
- Around line 342-382: ParseSSEStream's returned done value and the stream
events aren't being validated for terminal markers, so update the qiniu
streaming logic to track the ParseSSEStream(done) return and a sawTerminal bool
(like other drivers): inside the ParseSSEStream callback (used in this file)
detect terminal indicators (e.g., a choice with finish_reason or when
ParseSSEStream signals done) and set sawTerminal = true; after ParseSSEStream
completes, check both the returned done and sawTerminal and return an error if
neither indicates a proper termination (i.e., treat as truncated); only send the
final endOfStream "[DONE]" via sender if you did not already observe a terminal
marker.
In `@internal/entity/models/stepfun.go`:
- Around line 511-519: The base64 decode error from
base64.StdEncoding.DecodeString is currently ignored which drops audio silently;
update the handler around the DecodeString call to check for err != nil and log
the failure (including the error value and relevant event metadata such as
event.Type and any event ID/timestamp or event.Audio length) before skipping
sending, using the project logger (or the standard log package if no logger is
available), and only call sender(&chunk, nil) when decoding succeeds and
len(audioBytes) > 0; reference the DecodeString call and the sender(&chunk, nil)
invocation to locate where this change should be made.
In `@internal/entity/models/togetherai.go`:
- Around line 754-777: AudioSpeechWithSender is discarding the done value from
ParseSSEStream; capture its (done, err) return and validate stream termination
similarly to ChatStreamlyWithSender by ensuring the stream completed with a
terminal event or received the "[DONE]" sentinel. Update the ParseSSEStream call
in AudioSpeechWithSender to read both the done boolean and error (e.g., done,
err := ParseSSEStream[...](...)) and if err != nil return it, and if done is
false return a descriptive error indicating premature stream close so callers
(and sender) are notified of incomplete TTS streams.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: cf961780-8af3-4880-910c-9a0757678bff
📒 Files selected for processing (59)
internal/entity/models/302ai.gointernal/entity/models/aliyun.gointernal/entity/models/anthropic.gointernal/entity/models/astraflow.gointernal/entity/models/azure_openai.gointernal/entity/models/baichuan.gointernal/entity/models/baidu.gointernal/entity/models/base_model.gointernal/entity/models/bedrock.gointernal/entity/models/cohere.gointernal/entity/models/cometapi.gointernal/entity/models/deepinfra.gointernal/entity/models/deepseek.gointernal/entity/models/fishaudio.gointernal/entity/models/futurmix.gointernal/entity/models/gitee.gointernal/entity/models/gpustack.gointernal/entity/models/groq.gointernal/entity/models/huaweicloud.gointernal/entity/models/huggingface.gointernal/entity/models/hunyuan.gointernal/entity/models/jiekouai.gointernal/entity/models/jina.gointernal/entity/models/lmstudio.gointernal/entity/models/localai.gointernal/entity/models/longcat.gointernal/entity/models/mineru.gointernal/entity/models/mineru_local.gointernal/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/nvidia.gointernal/entity/models/ollama.gointernal/entity/models/openai.gointernal/entity/models/openrouter.gointernal/entity/models/orcarouter.gointernal/entity/models/paddleocr.gointernal/entity/models/paddleocr_local.gointernal/entity/models/perplexity.gointernal/entity/models/ppio.gointernal/entity/models/qiniu.gointernal/entity/models/replicate.gointernal/entity/models/siliconflow.gointernal/entity/models/stepfun.gointernal/entity/models/togetherai.gointernal/entity/models/tokenhub.gointernal/entity/models/tokenpony.gointernal/entity/models/upstage.gointernal/entity/models/vllm.gointernal/entity/models/volcengine.gointernal/entity/models/voyage.gointernal/entity/models/xai.gointernal/entity/models/xiaomi.gointernal/entity/models/xinference.gointernal/entity/models/xunfei.gointernal/entity/models/zhipu-ai.go
🚧 Files skipped from review as they are similar to previous changes (12)
- internal/entity/models/fishaudio.go
- internal/entity/models/orcarouter.go
- internal/entity/models/zhipu-ai.go
- internal/entity/models/deepinfra.go
- internal/entity/models/cohere.go
- internal/entity/models/astraflow.go
- internal/entity/models/baichuan.go
- internal/entity/models/xiaomi.go
- internal/entity/models/vllm.go
- internal/entity/models/novita.go
- internal/entity/models/minimax.go
- internal/entity/models/huaweicloud.go
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
internal/entity/models/lmstudio.go (2)
242-264:⚠️ Potential issue | 🟠 Major | ⚡ Quick winNil pointer dereference risk on
modelConfig.The code accesses
modelConfig.Stream,modelConfig.MaxTokens, etc. without first checking ifmodelConfigis nil. UnlikeChatWithMessages(line 94) which guards withif modelConfig != nil, this streaming method directly dereferences.🐛 Proposed fix
- if modelConfig.Stream != nil { - reqBody["stream"] = *modelConfig.Stream - } - - if modelConfig.MaxTokens != nil { - reqBody["max_tokens"] = *modelConfig.MaxTokens - } - - if modelConfig.Temperature != nil { - reqBody["temperature"] = *modelConfig.Temperature - } - - if modelConfig.DoSample != nil { - reqBody["do_sample"] = *modelConfig.DoSample - } - - if modelConfig.TopP != nil { - reqBody["top_p"] = *modelConfig.TopP - } - - if modelConfig.Stop != nil { - reqBody["stop"] = *modelConfig.Stop - } - - if modelConfig.Thinking != nil { + if modelConfig != nil { + if modelConfig.Stream != nil { + reqBody["stream"] = *modelConfig.Stream + } + if modelConfig.MaxTokens != nil { + reqBody["max_tokens"] = *modelConfig.MaxTokens + } + if modelConfig.Temperature != nil { + reqBody["temperature"] = *modelConfig.Temperature + } + if modelConfig.DoSample != nil { + reqBody["do_sample"] = *modelConfig.DoSample + } + if modelConfig.TopP != nil { + reqBody["top_p"] = *modelConfig.TopP + } + if modelConfig.Stop != nil { + reqBody["stop"] = *modelConfig.Stop + } + if modelConfig.Thinking != nil {🤖 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/lmstudio.go` around lines 242 - 264, The code dereferences modelConfig (accessing modelConfig.Stream, MaxTokens, Temperature, DoSample, TopP, Stop) without checking for nil, which can panic; update the function containing this block to first guard with if modelConfig != nil (same pattern as ChatWithMessages) and only then copy fields into reqBody, or alternatively treat modelConfig as non-nil by validating/initializing it at the start of the function; ensure you reference the existing modelConfig variable and mirror the nil-check approach used in ChatWithMessages to prevent nil pointer dereference.
309-309:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winDebug logging should be removed from production code.
common.Info(fmt.Sprintf("%v", event))logs every SSE event, which adds noise to production logs and may leak sensitive content.🔧 Suggested fix
if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { - common.Info(fmt.Sprintf("%v", event)) - choices, ok := event["choices"].([]interface{})🤖 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/lmstudio.go` at line 309, Remove the noisy debug log that prints every SSE event (the call common.Info(fmt.Sprintf("%v", event))) from internal/entity/models/lmstudio.go; either delete the line or replace it with a safe, conditional debug-level log (e.g., common.Debug or guarded by a debug/verbose flag) that does not include raw event contents or that redacts sensitive fields before logging.internal/entity/models/orcarouter.go (1)
254-254:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winDebug logging should be removed from production code.
common.Info(fmt.Sprintf("%v", event))logs every SSE event, adding noise to production logs and potentially leaking sensitive content.🔧 Suggested fix
sawTerminal := false done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { - common.Info(fmt.Sprintf("%v", event)) - choices, ok := event["choices"].([]interface{})🤖 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/orcarouter.go` at line 254, Remove the unconditional info-level logging of SSE events by deleting the call common.Info(fmt.Sprintf("%v", event)) in orcarouter.go (or guard it behind a debug-level path); if preserving diagnostics is needed, change it to a debug-level log (e.g., common.Debug/Debugf) and ensure any sensitive fields from the event are redacted before logging. Locate the call where the SSE event is handled (the line with common.Info(fmt.Sprintf("%v", event))) and either remove it or replace it with a guarded/debug log that redacts sensitive content.
🧹 Nitpick comments (1)
internal/entity/models/302ai.go (1)
327-365: ⚡ Quick winMissing stream termination check for consistency with other drivers.
Unlike other migrated drivers in this PR (azure_openai, gpustack, perplexity, togetherai, xai), this implementation discards the
donereturn value fromParseSSEStreamand doesn't trackfinish_reason. This inconsistency could hide premature stream closure.Consider adding termination tracking for consistency:
🔧 Suggested fix
+ sawTerminal := false - if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { + done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { choices, ok := event["choices"].([]interface{}) if !ok || len(choices) == 0 { return nil } firstChoice, ok := choices[0].(map[string]interface{}) if !ok { return nil } delta, ok := firstChoice["delta"].(map[string]interface{}) if !ok { return nil } reasoningContent, ok := delta["reasoning_content"].(string) if ok && reasoningContent != "" { if err := sender(nil, &reasoningContent); err != nil { return err } } content, ok := delta["content"].(string) if ok && content != "" { if err := sender(&content, nil); err != nil { return err } } + if finishReason, ok := firstChoice["finish_reason"].(string); ok && finishReason != "" { + sawTerminal = true + } return nil - }); err != nil { + }) + if err != nil { return fmt.Errorf("failed to scan response body: %w", err) } + if !done && !sawTerminal { + return fmt.Errorf("302ai: stream ended before [DONE] or finish_reason") + }🤖 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/302ai.go` around lines 327 - 365, ParseSSEStream's boolean "done" return value is being ignored and the handler never tracks a finish_reason, so the stream may close prematurely without detection; change the call to capture the done bool (e.g., done, err := ParseSSEStream[map[string]interface{}](...)) and introduce a closed-over variable (e.g., finished bool) that the event callback sets when it sees a finish_reason (inspect firstChoice["finish_reason"] or delta["finish_reason"] and set finished = true when present/equals "stop" or non-empty); after ParseSSEStream returns, use the captured done/finished flag to decide whether to send the "[DONE]" marker (only send if not already finished) and/or return an error if the stream closed unexpectedly, ensuring you still propagate err as before and use the existing sender function to emit the end-of-stream marker when appropriate.
🤖 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/lmstudio.go`:
- Around line 531-537: The loop over result["data"] uses unsafe assertions and
can panic; change to safe type checks by first testing result["data"] with a
type assertion like data, ok := result["data"].([]interface{}) and return or
handle error if not ok, then for each item assert itemMap, ok :=
model.(map[string]interface{}) and idStr, ok := itemMap["id"].(string) before
appending to models (ListModelResponse{Name: idStr}); ensure you handle
missing/invalid entries (skip or log) rather than panicking.
In `@internal/entity/models/orcarouter.go`:
- Around line 441-447: The current loop does unsafe type assertions on
result["data"] and its elements and will panic on unexpected formats; update the
code that builds models (using ListModelResponse, result, models, modelMap,
modelName) to perform guarded type assertions (use the "value, ok" form) for
result["data"] as []interface{} and for each element as map[string]interface{},
check that the "id" field exists and is a string before using it, and either
skip invalid entries or return an error so the function fails gracefully instead
of panicking.
---
Outside diff comments:
In `@internal/entity/models/lmstudio.go`:
- Around line 242-264: The code dereferences modelConfig (accessing
modelConfig.Stream, MaxTokens, Temperature, DoSample, TopP, Stop) without
checking for nil, which can panic; update the function containing this block to
first guard with if modelConfig != nil (same pattern as ChatWithMessages) and
only then copy fields into reqBody, or alternatively treat modelConfig as
non-nil by validating/initializing it at the start of the function; ensure you
reference the existing modelConfig variable and mirror the nil-check approach
used in ChatWithMessages to prevent nil pointer dereference.
- Line 309: Remove the noisy debug log that prints every SSE event (the call
common.Info(fmt.Sprintf("%v", event))) from internal/entity/models/lmstudio.go;
either delete the line or replace it with a safe, conditional debug-level log
(e.g., common.Debug or guarded by a debug/verbose flag) that does not include
raw event contents or that redacts sensitive fields before logging.
In `@internal/entity/models/orcarouter.go`:
- Line 254: Remove the unconditional info-level logging of SSE events by
deleting the call common.Info(fmt.Sprintf("%v", event)) in orcarouter.go (or
guard it behind a debug-level path); if preserving diagnostics is needed, change
it to a debug-level log (e.g., common.Debug/Debugf) and ensure any sensitive
fields from the event are redacted before logging. Locate the call where the SSE
event is handled (the line with common.Info(fmt.Sprintf("%v", event))) and
either remove it or replace it with a guarded/debug log that redacts sensitive
content.
---
Nitpick comments:
In `@internal/entity/models/302ai.go`:
- Around line 327-365: ParseSSEStream's boolean "done" return value is being
ignored and the handler never tracks a finish_reason, so the stream may close
prematurely without detection; change the call to capture the done bool (e.g.,
done, err := ParseSSEStream[map[string]interface{}](...)) and introduce a
closed-over variable (e.g., finished bool) that the event callback sets when it
sees a finish_reason (inspect firstChoice["finish_reason"] or
delta["finish_reason"] and set finished = true when present/equals "stop" or
non-empty); after ParseSSEStream returns, use the captured done/finished flag to
decide whether to send the "[DONE]" marker (only send if not already finished)
and/or return an error if the stream closed unexpectedly, ensuring you still
propagate err as before and use the existing sender function to emit the
end-of-stream marker when appropriate.
🪄 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
Run ID: c5206ca2-f454-40aa-8bda-239ac7803613
📒 Files selected for processing (59)
internal/entity/models/302ai.gointernal/entity/models/aliyun.gointernal/entity/models/anthropic.gointernal/entity/models/astraflow.gointernal/entity/models/avian.gointernal/entity/models/azure_openai.gointernal/entity/models/baichuan.gointernal/entity/models/baidu.gointernal/entity/models/bedrock.gointernal/entity/models/cohere.gointernal/entity/models/cometapi.gointernal/entity/models/deepinfra.gointernal/entity/models/deepseek.gointernal/entity/models/fishaudio.gointernal/entity/models/futurmix.gointernal/entity/models/gitee.gointernal/entity/models/gpustack.gointernal/entity/models/groq.gointernal/entity/models/huaweicloud.gointernal/entity/models/huggingface.gointernal/entity/models/hunyuan.gointernal/entity/models/jiekouai.gointernal/entity/models/jina.gointernal/entity/models/lmstudio.gointernal/entity/models/localai.gointernal/entity/models/longcat.gointernal/entity/models/mineru.gointernal/entity/models/mineru_local.gointernal/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/nvidia.gointernal/entity/models/ollama.gointernal/entity/models/openai.gointernal/entity/models/openrouter.gointernal/entity/models/orcarouter.gointernal/entity/models/paddleocr.gointernal/entity/models/paddleocr_local.gointernal/entity/models/perplexity.gointernal/entity/models/ppio.gointernal/entity/models/qiniu.gointernal/entity/models/replicate.gointernal/entity/models/siliconflow.gointernal/entity/models/stepfun.gointernal/entity/models/togetherai.gointernal/entity/models/tokenhub.gointernal/entity/models/tokenpony.gointernal/entity/models/upstage.gointernal/entity/models/vllm.gointernal/entity/models/volcengine.gointernal/entity/models/voyage.gointernal/entity/models/xai.gointernal/entity/models/xiaomi.gointernal/entity/models/xinference.gointernal/entity/models/xunfei.gointernal/entity/models/zhipu-ai.go
🚧 Files skipped from review as they are similar to previous changes (51)
- internal/entity/models/paddleocr.go
- internal/entity/models/bedrock.go
- internal/entity/models/ollama.go
- internal/entity/models/mineru.go
- internal/entity/models/jina.go
- internal/entity/models/futurmix.go
- internal/entity/models/anthropic.go
- internal/entity/models/voyage.go
- internal/entity/models/qiniu.go
- internal/entity/models/novita.go
- internal/entity/models/replicate.go
- internal/entity/models/jiekouai.go
- internal/entity/models/aliyun.go
- internal/entity/models/paddleocr_local.go
- internal/entity/models/xinference.go
- internal/entity/models/mineru_local.go
- internal/entity/models/mistral.go
- internal/entity/models/avian.go
- internal/entity/models/astraflow.go
- internal/entity/models/groq.go
- internal/entity/models/cohere.go
- internal/entity/models/tokenpony.go
- internal/entity/models/n1n.go
- internal/entity/models/volcengine.go
- internal/entity/models/deepseek.go
- internal/entity/models/modelscope.go
- internal/entity/models/gitee.go
- internal/entity/models/huaweicloud.go
- internal/entity/models/xunfei.go
- internal/entity/models/hunyuan.go
- internal/entity/models/upstage.go
- internal/entity/models/tokenhub.go
- internal/entity/models/openai.go
- internal/entity/models/xiaomi.go
- internal/entity/models/fishaudio.go
- internal/entity/models/stepfun.go
- internal/entity/models/deepinfra.go
- internal/entity/models/siliconflow.go
- internal/entity/models/huggingface.go
- internal/entity/models/ppio.go
- internal/entity/models/baichuan.go
- internal/entity/models/cometapi.go
- internal/entity/models/longcat.go
- internal/entity/models/nvidia.go
- internal/entity/models/baidu.go
- internal/entity/models/minimax.go
- internal/entity/models/zhipu-ai.go
- internal/entity/models/localai.go
- internal/entity/models/moonshot.go
- internal/entity/models/openrouter.go
- internal/entity/models/vllm.go
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
internal/entity/models/lmstudio.go (2)
242-264:⚠️ Potential issue | 🟠 Major | ⚡ Quick winNil pointer dereference risk on
modelConfig.The code accesses
modelConfig.Stream,modelConfig.MaxTokens, etc. without first checking ifmodelConfigis nil. UnlikeChatWithMessages(line 94) which guards withif modelConfig != nil, this streaming method directly dereferences.🐛 Proposed fix
- if modelConfig.Stream != nil { - reqBody["stream"] = *modelConfig.Stream - } - - if modelConfig.MaxTokens != nil { - reqBody["max_tokens"] = *modelConfig.MaxTokens - } - - if modelConfig.Temperature != nil { - reqBody["temperature"] = *modelConfig.Temperature - } - - if modelConfig.DoSample != nil { - reqBody["do_sample"] = *modelConfig.DoSample - } - - if modelConfig.TopP != nil { - reqBody["top_p"] = *modelConfig.TopP - } - - if modelConfig.Stop != nil { - reqBody["stop"] = *modelConfig.Stop - } - - if modelConfig.Thinking != nil { + if modelConfig != nil { + if modelConfig.Stream != nil { + reqBody["stream"] = *modelConfig.Stream + } + if modelConfig.MaxTokens != nil { + reqBody["max_tokens"] = *modelConfig.MaxTokens + } + if modelConfig.Temperature != nil { + reqBody["temperature"] = *modelConfig.Temperature + } + if modelConfig.DoSample != nil { + reqBody["do_sample"] = *modelConfig.DoSample + } + if modelConfig.TopP != nil { + reqBody["top_p"] = *modelConfig.TopP + } + if modelConfig.Stop != nil { + reqBody["stop"] = *modelConfig.Stop + } + if modelConfig.Thinking != nil {🤖 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/lmstudio.go` around lines 242 - 264, The code dereferences modelConfig (accessing modelConfig.Stream, MaxTokens, Temperature, DoSample, TopP, Stop) without checking for nil, which can panic; update the function containing this block to first guard with if modelConfig != nil (same pattern as ChatWithMessages) and only then copy fields into reqBody, or alternatively treat modelConfig as non-nil by validating/initializing it at the start of the function; ensure you reference the existing modelConfig variable and mirror the nil-check approach used in ChatWithMessages to prevent nil pointer dereference.
309-309:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winDebug logging should be removed from production code.
common.Info(fmt.Sprintf("%v", event))logs every SSE event, which adds noise to production logs and may leak sensitive content.🔧 Suggested fix
if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { - common.Info(fmt.Sprintf("%v", event)) - choices, ok := event["choices"].([]interface{})🤖 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/lmstudio.go` at line 309, Remove the noisy debug log that prints every SSE event (the call common.Info(fmt.Sprintf("%v", event))) from internal/entity/models/lmstudio.go; either delete the line or replace it with a safe, conditional debug-level log (e.g., common.Debug or guarded by a debug/verbose flag) that does not include raw event contents or that redacts sensitive fields before logging.internal/entity/models/orcarouter.go (1)
254-254:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winDebug logging should be removed from production code.
common.Info(fmt.Sprintf("%v", event))logs every SSE event, adding noise to production logs and potentially leaking sensitive content.🔧 Suggested fix
sawTerminal := false done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { - common.Info(fmt.Sprintf("%v", event)) - choices, ok := event["choices"].([]interface{})🤖 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/orcarouter.go` at line 254, Remove the unconditional info-level logging of SSE events by deleting the call common.Info(fmt.Sprintf("%v", event)) in orcarouter.go (or guard it behind a debug-level path); if preserving diagnostics is needed, change it to a debug-level log (e.g., common.Debug/Debugf) and ensure any sensitive fields from the event are redacted before logging. Locate the call where the SSE event is handled (the line with common.Info(fmt.Sprintf("%v", event))) and either remove it or replace it with a guarded/debug log that redacts sensitive content.
🧹 Nitpick comments (1)
internal/entity/models/302ai.go (1)
327-365: ⚡ Quick winMissing stream termination check for consistency with other drivers.
Unlike other migrated drivers in this PR (azure_openai, gpustack, perplexity, togetherai, xai), this implementation discards the
donereturn value fromParseSSEStreamand doesn't trackfinish_reason. This inconsistency could hide premature stream closure.Consider adding termination tracking for consistency:
🔧 Suggested fix
+ sawTerminal := false - if _, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { + done, err := ParseSSEStream[map[string]interface{}](resp.Body, func(event map[string]interface{}) error { choices, ok := event["choices"].([]interface{}) if !ok || len(choices) == 0 { return nil } firstChoice, ok := choices[0].(map[string]interface{}) if !ok { return nil } delta, ok := firstChoice["delta"].(map[string]interface{}) if !ok { return nil } reasoningContent, ok := delta["reasoning_content"].(string) if ok && reasoningContent != "" { if err := sender(nil, &reasoningContent); err != nil { return err } } content, ok := delta["content"].(string) if ok && content != "" { if err := sender(&content, nil); err != nil { return err } } + if finishReason, ok := firstChoice["finish_reason"].(string); ok && finishReason != "" { + sawTerminal = true + } return nil - }); err != nil { + }) + if err != nil { return fmt.Errorf("failed to scan response body: %w", err) } + if !done && !sawTerminal { + return fmt.Errorf("302ai: stream ended before [DONE] or finish_reason") + }🤖 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/302ai.go` around lines 327 - 365, ParseSSEStream's boolean "done" return value is being ignored and the handler never tracks a finish_reason, so the stream may close prematurely without detection; change the call to capture the done bool (e.g., done, err := ParseSSEStream[map[string]interface{}](...)) and introduce a closed-over variable (e.g., finished bool) that the event callback sets when it sees a finish_reason (inspect firstChoice["finish_reason"] or delta["finish_reason"] and set finished = true when present/equals "stop" or non-empty); after ParseSSEStream returns, use the captured done/finished flag to decide whether to send the "[DONE]" marker (only send if not already finished) and/or return an error if the stream closed unexpectedly, ensuring you still propagate err as before and use the existing sender function to emit the end-of-stream marker when appropriate.
🤖 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/lmstudio.go`:
- Around line 531-537: The loop over result["data"] uses unsafe assertions and
can panic; change to safe type checks by first testing result["data"] with a
type assertion like data, ok := result["data"].([]interface{}) and return or
handle error if not ok, then for each item assert itemMap, ok :=
model.(map[string]interface{}) and idStr, ok := itemMap["id"].(string) before
appending to models (ListModelResponse{Name: idStr}); ensure you handle
missing/invalid entries (skip or log) rather than panicking.
In `@internal/entity/models/orcarouter.go`:
- Around line 441-447: The current loop does unsafe type assertions on
result["data"] and its elements and will panic on unexpected formats; update the
code that builds models (using ListModelResponse, result, models, modelMap,
modelName) to perform guarded type assertions (use the "value, ok" form) for
result["data"] as []interface{} and for each element as map[string]interface{},
check that the "id" field exists and is a string before using it, and either
skip invalid entries or return an error so the function fails gracefully instead
of panicking.
---
Outside diff comments:
In `@internal/entity/models/lmstudio.go`:
- Around line 242-264: The code dereferences modelConfig (accessing
modelConfig.Stream, MaxTokens, Temperature, DoSample, TopP, Stop) without
checking for nil, which can panic; update the function containing this block to
first guard with if modelConfig != nil (same pattern as ChatWithMessages) and
only then copy fields into reqBody, or alternatively treat modelConfig as
non-nil by validating/initializing it at the start of the function; ensure you
reference the existing modelConfig variable and mirror the nil-check approach
used in ChatWithMessages to prevent nil pointer dereference.
- Line 309: Remove the noisy debug log that prints every SSE event (the call
common.Info(fmt.Sprintf("%v", event))) from internal/entity/models/lmstudio.go;
either delete the line or replace it with a safe, conditional debug-level log
(e.g., common.Debug or guarded by a debug/verbose flag) that does not include
raw event contents or that redacts sensitive fields before logging.
In `@internal/entity/models/orcarouter.go`:
- Line 254: Remove the unconditional info-level logging of SSE events by
deleting the call common.Info(fmt.Sprintf("%v", event)) in orcarouter.go (or
guard it behind a debug-level path); if preserving diagnostics is needed, change
it to a debug-level log (e.g., common.Debug/Debugf) and ensure any sensitive
fields from the event are redacted before logging. Locate the call where the SSE
event is handled (the line with common.Info(fmt.Sprintf("%v", event))) and
either remove it or replace it with a guarded/debug log that redacts sensitive
content.
---
Nitpick comments:
In `@internal/entity/models/302ai.go`:
- Around line 327-365: ParseSSEStream's boolean "done" return value is being
ignored and the handler never tracks a finish_reason, so the stream may close
prematurely without detection; change the call to capture the done bool (e.g.,
done, err := ParseSSEStream[map[string]interface{}](...)) and introduce a
closed-over variable (e.g., finished bool) that the event callback sets when it
sees a finish_reason (inspect firstChoice["finish_reason"] or
delta["finish_reason"] and set finished = true when present/equals "stop" or
non-empty); after ParseSSEStream returns, use the captured done/finished flag to
decide whether to send the "[DONE]" marker (only send if not already finished)
and/or return an error if the stream closed unexpectedly, ensuring you still
propagate err as before and use the existing sender function to emit the
end-of-stream marker when appropriate.
🪄 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
Run ID: c5206ca2-f454-40aa-8bda-239ac7803613
📒 Files selected for processing (59)
internal/entity/models/302ai.gointernal/entity/models/aliyun.gointernal/entity/models/anthropic.gointernal/entity/models/astraflow.gointernal/entity/models/avian.gointernal/entity/models/azure_openai.gointernal/entity/models/baichuan.gointernal/entity/models/baidu.gointernal/entity/models/bedrock.gointernal/entity/models/cohere.gointernal/entity/models/cometapi.gointernal/entity/models/deepinfra.gointernal/entity/models/deepseek.gointernal/entity/models/fishaudio.gointernal/entity/models/futurmix.gointernal/entity/models/gitee.gointernal/entity/models/gpustack.gointernal/entity/models/groq.gointernal/entity/models/huaweicloud.gointernal/entity/models/huggingface.gointernal/entity/models/hunyuan.gointernal/entity/models/jiekouai.gointernal/entity/models/jina.gointernal/entity/models/lmstudio.gointernal/entity/models/localai.gointernal/entity/models/longcat.gointernal/entity/models/mineru.gointernal/entity/models/mineru_local.gointernal/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/nvidia.gointernal/entity/models/ollama.gointernal/entity/models/openai.gointernal/entity/models/openrouter.gointernal/entity/models/orcarouter.gointernal/entity/models/paddleocr.gointernal/entity/models/paddleocr_local.gointernal/entity/models/perplexity.gointernal/entity/models/ppio.gointernal/entity/models/qiniu.gointernal/entity/models/replicate.gointernal/entity/models/siliconflow.gointernal/entity/models/stepfun.gointernal/entity/models/togetherai.gointernal/entity/models/tokenhub.gointernal/entity/models/tokenpony.gointernal/entity/models/upstage.gointernal/entity/models/vllm.gointernal/entity/models/volcengine.gointernal/entity/models/voyage.gointernal/entity/models/xai.gointernal/entity/models/xiaomi.gointernal/entity/models/xinference.gointernal/entity/models/xunfei.gointernal/entity/models/zhipu-ai.go
🚧 Files skipped from review as they are similar to previous changes (51)
- internal/entity/models/paddleocr.go
- internal/entity/models/bedrock.go
- internal/entity/models/ollama.go
- internal/entity/models/mineru.go
- internal/entity/models/jina.go
- internal/entity/models/futurmix.go
- internal/entity/models/anthropic.go
- internal/entity/models/voyage.go
- internal/entity/models/qiniu.go
- internal/entity/models/novita.go
- internal/entity/models/replicate.go
- internal/entity/models/jiekouai.go
- internal/entity/models/aliyun.go
- internal/entity/models/paddleocr_local.go
- internal/entity/models/xinference.go
- internal/entity/models/mineru_local.go
- internal/entity/models/mistral.go
- internal/entity/models/avian.go
- internal/entity/models/astraflow.go
- internal/entity/models/groq.go
- internal/entity/models/cohere.go
- internal/entity/models/tokenpony.go
- internal/entity/models/n1n.go
- internal/entity/models/volcengine.go
- internal/entity/models/deepseek.go
- internal/entity/models/modelscope.go
- internal/entity/models/gitee.go
- internal/entity/models/huaweicloud.go
- internal/entity/models/xunfei.go
- internal/entity/models/hunyuan.go
- internal/entity/models/upstage.go
- internal/entity/models/tokenhub.go
- internal/entity/models/openai.go
- internal/entity/models/xiaomi.go
- internal/entity/models/fishaudio.go
- internal/entity/models/stepfun.go
- internal/entity/models/deepinfra.go
- internal/entity/models/siliconflow.go
- internal/entity/models/huggingface.go
- internal/entity/models/ppio.go
- internal/entity/models/baichuan.go
- internal/entity/models/cometapi.go
- internal/entity/models/longcat.go
- internal/entity/models/nvidia.go
- internal/entity/models/baidu.go
- internal/entity/models/minimax.go
- internal/entity/models/zhipu-ai.go
- internal/entity/models/localai.go
- internal/entity/models/moonshot.go
- internal/entity/models/openrouter.go
- internal/entity/models/vllm.go
🛑 Comments failed to post (2)
internal/entity/models/lmstudio.go (1)
531-537:
⚠️ Potential issue | 🟠 Major | ⚡ Quick winUnsafe type assertions will panic on unexpected response format.
The code uses direct type assertions without
okchecks onresult["data"].([]interface{})andmodelMap["id"].(string). If the API returns an unexpected format, this will panic.🐛 Proposed fix
// convert result["data"] 2 []map[string]interface{} models := make([]ListModelResponse, 0) - for _, model := range result["data"].([]interface{}) { - modelMap := model.(map[string]interface{}) - modelName := modelMap["id"].(string) + data, ok := result["data"].([]interface{}) + if !ok { + return nil, fmt.Errorf("invalid models list format") + } + for _, model := range data { + modelMap, ok := model.(map[string]interface{}) + if !ok { + continue + } + modelName, ok := modelMap["id"].(string) + if !ok { + continue + } models = append(models, ListModelResponse{Name: modelName}) }🤖 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/lmstudio.go` around lines 531 - 537, The loop over result["data"] uses unsafe assertions and can panic; change to safe type checks by first testing result["data"] with a type assertion like data, ok := result["data"].([]interface{}) and return or handle error if not ok, then for each item assert itemMap, ok := model.(map[string]interface{}) and idStr, ok := itemMap["id"].(string) before appending to models (ListModelResponse{Name: idStr}); ensure you handle missing/invalid entries (skip or log) rather than panicking.internal/entity/models/orcarouter.go (1)
441-447:
⚠️ Potential issue | 🟠 Major | ⚡ Quick winUnsafe type assertions will panic on unexpected response format.
Same issue as in lmstudio.go - direct type assertions without
okchecks.🐛 Proposed fix
// convert result["data"] to []map[string]interface{} models := make([]ListModelResponse, 0) - for _, model := range result["data"].([]interface{}) { - modelMap := model.(map[string]interface{}) - modelName := modelMap["id"].(string) + data, ok := result["data"].([]interface{}) + if !ok { + return nil, fmt.Errorf("invalid models list format") + } + for _, model := range data { + modelMap, ok := model.(map[string]interface{}) + if !ok { + continue + } + modelName, ok := modelMap["id"].(string) + if !ok { + continue + } models = append(models, ListModelResponse{Name: modelName}) }🤖 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/orcarouter.go` around lines 441 - 447, The current loop does unsafe type assertions on result["data"] and its elements and will panic on unexpected formats; update the code that builds models (using ListModelResponse, result, models, modelMap, modelName) to perform guarded type assertions (use the "value, ok" form) for result["data"] as []interface{} and for each element as map[string]interface{}, check that the "id" field exists and is a string before using it, and either skip invalid entries or return an error so the function fails gracefully instead of panicking.
0aab26a to
4ad2212
Compare
Introduce reusable helpers for the Go model-driver layer and apply them across
every OpenAI-compatible provider, removing ~1600 lines of per-file boilerplate.
- driver_http.go: add NewDriverHTTPClient(), which clones http.DefaultTransport
(inheriting HTTP_PROXY/HTTPS_PROXY/NO_PROXY) and applies the standard
connection-pool settings (MaxIdleConns=100, MaxIdleConnsPerHost=10,
IdleConnTimeout=90s, DisableCompression=false, ResponseHeaderTimeout=60s).
Also add PostJSONRequest and ReadErrorBody helpers.
- base_model.go: add the generic ParseSSEStream[T] helper for OpenAI-compatible
Server-Sent Events streams; returns (done, err) where done means the [DONE]
sentinel was seen.
- Every provider constructor now builds its client via NewDriverHTTPClient()
instead of an inline &http.Client{Transport: &http.Transport{...}} block. This
normalizes the few drivers that had inverted pool values (302ai, baidu,
openrouter, paddleocr_local, xunfei) or a missing ResponseHeaderTimeout (xai).
jina and jiekouai keep their explicit http.Client.Timeout (90s / 120s) by
overriding it on the shared client, because their methods issue requests
without a per-call context deadline.
- Every OpenAI-compatible streaming driver now uses ParseSSEStream instead of an
inline bufio.Scanner loop. ollama (NDJSON) and replicate (non-standard
multi-field SSE) are intentionally excluded; xunfei (WebSocket) and bedrock
(AWS event stream) do not use it.
- builtin.go is left as-is: its client has deliberate, documented timeouts for the
local TEI server and does not embed BaseModel.
4ad2212 to
2c1dfb9
Compare
|
Hi, @Haruko386, |
Removed extensive comments from the ParseSSEStream function.
Haruko386
left a comment
There was a problem hiding this comment.
@JPette1783 LGTM, but it still need my boss to review @JinHai-CN
Resolve the base_model.go conflict by keeping both new functions: this PR's ParseSSEStream helper and ParseListModel added on main by the infiniflow#15900 list-models refactor. Also fix a pre-existing main typo surfaced by the merge — gitee_test.go referenced the undefined DSModelList; corrected to ModelList, its actual type after the infiniflow#15900 rename.
|
Hi, @JinHai-CN, |
|
@JPette1783 I'm testing your code for now, when I 'm done, we will merge your code |
|
@JPette1783 pleased pull the latest code |
| func NewDriverHTTPClient() *http.Client { | ||
| var t *http.Transport | ||
| if dt, ok := http.DefaultTransport.(*http.Transport); ok { | ||
| t = dt.Clone() | ||
| } else { | ||
| t = &http.Transport{Proxy: http.ProxyFromEnvironment} | ||
| } | ||
| t.MaxIdleConns = 100 | ||
| t.MaxIdleConnsPerHost = 10 | ||
| t.IdleConnTimeout = 90 * time.Second | ||
| t.DisableCompression = false | ||
| t.ResponseHeaderTimeout = 60 * time.Second | ||
| return &http.Client{Transport: t} | ||
| } | ||
|
|
||
| // PostJSONRequest marshals body to JSON, creates a POST request to url using | ||
| // client, and sets the Content-Type header to application/json. If auth is | ||
| // non-empty it is set as the Authorization header verbatim (include the scheme, | ||
| // e.g. "Bearer sk-..."). | ||
| // | ||
| // The caller is responsible for closing resp.Body. | ||
| func PostJSONRequest(ctx context.Context, client *http.Client, url, auth string, body map[string]interface{}) (*http.Response, error) { | ||
| data, err := json.Marshal(body) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to marshal request: %w", err) | ||
| } | ||
| req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(data)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to create request: %w", err) | ||
| } | ||
| req.Header.Set("Content-Type", "application/json") | ||
| if auth != "" { | ||
| req.Header.Set("Authorization", auth) | ||
| } | ||
| return client.Do(req) | ||
| } | ||
|
|
||
| // ReadErrorBody reads all bytes from r and returns them as a string suitable | ||
| // for embedding in an error message. It never returns an error of its own; | ||
| // if reading fails it returns an empty string so the caller's error path stays | ||
| // simple. | ||
| func ReadErrorBody(r io.Reader) string { | ||
| b, _ := io.ReadAll(r) | ||
| return string(b) | ||
| } |
…el.go
Per review feedback ("put these in base_model.go"), consolidate the shared
driver utilities into base_model.go: NewDriverHTTPClient, PostJSONRequest, and
ReadErrorBody now live alongside ParseSSEStream. driver_http.go is removed.
|
Hi, @Haruko386, Updated |
Removed comments from NewDriverHTTPClient and PostJSONRequest functions to streamline code.
|
Thank you for your review @Haruko386! |
|
Hi, @JinHai-CN , Could you please review this PR? |
|
Thank you @JinHai-CN! |
What problem does this PR solve?
The Go model-driver layer () has ~38,700 lines across 109 files. Roughly 74% of that is boilerplate duplicated into every driver: identical HTTP client setup, the same 65-line SSE scanner loop, and 10-11 one-line "not supported" stub methods per driver. Any fix must be manually propagated to every file. Closes #15820.
This PR establishes the three shared utility files that form the foundation for incremental driver migration:
— shared HTTP infrastructure
**** — one canonical HTTP client constructor. Clones so proxy env-vars (, , ) and any process-wide transport customisation are inherited automatically. Replaces ~60 nearly-identical inline transport-setup blocks scattered across the driver layer.
**** — marshals a to JSON and POSTs it with an optional header. Replaces the repeated 10-line marshal//header pattern used in most non-streaming paths.
**** — reads a non-200 response body for inclusion in an error message without adding extra error-handling boilerplate in the caller.
— shared SSE parser
**** — the standard SSE scanner used by ~52 OpenAI-compatible drivers, extracted into a single reusable function. It handles buffer sizing (64 KB default / 1 MB max), prefix stripping, sentinel, and malformed-line skipping — matching every existing inline loop exactly. Drivers with non-standard transports (Xunfei WebSocket, Bedrock AWS event streams) are explicitly excluded.
— embeddable stub base
**** — an embeddable struct that satisfies the optional methods (, , , , , , , , , , ) with a error. Replaces the ~11 one-line stubs every driver currently repeats. Drivers that support an optional capability override the embedded method — Go promotion rules ensure the driver's own definition wins.
Proof-of-concept migration:
is migrated to demonstrate real-world usage:
The remaining ~60 drivers can be migrated incrementally in follow-up PRs using the same mechanical substitution.
Type of change