Skip to content

feat(models): add shared HTTP client, SSE parser, and stub helpers for Go model drivers - #15821

Merged
JinHai-CN merged 6 commits into
infiniflow:mainfrom
Lobster-0429:feat/go-model-driver-shared-utils
Jun 11, 2026
Merged

JinHai-CN merged 6 commits into
infiniflow:mainfrom
Lobster-0429:feat/go-model-driver-shared-utils

Conversation

@Lobster-0429

Copy link
Copy Markdown
Contributor

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:

  • replaces its inline transport setup (7 lines) with (1 line)
  • The 11 stub methods at the bottom (~30 lines) are replaced by embedding (1 field + 1 constructor line)
  • Net change: −37 lines, identical runtime behaviour

The remaining ~60 drivers can be migrated incrementally in follow-up PRs using the same mechanical substitution.


Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)
  • Documentation Update
  • Refactoring
  • Performance Improvement
  • Other (please describe):

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 8, 2026
@coderabbitai

coderabbitai Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds 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.

Changes

Shared Utilities

Layer / File(s) Summary
Shared HTTP client and SSE parser
internal/entity/models/driver_http.go, internal/entity/models/base_model.go
Introduces NewDriverHTTPClient, PostJSONRequest, ReadErrorBody, and ParseSSEStream[T] (SSE data: line scanner + per-event onEvent callback, returns done/err).

Provider migrations

Layer / File(s) Summary
All model drivers migrated
internal/entity/models/*.go
Every provider model constructor now uses NewDriverHTTPClient(); streaming methods (ChatStreamlyWithSender, TTS/ASR streamers) replace bufio.Scanner-based "data:" parsing with ParseSSEStream callbacks that extract choices[0].delta (reasoning/content) or provider-typed events and forward deltas to the sender; imports dropping bufio/time when no longer needed; unified done/finish_reason termination checks and error wrapping (failed to scan response body).

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • Haruko386

"🐰
I hopped through transports, cloned no more,
One client to rule them—pools and timeouts soar.
SSE lines once scanned with care,
Now parsed in streams with tidy flair.
Tokens hop out — hooray, encore!"

@Haruko386 Haruko386 added ci Continue Integration and removed 💞 feature Feature request, pull request that fullfill a new feature. ☯️ refactor Pull request that refactor/refine code labels Jun 9, 2026
@Haruko386
Haruko386 marked this pull request as draft June 9, 2026 01:32
@Haruko386
Haruko386 marked this pull request as ready for review June 9, 2026 01:32
@dosubot dosubot Bot added ☯️ refactor Pull request that refactor/refine code 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 9, 2026
@codecov

codecov Bot commented Jun 9, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (47fb462) to head (863bd33).
⚠️ Report is 9 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@JPette1783 do these changes

Comment on lines -357 to -399
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())
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Just keep it like this is ok

Comment thread internal/entity/models/avian.go Outdated
// AvianModel implements ModelDriver for Avian (https://api.avian.io/docs/).
type AvianModel struct {
baseModel BaseModel
UnimplementedModelDriver

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

no need UnimplementedModelDriver for now, we shall do model provider refactor internal

Comment on lines -38 to -44
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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

you delete http settting and not use another way to set it

Comment thread internal/entity/models/sse_stream.go Outdated
Comment on lines +42 to +63
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()
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

could you implement this in all provider and provide your test output in RAGFlow CLI ?

Lobster-0429 added a commit to Lobster-0429/ragflow that referenced this pull request Jun 9, 2026
… 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
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 9, 2026
@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Please review this again @Haruko386.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Caution

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

⚠️ Outside diff range comments (6)
internal/entity/models/qiniu.go (1)

350-389: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Missing termination tracking; premature stream end goes undetected.

Unlike other refactored drivers (longcat, openai, upstage), this implementation ignores the done return value and doesn't track sawTerminal. 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 | 🟠 Major

Handle premature SSE termination for 302ai stream

  • internal/entity/models/302ai.go’s ChatStreamlyWithSender discards the (done) return from ParseSSEStream and never tracks sawTerminal / checks finish_reason, then unconditionally sends a synthetic "[DONE]".
  • ParseSSEStream returns (done=false, err=nil) when the upstream reader exhausts without receiving the data: [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, while zhipu-ai.go follows 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 win

Nil pointer dereference: modelConfig accessed without nil check.

If modelConfig is nil, accessing modelConfig.Stream at line 250 will cause a panic. The non-streaming ChatWithMessages method (line 102) correctly wraps similar accesses in if 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 win

Nil pointer dereference: modelConfig accessed without nil check.

This method accesses modelConfig fields directly without verifying it's non-nil. If modelConfig is 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 win

Nil pointer dereference: chatModelConfig accessed without nil check.

Unlike ChatWithMessages (line 96), this method accesses chatModelConfig fields directly without first checking if it's nil. If chatModelConfig is 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 to ChatWithMessages.

🤖 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 win

Missing terminal condition tracking.

Unlike other drivers in this PR (cohere, cometapi, deepinfra, deepseek, futurmix, gitee), this implementation doesn't track finish_reason via sawTerminal and doesn't validate that the stream completed properly before sending [DONE].

If the server closes the connection prematurely (without sending [DONE] or a finish_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 value

TTS stream ignores done flag and doesn't send [DONE] marker.

Unlike readXiaomiASRStream (which sends [DONE] at line 611-612) and ChatStreamlyWithSender (lines 354-357), this function returns nil directly 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 win

Inconsistent stream termination validation compared to other drivers.

Unlike baichuan, ppio, siliconflow, and xai drivers which all check if !done && !sawTerminal to detect truncated streams, this implementation ignores the done return value and doesn't track finish_reason. If the provider terminates the stream unexpectedly (without [DONE] or finish_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 value

ASR stream also ignores done flag.

Same inconsistency as the chat streaming: readXiaomiASRStream ignores the done return 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

parseCometAPIStreamEvent is now unused.

This helper function is no longer called after migrating to ParseSSEStream with 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 value

Consider 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

📥 Commits

Reviewing files that changed from the base of the PR and between 34dab09 and c30dfcb.

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

Comment thread internal/entity/models/baidu.go Resolved
Comment on lines +295 to +296
_ = done
_ = sawTerminal

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Comment thread internal/entity/models/vllm.go Resolved
Comment thread internal/entity/models/zhipu-ai.go Resolved
@Lobster-0429
Lobster-0429 requested a review from Haruko386 June 9, 2026 05:43
@Haruko386

Copy link
Copy Markdown
Member

@JPette1783 fix the CI error first

@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @Haruko386 ,
I think this Ci failure is not related to my PR.
Could you please check this?

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi @JPette1783 plz do some changes

Comment thread internal/entity/models/driver_http.go Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Refactor this for all model provider

Comment thread internal/entity/models/sse_stream.go Outdated

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I suggest put this func in base_model.go

Lobster-0429 added a commit to Lobster-0429/ragflow that referenced this pull request Jun 9, 2026
…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]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (6)
internal/entity/models/aliyun.go (1)

230-260: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Nil pointer dereference: chatModelConfig accessed without nil check.

ChatStreamlyWithSender accesses chatModelConfig.Stream, chatModelConfig.MaxTokens, etc. without first checking if chatModelConfig is nil. If a caller passes nil, this will panic. Compare with ChatWithMessages (line 88) which wraps the entire block in if 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 in ChatWithMessages.

🤖 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 win

Missing timeout on streaming request.

This streaming request uses context.Background() without a timeout, unlike other drivers (302ai, aliyun, baidu) which use context.WithTimeout(context.Background(), streamCallTimeout). Since NewDriverHTTPClient() doesn't set a client-level Timeout, 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 win

Nil pointer dereference risks in ChatStreamlyWithSender.

Two issues in this config-handling block:

  1. Line 251+: modelConfig is dereferenced without a nil guard. If the caller passes nil for modelConfig, accessing modelConfig.Stream will panic. Compare with ChatWithMessages (line 87) which correctly wraps in if chatModelConfig != nil.

  2. Line 279: *modelConfig.Effort is dereferenced unconditionally inside the Thinking block. If Effort is nil, this will panic. The non-streaming path (lines 108-130 in ChatWithMessages) has a default effort := "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 win

Missing timeout for streaming request.

Same issue as TokenPony: the streaming request uses context.Background() without a timeout, unlike TogetherAI which uses streamCallTimeout. 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 win

Missing 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 use streamCallTimeout. 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 win

Missing stream termination validation.

Unlike the TogetherAI and TokenPony drivers in this batch, TokenHub doesn't track finish_reason or validate the done return value from ParseSSEStream. The method unconditionally sends [DONE] even if the stream ended prematurely without a [DONE] sentinel or terminal finish_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 value

Consider adding terminal-state validation for consistency with other drivers.

The done return value from ParseSSEStream is discarded. If the upstream terminates abnormally (no [DONE] sentinel and no finish_reason), this code silently proceeds to send [DONE] to the client anyway. Other drivers in this batch (hunyuan, localai, longcat) check !done && !sawTerminal and 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 value

Missing terminal-state validation.

Similar to the HuggingFace driver, the done return value is discarded. If the stream ends without [DONE] or finish_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 value

Missing terminal-state validation.

Same pattern as HuggingFace and JiekouAI - the done return 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 value

Missing terminal condition check for premature stream end.

Unlike other drivers in this batch (Mistral, ModelScope, Moonshot, N1N, OpenAI), this implementation discards the done return value and doesn't track finish_reason. If the stream ends prematurely without [DONE] or finish_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 value

Missing terminal condition check and verbose logging.

Two observations:

  1. The done return value is discarded and there's no finish_reason tracking. If the stream ends prematurely, no error is returned (inconsistent with Mistral, ModelScope, Moonshot, N1N, OpenAI drivers).

  2. 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 win

Missing stream termination validation.

Unlike other drivers in this batch (Perplexity, PPIO, Siliconflow, StepFun), this implementation discards the done return value and doesn't track sawTerminal. If the Qiniu API prematurely closes the connection without sending [DONE] or a finish_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 value

Consider logging base64 decode failures.

When base64.StdEncoding.DecodeString fails, 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 value

AudioSpeechWithSender ignores stream termination status.

The done return value from ParseSSEStream is discarded. Unlike ChatStreamlyWithSender, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 45a982e and fdb5795.

📒 Files selected for processing (59)
  • internal/entity/models/302ai.go
  • internal/entity/models/aliyun.go
  • internal/entity/models/anthropic.go
  • internal/entity/models/astraflow.go
  • internal/entity/models/azure_openai.go
  • internal/entity/models/baichuan.go
  • internal/entity/models/baidu.go
  • internal/entity/models/base_model.go
  • internal/entity/models/bedrock.go
  • internal/entity/models/cohere.go
  • internal/entity/models/cometapi.go
  • internal/entity/models/deepinfra.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/fishaudio.go
  • internal/entity/models/futurmix.go
  • internal/entity/models/gitee.go
  • internal/entity/models/gpustack.go
  • internal/entity/models/groq.go
  • internal/entity/models/huaweicloud.go
  • internal/entity/models/huggingface.go
  • internal/entity/models/hunyuan.go
  • internal/entity/models/jiekouai.go
  • internal/entity/models/jina.go
  • internal/entity/models/lmstudio.go
  • internal/entity/models/localai.go
  • internal/entity/models/longcat.go
  • internal/entity/models/mineru.go
  • internal/entity/models/mineru_local.go
  • internal/entity/models/minimax.go
  • internal/entity/models/mistral.go
  • internal/entity/models/modelscope.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/n1n.go
  • internal/entity/models/novita.go
  • internal/entity/models/nvidia.go
  • internal/entity/models/ollama.go
  • internal/entity/models/openai.go
  • internal/entity/models/openrouter.go
  • internal/entity/models/orcarouter.go
  • internal/entity/models/paddleocr.go
  • internal/entity/models/paddleocr_local.go
  • internal/entity/models/perplexity.go
  • internal/entity/models/ppio.go
  • internal/entity/models/qiniu.go
  • internal/entity/models/replicate.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/stepfun.go
  • internal/entity/models/togetherai.go
  • internal/entity/models/tokenhub.go
  • internal/entity/models/tokenpony.go
  • internal/entity/models/upstage.go
  • internal/entity/models/vllm.go
  • internal/entity/models/volcengine.go
  • internal/entity/models/voyage.go
  • internal/entity/models/xai.go
  • internal/entity/models/xiaomi.go
  • internal/entity/models/xinference.go
  • internal/entity/models/xunfei.go
  • internal/entity/models/zhipu-ai.go
🚧 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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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 win

Nil pointer dereference risk on modelConfig.

The code accesses modelConfig.Stream, modelConfig.MaxTokens, etc. without first checking if modelConfig is nil. Unlike ChatWithMessages (line 94) which guards with if 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 win

Debug 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 win

Debug 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 win

Missing 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 done return value from ParseSSEStream and doesn't track finish_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

📥 Commits

Reviewing files that changed from the base of the PR and between fdb5795 and 01e282c.

📒 Files selected for processing (59)
  • internal/entity/models/302ai.go
  • internal/entity/models/aliyun.go
  • internal/entity/models/anthropic.go
  • internal/entity/models/astraflow.go
  • internal/entity/models/avian.go
  • internal/entity/models/azure_openai.go
  • internal/entity/models/baichuan.go
  • internal/entity/models/baidu.go
  • internal/entity/models/bedrock.go
  • internal/entity/models/cohere.go
  • internal/entity/models/cometapi.go
  • internal/entity/models/deepinfra.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/fishaudio.go
  • internal/entity/models/futurmix.go
  • internal/entity/models/gitee.go
  • internal/entity/models/gpustack.go
  • internal/entity/models/groq.go
  • internal/entity/models/huaweicloud.go
  • internal/entity/models/huggingface.go
  • internal/entity/models/hunyuan.go
  • internal/entity/models/jiekouai.go
  • internal/entity/models/jina.go
  • internal/entity/models/lmstudio.go
  • internal/entity/models/localai.go
  • internal/entity/models/longcat.go
  • internal/entity/models/mineru.go
  • internal/entity/models/mineru_local.go
  • internal/entity/models/minimax.go
  • internal/entity/models/mistral.go
  • internal/entity/models/modelscope.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/n1n.go
  • internal/entity/models/novita.go
  • internal/entity/models/nvidia.go
  • internal/entity/models/ollama.go
  • internal/entity/models/openai.go
  • internal/entity/models/openrouter.go
  • internal/entity/models/orcarouter.go
  • internal/entity/models/paddleocr.go
  • internal/entity/models/paddleocr_local.go
  • internal/entity/models/perplexity.go
  • internal/entity/models/ppio.go
  • internal/entity/models/qiniu.go
  • internal/entity/models/replicate.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/stepfun.go
  • internal/entity/models/togetherai.go
  • internal/entity/models/tokenhub.go
  • internal/entity/models/tokenpony.go
  • internal/entity/models/upstage.go
  • internal/entity/models/vllm.go
  • internal/entity/models/volcengine.go
  • internal/entity/models/voyage.go
  • internal/entity/models/xai.go
  • internal/entity/models/xiaomi.go
  • internal/entity/models/xinference.go
  • internal/entity/models/xunfei.go
  • internal/entity/models/zhipu-ai.go
🚧 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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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 win

Nil pointer dereference risk on modelConfig.

The code accesses modelConfig.Stream, modelConfig.MaxTokens, etc. without first checking if modelConfig is nil. Unlike ChatWithMessages (line 94) which guards with if 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 win

Debug 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 win

Debug 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 win

Missing 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 done return value from ParseSSEStream and doesn't track finish_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

📥 Commits

Reviewing files that changed from the base of the PR and between fdb5795 and 01e282c.

📒 Files selected for processing (59)
  • internal/entity/models/302ai.go
  • internal/entity/models/aliyun.go
  • internal/entity/models/anthropic.go
  • internal/entity/models/astraflow.go
  • internal/entity/models/avian.go
  • internal/entity/models/azure_openai.go
  • internal/entity/models/baichuan.go
  • internal/entity/models/baidu.go
  • internal/entity/models/bedrock.go
  • internal/entity/models/cohere.go
  • internal/entity/models/cometapi.go
  • internal/entity/models/deepinfra.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/fishaudio.go
  • internal/entity/models/futurmix.go
  • internal/entity/models/gitee.go
  • internal/entity/models/gpustack.go
  • internal/entity/models/groq.go
  • internal/entity/models/huaweicloud.go
  • internal/entity/models/huggingface.go
  • internal/entity/models/hunyuan.go
  • internal/entity/models/jiekouai.go
  • internal/entity/models/jina.go
  • internal/entity/models/lmstudio.go
  • internal/entity/models/localai.go
  • internal/entity/models/longcat.go
  • internal/entity/models/mineru.go
  • internal/entity/models/mineru_local.go
  • internal/entity/models/minimax.go
  • internal/entity/models/mistral.go
  • internal/entity/models/modelscope.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/n1n.go
  • internal/entity/models/novita.go
  • internal/entity/models/nvidia.go
  • internal/entity/models/ollama.go
  • internal/entity/models/openai.go
  • internal/entity/models/openrouter.go
  • internal/entity/models/orcarouter.go
  • internal/entity/models/paddleocr.go
  • internal/entity/models/paddleocr_local.go
  • internal/entity/models/perplexity.go
  • internal/entity/models/ppio.go
  • internal/entity/models/qiniu.go
  • internal/entity/models/replicate.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/stepfun.go
  • internal/entity/models/togetherai.go
  • internal/entity/models/tokenhub.go
  • internal/entity/models/tokenpony.go
  • internal/entity/models/upstage.go
  • internal/entity/models/vllm.go
  • internal/entity/models/volcengine.go
  • internal/entity/models/voyage.go
  • internal/entity/models/xai.go
  • internal/entity/models/xiaomi.go
  • internal/entity/models/xinference.go
  • internal/entity/models/xunfei.go
  • internal/entity/models/zhipu-ai.go
🚧 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 win

Unsafe type assertions will panic on unexpected response format.

The code uses direct type assertions without ok checks on result["data"].([]interface{}) and modelMap["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 win

Unsafe type assertions will panic on unexpected response format.

Same issue as in lmstudio.go - direct type assertions without ok checks.

🐛 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.

@Lobster-0429
Lobster-0429 force-pushed the feat/go-model-driver-shared-utils branch 2 times, most recently from 0aab26a to 4ad2212 Compare June 9, 2026 15:15
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.
@Lobster-0429
Lobster-0429 force-pushed the feat/go-model-driver-shared-utils branch from 4ad2212 to 2c1dfb9 Compare June 9, 2026 15:22
@Lobster-0429
Lobster-0429 requested a review from Haruko386 June 9, 2026 15:27
@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @Haruko386,
Please review this PR.

Removed extensive comments from the ParseSSEStream function.

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@JPette1783 LGTM, but it still need my boss to review @JinHai-CN

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jun 10, 2026
@Haruko386
Haruko386 requested a review from JinHai-CN June 10, 2026 05:33
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.
@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @JinHai-CN,
Could you please review this PR?

@Haruko386

Haruko386 commented Jun 11, 2026 •

Copy link
Copy Markdown
Member

@JPette1783 I'm testing your code for now, when I 'm done, we will merge your code
please be patient

@Haruko386

Copy link
Copy Markdown
Member

@JPette1783 pleased pull the latest code

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@JPette1783

Comment thread internal/entity/models/driver_http.go Outdated
Comment on lines +36 to +80
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)
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

put these in base_model.go

@dosubot dosubot Bot removed the lgtm This PR has been approved by a maintainer label Jun 11, 2026
…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.
@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @Haruko386, Updated

Removed comments from NewDriverHTTPClient and PostJSONRequest functions to streamline code.

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@JPette1783 done
LGTM

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jun 11, 2026
@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Thank you for your review @Haruko386!
Please review this PR @JinHai-CN.

@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @JinHai-CN , Could you please review this PR?
All CI tests are successfully passed.

@JinHai-CN
JinHai-CN merged commit daa3811 into infiniflow:main Jun 11, 2026
1 check passed
@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Thank you @JinHai-CN!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. lgtm This PR has been approved by a maintainer ☯️ refactor Pull request that refactor/refine code size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Refactor Go model drivers — extract shared HTTP, SSE streaming, and capability stubs to eliminate

3 participants