Repository navigation
Refactor[Go Model Provider]: refactor baseURL and modelConfig - #15627
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAll provider drivers were refactored to embed BaseModel and delegate APIConfigCheck, GetBaseURL, URLSuffix usage, and HTTP calls to baseModel; BaseModel API key trimming and Region fallback logic were adjusted; tests updated to reference baseModel fields. ChangesUnified BaseModel integration across providers
Sequence Diagram(s)sequenceDiagram
autonumber
participant Driver as Provider Driver
participant BM as BaseModel
participant API as Upstream API
Driver->>BM: APIConfigCheck(apiConfig)
Driver->>BM: GetBaseURL(apiConfig)
Driver->>BM: Build URL with BM.URLSuffix
Driver->>BM: BM.httpClient.Do(req)
BM-->>API: HTTP request
API-->>BM: HTTP response / SSE
BM-->>Driver: Parsed/streamed result
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
|
There was a problem hiding this comment.
Actionable comments posted: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (23)
internal/entity/models/mistral.go (1)
654-704:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMissing API config validation before dereferencing
ApiKey.
OCRFiledereferences*apiConfig.ApiKeyon line 702 without first validatingapiConfigviabaseModel.APIConfigCheck. Other methods in this driver (e.g.,ChatWithMessages,Embed,ListModels) correctly validate first.🐛 Proposed fix
func (m *MistralModel) OCRFile(modelName *string, content []byte, urls *string, apiConfig *APIConfig, ocrConfig *OCRConfig) (*OCRFileResponse, error) { if (urls == nil || *urls == "") && (content == nil || len(content) == 0) { return nil, fmt.Errorf("file url or content is required") } + if err := m.baseModel.APIConfigCheck(apiConfig); err != nil { + return nil, err + } region := "default"🤖 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/mistral.go` around lines 654 - 704, The OCRFile method dereferences apiConfig.ApiKey without validating apiConfig first; call m.baseModel.APIConfigCheck(ctx, apiConfig) (or the non-ctx variant used elsewhere) near the start of OCRFile (before using apiConfig or *apiConfig.ApiKey) and handle/return any error it produces, and then use the validated/returned APIConfig for subsequent calls (e.g., when setting the Authorization header) to match how ChatWithMessages/Embed/ListModels perform API config validation.internal/entity/models/baichuan.go (2)
184-199:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMissing API config validation before dereferencing
ApiKey.
ChatStreamlyWithSenderdereferences*apiConfig.ApiKeyon line 253 without first validatingapiConfigviabaseModel.APIConfigCheck. IfapiConfigorapiConfig.ApiKeyis nil, this will panic.Other methods like
ChatWithMessagescorrectly callb.baseModel.APIConfigCheck(apiConfig)before use.🐛 Proposed fix
func (b *BaichuanModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, modelConfig *ChatConfig, sender func(*string, *string) error) error { if len(messages) == 0 { return fmt.Errorf("messages is empty") } + if err := b.baseModel.APIConfigCheck(apiConfig); err != nil { + return err + } var region = "default"Also applies to: 253-253
🤖 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/baichuan.go` around lines 184 - 199, The method BaichuanModel.ChatStreamlyWithSender dereferences apiConfig.ApiKey without first validating apiConfig; call b.baseModel.APIConfigCheck(apiConfig) at the start of ChatStreamlyWithSender (like ChatWithMessages does), return the error if non-nil, and only then safely dereference *apiConfig.ApiKey (or otherwise guard nil ApiKey) so the function cannot panic when apiConfig or apiConfig.ApiKey is nil.
329-344:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMissing API config validation before dereferencing
ApiKey.
Embeddereferences*apiConfig.ApiKeyon line 365 without first validatingapiConfigviabaseModel.APIConfigCheck. IfapiConfigorapiConfig.ApiKeyis nil, this will panic.🐛 Proposed fix
func (b *BaichuanModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) { if len(texts) == 0 { return []EmbeddingData{}, nil } + if err := b.baseModel.APIConfigCheck(apiConfig); err != nil { + return nil, err + } var region = "default"Also applies to: 365-365
🤖 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/baichuan.go` around lines 329 - 344, The Embed method dereferences apiConfig.ApiKey without ensuring apiConfig is valid; call b.baseModel.APIConfigCheck(apiConfig) (or otherwise validate apiConfig and apiConfig.ApiKey != nil) at the start of Embed before using *apiConfig.ApiKey, and return a clear error if the check fails; update the Embed implementation to perform this validation (referencing Embed, APIConfig, ApiKey and baseModel.APIConfigCheck) so no nil pointer dereference can occur.internal/entity/models/xunfei.go (2)
61-76:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMissing API config validation before dereferencing
ApiKey.
ChatWithMessagesdereferences*apiConfig.ApiKeyon line 137 without first validatingapiConfigviabaseModel.APIConfigCheck. IfapiConfigorapiConfig.ApiKeyis nil, this will panic.This issue also affects
ChatStreamlyWithSender(line 276) andListModels(line 421).🐛 Proposed fix for ChatWithMessages
func (x *XunFeiModel) ChatWithMessages(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig) (*ChatResponse, error) { + if err := x.baseModel.APIConfigCheck(apiConfig); err != nil { + return nil, err + } if len(messages) == 0 { return nil, fmt.Errorf("messages is empty") }🐛 Proposed fix for ChatStreamlyWithSender
func (x *XunFeiModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, modelConfig *ChatConfig, sender func(*string, *string) error) error { + if err := x.baseModel.APIConfigCheck(apiConfig); err != nil { + return err + } if len(messages) == 0 { return fmt.Errorf("messages is empty") }🐛 Proposed fix for ListModels
func (x *XunFeiModel) ListModels(apiConfig *APIConfig) ([]string, error) { + if err := x.baseModel.APIConfigCheck(apiConfig); err != nil { + return nil, err + } var region = "default"Also applies to: 137-137
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/xunfei.go` around lines 61 - 76, ChatWithMessages (and similarly ChatStreamlyWithSender and ListModels) currently dereference *apiConfig.ApiKey without validating apiConfig; call or reuse baseModel.APIConfigCheck(apiConfig) (or at minimum check apiConfig != nil && apiConfig.ApiKey != nil && *apiConfig.ApiKey != "") at the start of each function and return a clear error if the check fails before any dereference (e.g., before using *apiConfig.ApiKey or passing apiConfig into baseModel.GetBaseURL); update the code paths in ChatWithMessages, ChatStreamlyWithSender, and ListModels to perform this validation and early-return on invalid config.
444-450:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winUnchecked type assertions may cause panic on malformed response.
Lines 446-449 perform type assertions without checking the
okreturn value. If the API returns an unexpected response format (e.g.,datais not[]interface{}or a model entry lacksid), this will panic.🛡️ Proposed defensive fix
// convert result["data"] to []map[string]interface{} models := make([]string, 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, 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/xunfei.go` around lines 444 - 450, The loop unconditionally asserts types on result["data"] and model.(map[string]interface{})/["id"].(string) which can panic on malformed responses; update the code that builds models (the models slice, the loop over result["data"], and modelMap/modelName extraction) to first test type assertions using the comma-ok idiom (e.g., check result["data"] is []interface{}, each item is map[string]interface{}, and "id" exists and is string), skip or return a controlled error when checks fail, and log the unexpected shape instead of allowing a panic.internal/entity/models/302ai.go (1)
483-499:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winFix copy-paste error: error messages reference "Jina" instead of "302ai".
These error messages incorrectly reference "Jina" - likely a copy-paste artifact from another driver.
🐛 Proposed fix
if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("Jina embedding API error: status %d, body: %s", resp.StatusCode, string(body)) + return nil, fmt.Errorf("302.ai embedding API error: status %d, body: %s", resp.StatusCode, string(body)) } ... if len(parsedResponse.Data) == 0 { - return nil, fmt.Errorf("Jina embedding response contains no data: %s", string(body)) + return nil, fmt.Errorf("302.ai embedding response contains no data: %s", string(body)) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/302ai.go` around lines 483 - 499, The error messages in the 302ai embedding response handling incorrectly reference "Jina" (copy-paste relic); update the fmt.Errorf strings in the block that checks resp.StatusCode, json.Unmarshal failure, and empty parsedResponse.Data to say "302ai" (e.g., "302ai embedding API error: status %d, body: %s" and "302ai embedding response contains no data: %s") so the errors reference the correct provider; locate the messages near the variables resp.StatusCode, parsedResponse, and the json.Unmarshal error handling in this file and replace "Jina" with "302ai".internal/entity/models/xai.go (1)
622-631:⚠️ Potential issue | 🟠 Major | ⚡ Quick winRestore request deadlines for ASR and TTS.
Lines 622-631 and 705-713 create plain
http.NewRequestcalls, but this driver's sharedhttp.Clientintentionally has noTimeout. A stalled connection or slow body read can now block these methods indefinitely.Suggested fix
- req, err := http.NewRequest("POST", url, &body) + ctx, cancel := context.WithTimeout(context.Background(), longOpCallTimeout) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, "POST", url, &body)- req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) + ctx, cancel := context.WithTimeout(context.Background(), longOpCallTimeout) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData))Based on learnings: if
httpClient.Timeoutis intentionally unset, usingcontext.WithTimeoutper request is the legitimate overall deadline.Also applies to: 705-713
🤖 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/xai.go` around lines 622 - 631, The request creation uses http.NewRequest without a context deadline which can hang because x.baseModel.httpClient intentionally has no Timeout; wrap the request with a per-call context timeout (e.g., ctx, cancel := context.WithTimeout(ctx, timeout); defer cancel()) and create the request with http.NewRequestWithContext(ctx, "POST", url, &body), then proceed to set headers (Authorization using apiConfig.ApiKey and Content-Type from writer.FormDataContentType()) and call x.baseModel.httpClient.Do(req); apply the same change to the other request site around the x.baseModel.httpClient.Do call (the block at 705-713) so both ASR and TTS requests use per-request contexts and cancellations.internal/entity/models/togetherai.go (2)
499-539:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMissing
APIConfigCheckinRerankmethod.Unlike other methods (
ChatWithMessages,ListModels,Embed,TranscribeAudio,AudioSpeech), theRerankmethod doesn't validateapiConfigbefore dereferencingapiConfig.ApiKeyon line 539. This will panic ifapiConfigis nil orApiKeyis nil.🐛 Proposed fix
func (t *TogetherAIModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) { if len(documents) == 0 { return &RerankResponse{}, nil } + if err := t.baseModel.APIConfigCheck(apiConfig); err != nil { + return nil, err + } + var region = "default"🤖 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 499 - 539, The Rerank method dereferences apiConfig.ApiKey without validating apiConfig; add the same APIConfigCheck call used in other methods (or explicitly check that apiConfig != nil and apiConfig.ApiKey != nil) at the start of TogetherAIModel.Rerank before calling baseModel.GetBaseURL or using apiConfig.ApiKey, and return an appropriate error if the check fails so the subsequent req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) cannot panic.
516-519:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winDead code: redundant
topNreassignment.Line 516 sets
topN := rerankConfig.TopN, then lines 517-519 conditionally reassign the same value. The condition body has no effect.This appears to be a copy-paste from a pattern where
topNdefaults tolen(documents)whenTopNis 0.🔧 Suggested fix
- var topN = rerankConfig.TopN - if rerankConfig.TopN != 0 { - topN = rerankConfig.TopN - } + topN := rerankConfig.TopN + if topN == 0 { + topN = len(documents) + }🤖 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 516 - 519, The assignment to topN is redundant: topN is set to rerankConfig.TopN and then conditionally reassigned to the same value; remove the dead conditional and instead implement the intended default behavior where topN should equal rerankConfig.TopN unless it is 0, in which case set topN = len(documents). Update the code that initializes topN (variable topN and use of rerankConfig.TopN) to reflect this logic so later uses (e.g., reranking code) get the correct default when TopN == 0.internal/entity/models/gitee.go (1)
258-280:⚠️ Potential issue | 🟠 Major | ⚡ Quick winPotential nil pointer dereference on
chatModelConfig.
chatModelConfigis accessed without a nil check at lines 258, 262, 266, etc. If a caller passesnilforchatModelConfig, this will panic at runtime.The non-streaming
ChatWithMessages(line 103) properly guards withif chatModelConfig != nil, butChatStreamlyWithSenderdoes not.🐛 Proposed fix
+ if chatModelConfig == nil { + chatModelConfig = &ChatConfig{} + } + if chatModelConfig.Stream != nil { reqBody["stream"] = *chatModelConfig.Stream }Or wrap the entire block:
+ if chatModelConfig != nil { if chatModelConfig.Stream != nil { reqBody["stream"] = *chatModelConfig.Stream } // ... rest of config handling + }🤖 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/gitee.go` around lines 258 - 280, The code in ChatStreamlyWithSender dereferences chatModelConfig without checking for nil, which can panic; add a nil guard similar to ChatWithMessages by wrapping the block that reads chatModelConfig fields (Stream, MaxTokens, Temperature, DoSample, TopP, Stop) with if chatModelConfig != nil { ... } or return/handle the nil case early inside ChatStreamlyWithSender so accesses to chatModelConfig.Stream, chatModelConfig.MaxTokens, chatModelConfig.Temperature, chatModelConfig.DoSample, chatModelConfig.TopP and chatModelConfig.Stop are only performed when chatModelConfig is non-nil.internal/entity/models/orcarouter.go (3)
187-202:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winPotential nil pointer dereference in
ChatStreamlyWithSender.
ChatStreamlyWithSenderdereferences*apiConfig.ApiKeyat line 256 without first validating thatapiConfigorapiConfig.ApiKeyis non-nil. Consider addingAPIConfigCheckfor consistency withChatWithMessages.Also applies to: 256-256
🤖 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 187 - 202, ChatStreamlyWithSender dereferences apiConfig.ApiKey without nil checks; add the same validation used in ChatWithMessages (call APIConfigCheck or inline checks) before accessing *apiConfig.ApiKey and ensure apiConfig itself is non-nil; update ChatStreamlyWithSender (and any helper variables that read apiConfig.ApiKey) to return an error when apiConfig or apiConfig.ApiKey is nil or empty, mirroring the behavior of APIConfigCheck so you avoid a nil pointer dereference.
348-363:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winPotential nil pointer dereference in
AudioSpeech.
AudioSpeechdereferences*apiConfig.ApiKeyat line 394 without validation. Consider addingAPIConfigCheck.Also applies to: 394-394
🤖 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 348 - 363, AudioSpeech currently dereferences apiConfig.ApiKey without checking for nil; add a defensive check in AudioSpeech to validate apiConfig and apiConfig.ApiKey (and that the string is not empty) before using *apiConfig.ApiKey, or call/use a helper like APIConfigCheck to perform that validation; locate the AudioSpeech method on OrcaRouterModel and the GetBaseURL call (o.baseModel.GetBaseURL) and return a clear error when the API key is missing instead of dereferencing a nil pointer.
426-437:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winPotential nil pointer dereference in
ListModels.
ListModelsdereferences*apiConfig.ApiKeyat line 455 without validation. Consider addingAPIConfigCheck.Also applies to: 455-455
🤖 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 426 - 437, ListModels may dereference apiConfig.ApiKey (and possibly apiConfig) without validation leading to nil pointer panics; update OrcaRouterModel.ListModels to validate apiConfig and apiConfig.ApiKey before dereferencing (or call the existing APIConfigCheck helper) and return a clear error if missing, e.g., check apiConfig != nil and apiConfig.ApiKey != nil and *apiConfig.ApiKey != "" prior to using it (also adjust any other dereferences in ListModels accordingly).internal/entity/models/moonshot.go (2)
381-392:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winPotential nil pointer dereference in
ListModels.
ListModelsdereferences*apiConfig.ApiKeyat line 411 without validating thatapiConfig.ApiKeyis non-nil. Consider addingAPIConfigCheckfor consistency.Also applies to: 411-411
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/moonshot.go` around lines 381 - 392, ListModels currently dereferences apiConfig.ApiKey without ensuring apiConfig.ApiKey is non-nil; add a guard at the start of the function (or call the existing APIConfigCheck helper) to validate apiConfig and apiConfig.ApiKey before any dereference, returning a clear error if missing, and update any subsequent code paths (e.g., where *apiConfig.ApiKey is used) to assume a non-nil value after this check; refer to the ListModels method and APIConfigCheck (or the APIConfig struct) to locate where to add the validation.
207-223:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winPotential nil pointer dereference when accessing
apiConfig.ApiKey.
ChatStreamlyWithSenderdereferences*apiConfig.ApiKeyat line 293 without first validating thatapiConfigorapiConfig.ApiKeyis non-nil. WhileapiConfigis checked for region (lines 213-216), the API key is accessed unconditionally. Consider addingAPIConfigCheckat the start of this method for consistency withBalance(line 446).Suggested fix
func (m *MoonshotModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig, sender func(*string, *string) error) error { + if err := m.baseModel.APIConfigCheck(apiConfig); err != nil { + return err + } if len(messages) == 0 { return fmt.Errorf("messages is empty") }Also applies to: 293-293
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/moonshot.go` around lines 207 - 223, The method ChatStreamlyWithSender currently dereferences apiConfig.ApiKey without nil-checking apiConfig or apiConfig.ApiKey; add the same validation used by Balance (or call APIConfigCheck) near the top of ChatStreamlyWithSender so that if apiConfig==nil or apiConfig.ApiKey==nil/empty you return a clear error instead of dereferencing; update the code paths that use *apiConfig.ApiKey (and any other apiConfig fields accessed later) to assume non-nil only after this guard.internal/entity/models/groq.go (2)
414-529:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMissing
APIConfigCheckbefore dereferencingapiConfig.ApiKey.
TranscribeAudiodereferences*apiConfig.ApiKeyat line 500 without first validating thatapiConfigandApiKeyare non-nil. Other methods in this file (e.g.,ChatWithMessages,ListModels) callg.baseModel.APIConfigCheck(apiConfig)for this purpose.🐛 Proposed fix
func (g *GroqModel) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) { + if err := g.baseModel.APIConfigCheck(apiConfig); err != nil { + return nil, err + } + if file == nil || *file == "" { return nil, fmt.Errorf("file is missing") }🤖 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/groq.go` around lines 414 - 529, TranscribeAudio dereferences apiConfig.ApiKey without validating apiConfig; call g.baseModel.APIConfigCheck(apiConfig) early (like other methods such as ChatWithMessages/ListModels) and return the error if non-nil, then proceed to use *apiConfig.ApiKey; ensure you place this check before building the request or setting the Authorization header so apiConfig and ApiKey are guaranteed non-nil when used.
535-595:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMissing
APIConfigCheckbefore dereferencingapiConfig.ApiKey.
AudioSpeechdereferences*apiConfig.ApiKeyat line 577 without first validating thatapiConfigandApiKeyare non-nil.🐛 Proposed fix
func (g *GroqModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) { + if err := g.baseModel.APIConfigCheck(apiConfig); err != nil { + return nil, err + } + if audioContent == nil || *audioContent == "" { return nil, fmt.Errorf("audio content is empty") }🤖 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/groq.go` around lines 535 - 595, In AudioSpeech, avoid dereferencing apiConfig.ApiKey without checking; add a guard that returns a clear error if apiConfig is nil or apiConfig.ApiKey is nil/empty before calling g.baseModel.GetBaseURL or setting the Authorization header (check apiConfig != nil && apiConfig.ApiKey != nil && *apiConfig.ApiKey != ""), and only set req.Header.Authorization when the API key is present; update error messages in AudioSpeech to reflect a missing API key and ensure references to APIConfig and ApiKey are used to locate the fix.internal/entity/models/deepinfra.go (1)
998-1002:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winTypo: "currence" should be "currency".
This is returned in the balance response and may be consumed by downstream clients or UIs.
🐛 Suggested fix
return map[string]interface{}{ "balance": result.Balance, - "currence": "USD", + "currency": "USD", }, 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/deepinfra.go` around lines 998 - 1002, The returned map uses the misspelled key "currence" instead of "currency"; locate the function that returns the map with "balance": result.Balance and change the map key "currence" to "currency" so downstream consumers receive the correct field name (ensure only the key string is updated, leaving result.Balance and the returned types intact).internal/entity/models/fishaudio.go (1)
436-481:⚠️ Potential issue | 🟠 Major | ⚡ Quick winPotential nil-pointer dereference on
apiConfig.ApiKey.Unlike other methods in this file (e.g.,
TranscribeAudio,AudioSpeech),Balancedoes not callbaseModel.APIConfigCheck(apiConfig)before dereferencing*apiConfig.ApiKeyat line 458. IfapiConfigis nil orApiKeyis nil, this will panic.🐛 Proposed fix
func (f *FishAudioModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) { + if err := f.baseModel.APIConfigCheck(apiConfig); err != nil { + return nil, err + } + var region = "default" if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" {🤖 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 436 - 481, The Balance method may panic by dereferencing apiConfig.ApiKey without validation; update FishAudioModel.Balance to call f.baseModel.APIConfigCheck(apiConfig) (same as TranscribeAudio/AudioSpeech) or otherwise validate that apiConfig and apiConfig.ApiKey are non-nil before using *apiConfig.ApiKey, and return the error from APIConfigCheck (or a descriptive error) if validation fails so the function never dereferences a nil pointer.internal/entity/models/jina.go (2)
183-216:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMissing API key validation in
Embedmay cause nil dereference.
EmbeddereferencesapiConfig.ApiKeyat line 216 without first validating thatapiConfigandapiConfig.ApiKeyare non-nil. UnlikeChatWithMessageswhich callsbaseModel.APIConfigCheck(apiConfig), this method has no such guard.If
apiConfigis nil or has a nilApiKey, this will panic.🐛 Proposed fix
func (j *JinaModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) { if len(texts) == 0 { return []EmbeddingData{}, nil } + if err := j.baseModel.APIConfigCheck(apiConfig); err != nil { + return nil, err + } + var region = "default"🤖 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/jina.go` around lines 183 - 216, Embed currently dereferences apiConfig.ApiKey without validation which can panic; call the existing baseModel.APIConfigCheck(apiConfig) (same guard used by ChatWithMessages) at the start of JinaModel.Embed and return the error when it fails, or explicitly check that apiConfig != nil and apiConfig.ApiKey != nil (and non-empty) before using *apiConfig.ApiKey; update any early returns to return a clear error instead of allowing a nil dereference.
259-299:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMissing API key validation in
Rerankmay cause nil dereference.Same issue as
Embed:RerankdereferencesapiConfig.ApiKeyat line 299 without validation.🐛 Proposed fix
func (j *JinaModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) { if len(documents) == 0 { return &RerankResponse{}, nil } + if err := j.baseModel.APIConfigCheck(apiConfig); err != nil { + return nil, err + } + var region = "default"🤖 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/jina.go` around lines 259 - 299, The Rerank method dereferences apiConfig.ApiKey without checking for nil/empty (risking a panic); update JinaModel.Rerank to validate apiConfig and apiConfig.ApiKey (and that ApiKey is not empty) before using it (similar to the Embed fix), returning a clear error if missing, and only set the Authorization header when ApiKey is present.internal/entity/models/huggingface.go (2)
475-486:⚠️ Potential issue | 🟠 Major | ⚡ Quick winPotential nil pointer dereference in
ListModels.At line 477,
apiConfig.Regionis accessed without first checking ifapiConfigis nil. WhileGetBaseURL(line 482) would also fail on nilapiConfig, the nil dereference at line 477 would panic first. Additionally, line 505 dereferencesapiConfig.ApiKeywithout a nil guard.Consider adding validation at the start of this method, consistent with other methods that call
baseModel.APIConfigCheck.🐛 Proposed fix
func (h *HuggingFaceModel) ListModels(apiConfig *APIConfig) ([]string, error) { + if err := h.baseModel.APIConfigCheck(apiConfig); err != nil { + return nil, err + } + var region = "default" - if apiConfig.Region != nil && *apiConfig.Region != "" { + if apiConfig != nil && apiConfig.Region != nil && *apiConfig.Region != "" { region = *apiConfig.Region }🤖 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 475 - 486, In ListModels, guard against a nil apiConfig and its fields before dereferencing apiConfig.Region and apiConfig.ApiKey by invoking the existing validation helper (baseModel.APIConfigCheck) at the start of the method or by explicitly checking apiConfig != nil and required fields; ensure you call baseModel.APIConfigCheck(apiConfig) (or equivalent) prior to using apiConfig.Region and before calling h.baseModel.GetBaseURL(apiConfig), and remove the standalone unchecked dereferences of apiConfig.Region and apiConfig.ApiKey so the method fails with a clear error instead of panicking.
234-268:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winPotential nil pointer dereference in
ChatStreamlyWithSender.The method accesses
modelConfig.Stream,modelConfig.MaxTokens, etc. without first checking ifmodelConfigis nil. If a caller passesnilformodelConfig, this will panic at line 234.Compare with
ChatWithMessages(line 88) which guards these accesses withif chatModelConfig != nil.🐛 Proposed fix
- if modelConfig.Stream != nil { - reqBody["stream"] = *modelConfig.Stream - } - - if modelConfig.MaxTokens != 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["max_tokens"] = *modelConfig.MaxTokens + } + + if modelConfig.Temperature != nil { - reqBody["temperature"] = *modelConfig.Temperature - } - - if modelConfig.DoSample != nil { + reqBody["temperature"] = *modelConfig.Temperature + } + + if modelConfig.DoSample != nil { - reqBody["do_sample"] = *modelConfig.DoSample - } - - if modelConfig.TopP != nil { + reqBody["do_sample"] = *modelConfig.DoSample + } + + if modelConfig.TopP != nil { - reqBody["top_p"] = *modelConfig.TopP - } - - if modelConfig.Stop != nil { + reqBody["top_p"] = *modelConfig.TopP + } + + if modelConfig.Stop != nil { - reqBody["stop"] = *modelConfig.Stop - } - - if modelConfig.Thinking != nil { + reqBody["stop"] = *modelConfig.Stop + } + + if modelConfig.Thinking != nil { - if *modelConfig.Thinking { + if *modelConfig.Thinking { - reqBody["thinking"] = map[string]interface{}{ + reqBody["thinking"] = map[string]interface{}{ - "type": "enabled", + "type": "enabled", + } + } else { + reqBody["thinking"] = map[string]interface{}{ + "type": "disabled", + } } - } else { - reqBody["thinking"] = map[string]interface{}{ - "type": "disabled", - } } }🤖 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 234 - 268, The block in ChatStreamlyWithSender accesses modelConfig fields (Stream, MaxTokens, Temperature, DoSample, TopP, Stop, Thinking) without checking if modelConfig is nil; add a nil guard similar to ChatWithMessages (e.g., if modelConfig != nil) and move the entire reqBody population for those fields inside that guard so you never dereference a nil modelConfig, preserving existing behavior for each field (including the Thinking enabled/disabled map).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: fcb9027e-8c1c-4e8e-92dc-343d2b305133
📒 Files selected for processing (65)
internal/entity/models/302ai.gointernal/entity/models/aliyun.gointernal/entity/models/anthropic.gointernal/entity/models/astraflow.gointernal/entity/models/avian.gointernal/entity/models/azure_openai.gointernal/entity/models/baichuan.gointernal/entity/models/baidu.gointernal/entity/models/base_model.gointernal/entity/models/bedrock.gointernal/entity/models/cohere.gointernal/entity/models/cometapi.gointernal/entity/models/cometapi_test.gointernal/entity/models/deepinfra.gointernal/entity/models/deepseek.gointernal/entity/models/dummy.gointernal/entity/models/fishaudio.gointernal/entity/models/futurmix.gointernal/entity/models/gitee.gointernal/entity/models/google.gointernal/entity/models/google_test.gointernal/entity/models/gpustack.gointernal/entity/models/groq.gointernal/entity/models/groq_test.gointernal/entity/models/huaweicloud.gointernal/entity/models/huggingface.gointernal/entity/models/hunyuan.gointernal/entity/models/jiekouai.gointernal/entity/models/jina.gointernal/entity/models/lmstudio.gointernal/entity/models/localai.gointernal/entity/models/longcat.gointernal/entity/models/mineru.gointernal/entity/models/mineru_local.gointernal/entity/models/minimax.gointernal/entity/models/mistral.gointernal/entity/models/modelscope.gointernal/entity/models/moonshot.gointernal/entity/models/n1n.gointernal/entity/models/novita.gointernal/entity/models/nvidia.gointernal/entity/models/ollama.gointernal/entity/models/openai.gointernal/entity/models/openrouter.gointernal/entity/models/orcarouter.gointernal/entity/models/paddleocr.gointernal/entity/models/paddleocr_local.gointernal/entity/models/perplexity.gointernal/entity/models/ppio.gointernal/entity/models/ppio_test.gointernal/entity/models/qiniu.gointernal/entity/models/replicate.gointernal/entity/models/siliconflow.gointernal/entity/models/stepfun.gointernal/entity/models/togetherai.gointernal/entity/models/tokenhub.gointernal/entity/models/tokenpony.gointernal/entity/models/upstage.gointernal/entity/models/vllm.gointernal/entity/models/volcengine.gointernal/entity/models/voyage.gointernal/entity/models/xai.gointernal/entity/models/xinference.gointernal/entity/models/xunfei.gointernal/entity/models/zhipu-ai.go
|
|
||
| // send request | ||
| resp, err := c.httpClient.Do(req) | ||
| resp, err := c.baseModel.httpClient.Do(req) |
There was a problem hiding this comment.
Copy-paste error: Wrong provider name in error message.
The error message says "SiliconFlow ASR error" but this is the CometAPI driver.
Proposed fix
- return nil, fmt.Errorf("SiliconFlow ASR error: %s - %s", resp.Status, string(respBody))
+ return nil, fmt.Errorf("CometAPI ASR error: %s - %s", resp.Status, string(respBody))Also applies to: 728-728
🤖 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` at line 716, The error messages logged
after the HTTP call using c.baseModel.httpClient.Do(req) incorrectly reference
"SiliconFlow ASR error"; update those log/error strings to reference the correct
provider "CometAPI" (e.g., "CometAPI error" or "CometAPI ASR error") wherever
they are produced around the resp, err := c.baseModel.httpClient.Do(req) call
and the subsequent error handling (the second occurrence noted at the following
error check after that call). Ensure you replace only the provider name in the
existing error messages and keep the rest of the message/context intact.
| resolvedBaseURL, err := d.baseModel.GetBaseURL(apiConfig) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| url := fmt.Sprintf("%s/chat/completions", resolvedBaseURL) |
There was a problem hiding this comment.
Use the configured chat suffix in the streaming path too.
Line 255 hardcodes /chat/completions instead of d.baseModel.URLSuffix.Chat, so ChatStreamlyWithSender can hit a different endpoint than ChatWithMessages whenever this driver is instantiated with a custom suffix map.
Suggested fix
- url := fmt.Sprintf("%s/chat/completions", resolvedBaseURL)
+ url := fmt.Sprintf("%s/%s", strings.TrimSuffix(resolvedBaseURL, "/"), d.baseModel.URLSuffix.Chat)🤖 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/deepseek.go` around lines 251 - 255, The streaming
path in ChatStreamlyWithSender currently hardcodes "/chat/completions" after
calling d.baseModel.GetBaseURL(apiConfig); update it to use the configured
suffix d.baseModel.URLSuffix.Chat (same suffix used by ChatWithMessages) when
building the url so both streaming and non-streaming calls hit the same
endpoint; ensure you join resolvedBaseURL and d.baseModel.URLSuffix.Chat
correctly (preserve any leading/trailing slash behavior) and keep the call site
names (ChatStreamlyWithSender, d.baseModel.GetBaseURL,
d.baseModel.URLSuffix.Chat, ChatWithMessages) aligned.
| if err != nil { | ||
| return err | ||
| } | ||
| url := fmt.Sprintf("%s/chat/completions", resolvedBaseURL) |
There was a problem hiding this comment.
Inconsistent URL suffix usage: hardcoded path instead of URLSuffix.Chat.
Line 83 uses g.baseModel.URLSuffix.Chat but line 239 hardcodes "/chat/completions". This inconsistency could cause issues if the URL suffix is ever customized.
🔧 Suggested fix
- url := fmt.Sprintf("%s/chat/completions", resolvedBaseURL)
+ url := fmt.Sprintf("%s/%s", resolvedBaseURL, g.baseModel.URLSuffix.Chat)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| url := fmt.Sprintf("%s/chat/completions", resolvedBaseURL) | |
| url := fmt.Sprintf("%s/%s", resolvedBaseURL, g.baseModel.URLSuffix.Chat) |
🤖 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/gitee.go` at line 239, The code builds the completions
endpoint using a hardcoded "/chat/completions" string; change it to use the
model's URL suffix to keep behavior consistent with other uses. Replace the
hardcoded assembly of url (the line creating url from resolvedBaseURL) to
concatenate resolvedBaseURL with g.baseModel.URLSuffix.Chat (or otherwise format
using that field) so the code uses the same URLSuffix.Chat value as elsewhere
(e.g., where g.baseModel.URLSuffix.Chat is referenced) and avoids hardcoded
paths.
| func (g *GoogleModel) baseURL(apiConfig *APIConfig) string { | ||
| if apiConfig != nil && apiConfig.Region != nil { | ||
| if baseURL := strings.TrimSpace(g.BaseURL[*apiConfig.Region]); baseURL != "" { | ||
| return baseURL | ||
| } | ||
| baseURL, err := g.baseModel.GetBaseURL(apiConfig) | ||
| if err != nil { | ||
| return "" | ||
| } | ||
| return strings.TrimSpace(g.BaseURL["default"]) | ||
| return strings.TrimSpace(baseURL) | ||
| } |
There was a problem hiding this comment.
Silent error swallowing in baseURL method.
When GetBaseURL fails, this returns an empty string without propagating the error. If apiConfig.BaseURL is not set and no matching region exists, the genai client will receive an empty BaseURL which may cause confusing downstream failures.
Consider whether callers should see a clearer error when base URL resolution fails.
🤖 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/google.go` around lines 98 - 104, The current
GoogleModel.baseURL swallows errors from g.baseModel.GetBaseURL and returns an
empty string; change baseURL to return (string, error), propagate the error from
g.baseModel.GetBaseURL (wrap with context like "resolve base URL for
GoogleModel" and include apiConfig info), and update all callers that invoke
GoogleModel.baseURL to handle the error and abort client creation instead of
using an empty BaseURL; reference the GoogleModel.baseURL method and
g.baseModel.GetBaseURL so callers (e.g., where a genai client or BaseURL is
consumed) are updated to accept and react to the returned error.
| httpClient: &http.Client{ | ||
| Transport: &http.Transport{ | ||
| MaxIdleConns: 10, | ||
| MaxIdleConnsPerHost: 100, | ||
| IdleConnTimeout: 90 * time.Second, | ||
| DisableCompression: false, | ||
| }, |
There was a problem hiding this comment.
Connection pool settings appear swapped.
MaxIdleConns: 10 and MaxIdleConnsPerHost: 100 appear to be swapped compared to other providers in this PR (which use MaxIdleConns: 100 and MaxIdleConnsPerHost: 10). Since MaxIdleConnsPerHost is effectively capped by MaxIdleConns, the current configuration limits idle connections to 10 total despite the per-host setting of 100.
Suggested fix
httpClient: &http.Client{
Transport: &http.Transport{
- MaxIdleConns: 10,
- MaxIdleConnsPerHost: 100,
+ MaxIdleConns: 100,
+ MaxIdleConnsPerHost: 10,
IdleConnTimeout: 90 * time.Second,
DisableCompression: false,
},
},📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| httpClient: &http.Client{ | |
| Transport: &http.Transport{ | |
| MaxIdleConns: 10, | |
| MaxIdleConnsPerHost: 100, | |
| IdleConnTimeout: 90 * time.Second, | |
| DisableCompression: false, | |
| }, | |
| httpClient: &http.Client{ | |
| Transport: &http.Transport{ | |
| MaxIdleConns: 100, | |
| MaxIdleConnsPerHost: 10, | |
| IdleConnTimeout: 90 * time.Second, | |
| DisableCompression: false, | |
| }, |
🤖 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 46 - 52, The
http.Transport connection pool values are inverted in the httpClient
construction: change the fields on the Transport inside the httpClient
(httpClient: &http.Client{ Transport: &http.Transport{ ... }}) so that
MaxIdleConns is 100 and MaxIdleConnsPerHost is 10 (leave IdleConnTimeout and
DisableCompression unchanged) to match other providers and ensure the per-host
cap is effective.
| resolvedBaseURL, err := v.baseModel.GetBaseURL(apiConfig) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| url := fmt.Sprintf("%s/chat/completions", resolvedBaseURL) |
There was a problem hiding this comment.
Keep the streaming endpoint wired to URLSuffix.Chat.
Line 248 hardcodes /chat/completions, so this path ignores the suffix configuration preserved in v.baseModel.URLSuffix. Any custom VolcEngine deployment with a non-default chat suffix will work for non-streaming calls and break for streaming ones.
Suggested fix
- url := fmt.Sprintf("%s/chat/completions", resolvedBaseURL)
+ url := fmt.Sprintf("%s/%s", strings.TrimSuffix(resolvedBaseURL, "/"), v.baseModel.URLSuffix.Chat)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| resolvedBaseURL, err := v.baseModel.GetBaseURL(apiConfig) | |
| if err != nil { | |
| return err | |
| } | |
| url := fmt.Sprintf("%s/chat/completions", resolvedBaseURL) | |
| resolvedBaseURL, err := v.baseModel.GetBaseURL(apiConfig) | |
| if err != nil { | |
| return err | |
| } | |
| url := fmt.Sprintf("%s/%s", strings.TrimSuffix(resolvedBaseURL, "/"), v.baseModel.URLSuffix.Chat) |
🤖 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 244 - 248, The streaming
endpoint is hardcoded to "/chat/completions" and ignores the configured suffix
on v.baseModel; change the construction of the streaming URL to use the
preserved suffix (e.g., v.baseModel.URLSuffix.Chat or the equivalent
field/method) so it mirrors how GetBaseURL/apiConfig resolves non-streaming
calls; update the code that sets url in the same block (where resolvedBaseURL is
obtained from v.baseModel.GetBaseURL) to append the dynamic chat suffix instead
of the literal "/chat/completions".
There was a problem hiding this comment.
Actionable comments posted: 11
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (12)
internal/entity/models/base_model.go (1)
31-36:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift
APIConfigCheckis now too strict for optional-auth drivers and still leaves padded keys unnormalized.This helper now hard-fails every driver on an empty key, but
LocalAIModelin this PR still represents a provider that can run without auth. It also validatesstrings.TrimSpace(*apiConfig.ApiKey)without storing/returning that normalized value, so drivers likexunfei.go,aliyun.go,azure_openai.go, andlocalai.gostill send whitespace-padded keys unchanged. Please split normalization from “API key required” enforcement, or make the requirement opt-in per driver.🤖 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/base_model.go` around lines 31 - 36, APIConfigCheck currently both trims/normalizes the API key and unconditionally errors on an empty key, which breaks optional-auth drivers like LocalAIModel and fails to return the normalized value to callers; modify APIConfigCheck (BaseModel.APIConfigCheck) to separate normalization from enforcement by trimming whitespace and updating apiConfig.ApiKey to the trimmed value, and make the “must have key” check conditional (either return nil for empty keys or accept a parameter/flag so callers/drivers such as LocalAIModel, xunfei.go, aliyun.go, and azure_openai.go can opt-in to require a non-empty key); ensure callers that need required auth explicitly validate the presence of apiConfig.ApiKey after normalization.internal/entity/models/aliyun.go (2)
476-499:⚠️ Potential issue | 🟠 Major | ⚡ Quick winHandle a nil
rerankConfigbefore readingTopN.
var topN = rerankConfig.TopNpanics on the common nil-config path. The sibling rerank implementations in this PR default nil to “all documents”; this one should do the same.Suggested fix
- var topN = rerankConfig.TopN - if rerankConfig.TopN == 0 { - topN = len(documents) - } + topN := len(documents) + if rerankConfig != nil && rerankConfig.TopN > 0 { + topN = rerankConfig.TopN + }🤖 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 476 - 499, The Rerank method on AliyunModel reads rerankConfig.TopN without checking for nil, causing a panic; update AliyunModel.Rerank to guard for a nil rerankConfig (or nil TopN usage) before accessing TopN and default topN to len(documents) when rerankConfig is nil or TopN == 0, mirroring the sibling implementations; locate the topN logic in Rerank, add a nil-check for rerankConfig, and set var topN = len(documents) when rerankConfig == nil, otherwise use rerankConfig.TopN with the existing 0 => len(documents) fallback.
205-269:⚠️ Potential issue | 🟠 Major | ⚡ Quick winGuard
senderandchatModelConfigbefore dereferencing them.This method still reads
chatModelConfig.Stream/MaxTokensunconditionally and later callssender(...)unconditionally, sonilinputs panic the request path instead of returning a validation error.Suggested fix
func (a *AliyunModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig, sender func(*string, *string) error) error { if err := a.baseModel.APIConfigCheck(apiConfig); err != nil { return err } + if sender == nil { + return fmt.Errorf("sender is required") + } if len(messages) == 0 { return fmt.Errorf("messages is empty") } @@ - if chatModelConfig.Stream != nil { - reqBody["stream"] = *chatModelConfig.Stream - } - - if chatModelConfig.MaxTokens != nil { - reqBody["max_tokens"] = *chatModelConfig.MaxTokens - } - - if chatModelConfig.Temperature != nil { - reqBody["temperature"] = *chatModelConfig.Temperature - } - - if chatModelConfig.DoSample != nil { - reqBody["do_sample"] = *chatModelConfig.DoSample - } - - if chatModelConfig.TopP != nil { - reqBody["top_p"] = *chatModelConfig.TopP - } - - if chatModelConfig.Stop != nil { - reqBody["stop"] = *chatModelConfig.Stop - } - - if chatModelConfig.Thinking != nil { - if *chatModelConfig.Thinking { - reqBody["enable_thinking"] = true - } else { - reqBody["enable_thinking"] = false - } - } + if chatModelConfig != nil { + if chatModelConfig.Stream != nil { + reqBody["stream"] = *chatModelConfig.Stream + } + if chatModelConfig.MaxTokens != nil { + reqBody["max_tokens"] = *chatModelConfig.MaxTokens + } + if chatModelConfig.Temperature != nil { + reqBody["temperature"] = *chatModelConfig.Temperature + } + if chatModelConfig.DoSample != nil { + reqBody["do_sample"] = *chatModelConfig.DoSample + } + if chatModelConfig.TopP != nil { + reqBody["top_p"] = *chatModelConfig.TopP + } + if chatModelConfig.Stop != nil { + reqBody["stop"] = *chatModelConfig.Stop + } + if chatModelConfig.Thinking != nil { + reqBody["enable_thinking"] = *chatModelConfig.Thinking + } + }🤖 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 205 - 269, In ChatStreamlyWithSender ensure you validate inputs before dereferencing: check that chatModelConfig != nil (and return a descriptive error) before reading any of its fields like Stream, MaxTokens, Temperature, DoSample, TopP, Stop, Thinking, and check that sender != nil (and return an error) before invoking it; update the guarded blocks around uses of chatModelConfig.* and the final sender(...) call in the ChatStreamlyWithSender function so nil pointers can't be dereferenced and an appropriate validation error is returned instead.internal/entity/models/volcengine.go (1)
260-310:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winNil
modelConfigorEffortwill panic this stream path.This block dereferences
modelConfigimmediately and later doesswitch *modelConfig.Effortwithout checking either pointer.ChatStreamlyWithSender(..., nil, ...)orThinking=truewithEffort=nilwill crash here, while the non-streaming path already defaults missing effort to"medium".Suggested 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.TopP != nil { - reqBody["top_p"] = *modelConfig.TopP - } - - if modelConfig.DoSample != nil { - reqBody["do_sample"] = *modelConfig.DoSample - } - - if modelConfig.Stop != nil { - reqBody["stop"] = *modelConfig.Stop - } - - // TODO VolcEngine has `auto` mode - if modelConfig.Thinking != nil { - if *modelConfig.Thinking { - var thinkingFlag string - switch *modelConfig.Effort { + 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.TopP != nil { + reqBody["top_p"] = *modelConfig.TopP + } + if modelConfig.DoSample != nil { + reqBody["do_sample"] = *modelConfig.DoSample + } + if modelConfig.Stop != nil { + reqBody["stop"] = *modelConfig.Stop + } + if modelConfig.Thinking != nil { + if *modelConfig.Thinking { + effort := "medium" + if modelConfig.Effort != nil { + effort = *modelConfig.Effort + } + var thinkingFlag string + switch effort { case "none", "minimal": thinkingFlag = "disabled" reqBody["reasoning_effort"] = "minimal" - break case "low": thinkingFlag = "enabled" reqBody["reasoning_effort"] = "low" - break case "medium": thinkingFlag = "enabled" reqBody["reasoning_effort"] = "medium" - break case "auto", "default": thinkingFlag = "enabled" reqBody["reasoning_effort"] = "medium" - break case "high": thinkingFlag = "enabled" reqBody["reasoning_effort"] = "high" - break default: return fmt.Errorf("invalid effort level") } reqBody["thinking"] = map[string]interface{}{ "type": thinkingFlag, } - } else { - reqBody["thinking"] = map[string]interface{}{ - "type": "disabled", - } + } else { + reqBody["thinking"] = map[string]interface{}{ + "type": "disabled", + } + } } }🤖 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 260 - 310, The stream-path dereferences modelConfig and modelConfig.Effort without nil checks causing panics; update the logic around the Thinking branch in the function that builds reqBody (references: modelConfig, modelConfig.Thinking, modelConfig.Effort, reqBody) to first guard that modelConfig is non-nil and that modelConfig.Effort is non-nil before dereferencing; if Effort is nil, default it to "medium" (same as non-stream path) and proceed to set reasoning_effort and the local thinkingFlag accordingly, returning an error only for truly invalid effort strings.internal/entity/models/vllm.go (1)
248-282:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winGuard
modelConfigbefore reading its fields in the streaming path.This method dereferences
modelConfigrepeatedly without checking whether the pointer is nil, soChatStreamlyWithSender(..., nil, ...)panics before the request is even sent.Suggested 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.Thinking { - reqBody["thinking"] = map[string]interface{}{ - "type": "enabled", - } - } else { - reqBody["thinking"] = map[string]interface{}{ - "type": "disabled", - } - } - } + 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 { + if *modelConfig.Thinking { + reqBody["thinking"] = map[string]interface{}{ + "type": "enabled", + } + } else { + reqBody["thinking"] = map[string]interface{}{ + "type": "disabled", + } + } + } + }🤖 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/vllm.go` around lines 248 - 282, The code dereferences modelConfig repeatedly (e.g., modelConfig.Stream, MaxTokens, Temperature, DoSample, TopP, Stop, Thinking) in the streaming path (used by ChatStreamlyWithSender) without guarding for nil; wrap the entire sequence that sets reqBody from modelConfig in a single nil-check (if modelConfig != nil) so you only read its fields when non-nil, preserving the existing field mappings (including the Thinking branch that writes reqBody["thinking"] with type "enabled"/"disabled"); ensure reqBody is still used when modelConfig is nil by leaving it unchanged.internal/entity/models/upstage.go (1)
243-251:⚠️ Potential issue | 🟠 Major | ⚡ Quick winRestore a bounded context for the Upstage streaming request.
This stream request is built with
context.Background(), but the sharedhttp.Clientstill has noTimeout. Once the headers arrive, a stuck upstream stream can hang this call indefinitely unless you add a request-scoped deadline here.Based on learnings, when `httpClient.Timeout` is intentionally unset, `context.WithTimeout` is the method’s only overall request deadline.Suggested 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` around lines 243 - 251, The request uses context.Background() so the shared http.Client (u.baseModel.httpClient) can hang indefinitely; replace the Background context with a request-scoped context created via context.WithTimeout (e.g., ctx, cancel := context.WithTimeout(parentCtx, timeout)) and pass that ctx into http.NewRequestWithContext, then defer cancel() before calling u.baseModel.httpClient.Do(req); update the call site in upstage.go where NewRequestWithContext and Do are used (refer to symbols NewRequestWithContext, u.baseModel.httpClient.Do, and the function containing them) and choose a sensible timeout or a configurable value.internal/entity/models/astraflow.go (2)
396-414:⚠️ Potential issue | 🟠 Major | ⚡ Quick winGuard
modelNamebefore dereferencing in the embedding and TTS paths.
Embedstill dereferences*modelNameat Line 412, andAudioSpeechdoes the same at Line 576. A nil caller input will panic instead of returning a validation error.Proposed fix
func (a *AstraflowModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) { if err := a.baseModel.APIConfigCheck(apiConfig); err != nil { return nil, err } if len(texts) == 0 { return []EmbeddingData{}, nil } + if modelName == nil || strings.TrimSpace(*modelName) == "" { + return nil, fmt.Errorf("model name is required") + } resolvedBaseURL, err := a.baseModel.GetBaseURL(apiConfig) @@ func (a *AstraflowModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) { if err := a.baseModel.APIConfigCheck(apiConfig); err != nil { return nil, err } + if modelName == nil || strings.TrimSpace(*modelName) == "" { + return nil, fmt.Errorf("model name is required") + } if audioContent == nil || *audioContent == "" { return nil, fmt.Errorf("text content is missing") }Also applies to: 560-578
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/astraflow.go` around lines 396 - 414, AstraflowModel.Embed and the AudioSpeech method currently dereference modelName directly (e.g., "model": *modelName) which can panic if modelName is nil; add a nil-check at the start of both methods (Embed and AudioSpeech) after APIConfig validation and before constructing reqBody to return a clear validation error when modelName == nil, and then use *modelName safely thereafter.
470-495:⚠️ Potential issue | 🟠 Major | ⚡ Quick winHandle a nil
rerankConfigbefore readingTopN.Line 485 dereferences
rerankConfigunconditionally. Any caller that omits rerank options will panic before the request is built.Proposed fix
- var topN = rerankConfig.TopN - if rerankConfig.TopN != 0 { - topN = rerankConfig.TopN - } + topN := 0 + if rerankConfig != nil && rerankConfig.TopN != 0 { + topN = rerankConfig.TopN + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/astraflow.go` around lines 470 - 495, The Rerank method in AstraflowModel dereferences rerankConfig without checking for nil (see Rerank and the TopN handling), which can panic; modify the code to first check if rerankConfig is non-nil before reading rerankConfig.TopN (e.g., initialize topN to a safe default, then if rerankConfig != nil && rerankConfig.TopN != 0 set topN = rerankConfig.TopN), and ensure you never dereference rerankConfig when constructing reqBody or elsewhere in Rerank so callers that omit rerank options do not panic.internal/entity/models/cometapi.go (1)
575-614:⚠️ Potential issue | 🟠 Major | ⚡ Quick winValidate
modelNamein ASR/TTS before using*modelName.
TranscribeAudiowrites*modelNameat Line 613, andAudioSpeechputs*modelNameinto the JSON body at Line 709. A nil pointer here becomes a panic on request construction.Proposed fix
func (c *CometAPIModel) TranscribeAudio(modelName *string, file *string, apiConfig *APIConfig, asrConfig *ASRConfig) (*ASRResponse, error) { if err := c.baseModel.APIConfigCheck(apiConfig); err != nil { return nil, err } + if modelName == nil || strings.TrimSpace(*modelName) == "" { + return nil, fmt.Errorf("model name is required") + } if file == nil || *file == "" { return nil, fmt.Errorf("file is missing") } @@ func (c *CometAPIModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) { if err := c.baseModel.APIConfigCheck(apiConfig); err != nil { return nil, err } + if modelName == nil || strings.TrimSpace(*modelName) == "" { + return nil, fmt.Errorf("model name is required") + } if audioContent == nil || *audioContent == "" { return nil, fmt.Errorf("audio content is empty") }Also applies to: 693-710
🤖 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 575 - 614, TranscribeAudio (and likewise AudioSpeech) currently dereference modelName (using *modelName) without validating it, which can panic if nil; add an explicit nil/empty check at the start of TranscribeAudio and AudioSpeech (e.g., if modelName == nil || *modelName == "" { return nil, fmt.Errorf("modelName is required") } or appropriate error/return type) and return a clear error before any use of *modelName so no dereference occurs later in writer.WriteField("model", *modelName) or when inserting into the JSON body.internal/entity/models/gitee.go (1)
534-539:⚠️ Potential issue | 🔴 Critical | ⚡ Quick win
Rerankstill panics whenrerankConfigis omitted.
rerankConfig.TopNis read before any nil check, so callers relying on default rerank options crash before the request is built.Suggested fix
- var topN = rerankConfig.TopN - if rerankConfig.TopN == 0 { - topN = len(documents) - } + topN := len(documents) + if rerankConfig != nil && rerankConfig.TopN > 0 { + topN = rerankConfig.TopN + }🤖 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/gitee.go` around lines 534 - 539, The Rerank method reads rerankConfig.TopN before checking for nil, causing a panic when rerankConfig is omitted; modify the Rerank implementation to first check if rerankConfig == nil and initialize a default config (or treat TopN as 0) before accessing rerankConfig.TopN, then compute topN = rerankConfig.TopN (or default to len(documents) when TopN == 0) and continue; update the code around the topN/rerankConfig usage in the Rerank method so the nil guard runs before any access to rerankConfig.TopN.internal/entity/models/stepfun.go (1)
417-445:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winTTS request bodies still dereference
modelNameblindly.Both TTS paths build
"model": *modelNamewithout checking the pointer first, so omitted voice/model settings panic before the request is sent.Suggested fix
func (s *StepFunModel) AudioSpeech(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig) (*TTSResponse, error) { if err := s.baseModel.APIConfigCheck(apiConfig); err != nil { return nil, err } // TODO Test it if audioContent == nil || *audioContent == "" { return nil, fmt.Errorf("audio content is empty") } + if modelName == nil || strings.TrimSpace(*modelName) == "" { + return nil, fmt.Errorf("model name is required") + } @@ func (s *StepFunModel) AudioSpeechWithSender(modelName *string, audioContent *string, apiConfig *APIConfig, ttsConfig *TTSConfig, sender func(*string, *string) error) error { if err := s.baseModel.APIConfigCheck(apiConfig); err != nil { return err } if audioContent == nil || *audioContent == "" { return fmt.Errorf("audio content is empty") } + if modelName == nil || strings.TrimSpace(*modelName) == "" { + return fmt.Errorf("model name is required") + }Also applies to: 494-507
🤖 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 417 - 445, The code in StepFunModel.AudioSpeech dereferences modelName without nil checks (and similarly in the other TTS path around lines 494-507), which can panic if callers omit the model; update AudioSpeech (and the other TTS method) to first validate modelName is non-nil and non-empty before using *modelName — either return a clear error like "model name is required" or use a configured default if your design allows — and then use the validated value when assigning reqBody["model"]; also ensure any downstream uses of modelName follow the same nil/empty check.internal/entity/models/togetherai.go (1)
474-499:⚠️ Potential issue | 🔴 Critical | ⚡ Quick win
Rerankassumes both optional pointers are present.This path now validates
apiConfig, butrerankConfig.TopNand*modelNameare still dereferenced unconditionally.Rerank(..., nil, ..., nil)panics before request assembly.Suggested fix
func (t *TogetherAIModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) { if err := t.baseModel.APIConfigCheck(apiConfig); err != nil { return nil, err } if len(documents) == 0 { return &RerankResponse{}, nil } + if modelName == nil || strings.TrimSpace(*modelName) == "" { + return nil, fmt.Errorf("model name is required") + } resolvedBaseURL, err := t.baseModel.GetBaseURL(apiConfig) if err != nil { return nil, err } url := fmt.Sprintf("%s/%s", resolvedBaseURL, t.baseModel.URLSuffix.Rerank) - var topN = rerankConfig.TopN - if rerankConfig.TopN != 0 { + topN := 0 + if rerankConfig != nil && rerankConfig.TopN != 0 { topN = rerankConfig.TopN }🤖 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 474 - 499, TogetherAIModel.Rerank dereferences modelName and rerankConfig without nil checks, causing panics when callers pass nil; update Rerank to guard both pointers: only dereference modelName when non-nil (e.g., include "model" in reqBody only if modelName != nil or set an explicit default string), and handle rerankConfig == nil by using a safe default for topN (or omitting "top_n") and fix the current redundant topN assignment (use a local topN := 0 and override it only when rerankConfig != nil and rerankConfig.TopN != 0); ensure no unconditional dereferences of modelName or rerankConfig.TopN anywhere in TogetherAIModel.Rerank.
♻️ Duplicate comments (1)
internal/entity/models/volcengine.go (1)
237-242:⚠️ Potential issue | 🟠 Major | ⚡ Quick winUse the configured chat suffix for streaming too.
ChatWithMessagesnow respectsv.baseModel.URLSuffix.Chat, but the streaming path still hardcodes/chat/completions. Any custom VolcEngine deployment with a non-default chat suffix will pass normal calls and fail only when streaming.Suggested fix
- url := fmt.Sprintf("%s/chat/completions", resolvedBaseURL) + url := fmt.Sprintf("%s/%s", strings.TrimSuffix(resolvedBaseURL, "/"), v.baseModel.URLSuffix.Chat)🤖 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 237 - 242, The streaming URL is hardcoded to "/chat/completions" and doesn't use the configured chat suffix; replace the fmt.Sprintf("%s/chat/completions", resolvedBaseURL) call so it appends v.baseModel.URLSuffix.Chat (from the same baseModel used by GetBaseURL) instead of the literal path, ensuring you normalize slashes when joining resolvedBaseURL and v.baseModel.URLSuffix.Chat; update the code in the streaming method that builds `url` (where `resolvedBaseURL, err := v.baseModel.GetBaseURL(apiConfig)` is used) to use the configured suffix (`v.baseModel.URLSuffix.Chat`).
🤖 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/anthropic.go`:
- Around line 86-91: The code is mapping an empty region to "default" via
baseURLRegion := a.region(apiConfig) before calling a.baseModel.GetBaseURL,
which hides custom BaseURL[""] entries; instead construct the APIConfig passed
to GetBaseURL using the raw region from apiConfig (i.e., use apiConfig.Region
directly when apiConfig != nil rather than baseURLRegion), so change
baseURLConfig := &APIConfig{Region: apiConfig.Region} (falling back to nil if
apiConfig is nil) and leave region-to-"default" fallback logic only inside
a.region/newModelDriverForBaseURL/newModelDriverForBaseURL lookups.
In `@internal/entity/models/gitee.go`:
- Around line 219-225: The method GiteeModel.ChatStreamlyWithSender validates
apiConfig but dereferences chatModelConfig and calls sender without nil checks;
update ChatStreamlyWithSender to validate that chatModelConfig != nil before
accessing its fields and that sender != nil before invoking it, returning a
clear validation error (e.g., fmt.Errorf("chatModelConfig is nil") or
fmt.Errorf("sender is nil")) instead of panicking; apply the same nil checks and
error returns in the other affected methods/ranges (around lines 251-285 and
372-405) where chatModelConfig or sender are used so all optional streaming
inputs are validated before use.
In `@internal/entity/models/mistral.go`:
- Around line 566-572: The code currently dereferences the OCR model name
(reqData["model"] = *modelName) without validating that modelName is non-nil and
non-empty, causing a panic; update the request validation in the same function
that calls m.baseModel.APIConfigCheck (and the similar block around the other
occurrence at lines handling 589-595) to check that modelName != nil and
*modelName != "" and return a descriptive validation error (e.g.,
fmt.Errorf("ocr model name is required")) before any dereference; ensure both
places that set reqData["model"] perform this nil/empty guard so the function
returns a normal error instead of panicking.
In `@internal/entity/models/n1n.go`:
- Around line 72-78: The endpoint resolution currently reconstructs APIConfig
with only Region which strips any caller-supplied BaseURL; change endpointURL to
accept and forward the original *APIConfig (or merge the Region into the
provided APIConfig) instead of building a new one, then call
n.baseModel.GetBaseURL(originalCfg). Update all callers (ChatStreamlyWithSender,
Rerank, ListModels) to pass their existing APIConfig through to
endpointURL/GetBaseURL so custom BaseURL values are preserved.
In `@internal/entity/models/nvidia.go`:
- Around line 195-202: In ChatStreamlyWithSender validate the sender callback is
non-nil before any streaming or invocation: after the APIConfigCheck and
messages emptiness check in the NvidiaModel.ChatStreamlyWithSender function, add
a nil-check for the sender parameter and return a descriptive error (e.g.,
"sender is nil") rather than letting the code panic when sender is invoked for
chunks or the final [DONE] marker.
In `@internal/entity/models/ollama.go`:
- Around line 335-337: The Embed path currently enforces credentials by calling
o.baseModel.APIConfigCheck(apiConfig); remove that check from the embedding flow
so embeddings do not require credentials when other Ollama calls
(ChatWithMessages, ChatStreamlyWithSender, ListModels) remain keyless; instead
ensure the request-building code only adds an Authorization header when
apiConfig actually contains credentials (i.e., conditionally set the header in
the same way as the other methods), and remove or avoid calling
baseModel.APIConfigCheck from Embed (and the similar occurrence around the other
mentioned line) so embedding behaves consistently with the other Ollama methods.
In `@internal/entity/models/openai.go`:
- Around line 196-204: ChatStreamlyWithSender lacks a nil check for the sender
callback which can cause a panic when the first stream chunk is delivered; add
an early guard at the start of ChatStreamlyWithSender (after APIConfigCheck and
before using messages) to return a descriptive error if sender == nil so
downstream calls at the streaming callbacks cannot dereference a nil function
pointer.
In `@internal/entity/models/replicate.go`:
- Around line 672-678: The empty-input fast paths are being blocked by
credential validation; in both the Embed and Rerank methods move the early
return for no input (the len(texts) == 0 / len(docs) == 0 checks that return
empty slices) to run before calling r.baseModel.APIConfigCheck(apiConfig) so
callers that supply zero items do not get a config error; update Embed and
Rerank to check for empty inputs and return immediately, then perform
APIConfigCheck and the rest of the logic.
In `@internal/entity/models/vllm.go`:
- Around line 438-439: Requests currently always set Authorization: Bearer
<apiKey>; change this to only add the Authorization header when an API key is
present (apiConfig.ApiKey != nil && *apiConfig.ApiKey != "") so local vLLM
deployments without auth do not send an Authorization header. Keep the
Content-Type header unchanged. Apply this conditional header logic in the places
that set the Authorization header (the vLLM request builders around the header
lines in internal/entity/models/vllm.go, including the other occurrences noted).
In `@internal/entity/models/xunfei.go`:
- Around line 193-200: In ChatStreamlyWithSender, guard against a nil sender
before any streaming begins: check the sender parameter at the start of the
function (in the ChatStreamlyWithSender method of XunFeiModel) and return a
clear error if sender == nil so the function never calls sender(...) and avoids
a panic when streaming deltas or the final "[DONE]".
In `@internal/entity/models/zhipu-ai.go`:
- Around line 402-407: The API config check (z.baseModel.APIConfigCheck) is
performed before empty-input guards, causing calls with zero-length inputs to
fail on missing credentials; move the empty-input checks (e.g., if len(texts)==0
return []EmbeddingData{}, nil and if len(documents)==0 return []RerankResult{},
nil) to run before calling z.baseModel.APIConfigCheck so that embed/rerank
functions become no-ops when inputs are empty and skip config validation; update
both occurrences around the embedding code (the block using texts) and the
rerank code (the block using documents).
---
Outside diff comments:
In `@internal/entity/models/aliyun.go`:
- Around line 476-499: The Rerank method on AliyunModel reads rerankConfig.TopN
without checking for nil, causing a panic; update AliyunModel.Rerank to guard
for a nil rerankConfig (or nil TopN usage) before accessing TopN and default
topN to len(documents) when rerankConfig is nil or TopN == 0, mirroring the
sibling implementations; locate the topN logic in Rerank, add a nil-check for
rerankConfig, and set var topN = len(documents) when rerankConfig == nil,
otherwise use rerankConfig.TopN with the existing 0 => len(documents) fallback.
- Around line 205-269: In ChatStreamlyWithSender ensure you validate inputs
before dereferencing: check that chatModelConfig != nil (and return a
descriptive error) before reading any of its fields like Stream, MaxTokens,
Temperature, DoSample, TopP, Stop, Thinking, and check that sender != nil (and
return an error) before invoking it; update the guarded blocks around uses of
chatModelConfig.* and the final sender(...) call in the ChatStreamlyWithSender
function so nil pointers can't be dereferenced and an appropriate validation
error is returned instead.
In `@internal/entity/models/astraflow.go`:
- Around line 396-414: AstraflowModel.Embed and the AudioSpeech method currently
dereference modelName directly (e.g., "model": *modelName) which can panic if
modelName is nil; add a nil-check at the start of both methods (Embed and
AudioSpeech) after APIConfig validation and before constructing reqBody to
return a clear validation error when modelName == nil, and then use *modelName
safely thereafter.
- Around line 470-495: The Rerank method in AstraflowModel dereferences
rerankConfig without checking for nil (see Rerank and the TopN handling), which
can panic; modify the code to first check if rerankConfig is non-nil before
reading rerankConfig.TopN (e.g., initialize topN to a safe default, then if
rerankConfig != nil && rerankConfig.TopN != 0 set topN = rerankConfig.TopN), and
ensure you never dereference rerankConfig when constructing reqBody or elsewhere
in Rerank so callers that omit rerank options do not panic.
In `@internal/entity/models/base_model.go`:
- Around line 31-36: APIConfigCheck currently both trims/normalizes the API key
and unconditionally errors on an empty key, which breaks optional-auth drivers
like LocalAIModel and fails to return the normalized value to callers; modify
APIConfigCheck (BaseModel.APIConfigCheck) to separate normalization from
enforcement by trimming whitespace and updating apiConfig.ApiKey to the trimmed
value, and make the “must have key” check conditional (either return nil for
empty keys or accept a parameter/flag so callers/drivers such as LocalAIModel,
xunfei.go, aliyun.go, and azure_openai.go can opt-in to require a non-empty
key); ensure callers that need required auth explicitly validate the presence of
apiConfig.ApiKey after normalization.
In `@internal/entity/models/cometapi.go`:
- Around line 575-614: TranscribeAudio (and likewise AudioSpeech) currently
dereference modelName (using *modelName) without validating it, which can panic
if nil; add an explicit nil/empty check at the start of TranscribeAudio and
AudioSpeech (e.g., if modelName == nil || *modelName == "" { return nil,
fmt.Errorf("modelName is required") } or appropriate error/return type) and
return a clear error before any use of *modelName so no dereference occurs later
in writer.WriteField("model", *modelName) or when inserting into the JSON body.
In `@internal/entity/models/gitee.go`:
- Around line 534-539: The Rerank method reads rerankConfig.TopN before checking
for nil, causing a panic when rerankConfig is omitted; modify the Rerank
implementation to first check if rerankConfig == nil and initialize a default
config (or treat TopN as 0) before accessing rerankConfig.TopN, then compute
topN = rerankConfig.TopN (or default to len(documents) when TopN == 0) and
continue; update the code around the topN/rerankConfig usage in the Rerank
method so the nil guard runs before any access to rerankConfig.TopN.
In `@internal/entity/models/stepfun.go`:
- Around line 417-445: The code in StepFunModel.AudioSpeech dereferences
modelName without nil checks (and similarly in the other TTS path around lines
494-507), which can panic if callers omit the model; update AudioSpeech (and the
other TTS method) to first validate modelName is non-nil and non-empty before
using *modelName — either return a clear error like "model name is required" or
use a configured default if your design allows — and then use the validated
value when assigning reqBody["model"]; also ensure any downstream uses of
modelName follow the same nil/empty check.
In `@internal/entity/models/togetherai.go`:
- Around line 474-499: TogetherAIModel.Rerank dereferences modelName and
rerankConfig without nil checks, causing panics when callers pass nil; update
Rerank to guard both pointers: only dereference modelName when non-nil (e.g.,
include "model" in reqBody only if modelName != nil or set an explicit default
string), and handle rerankConfig == nil by using a safe default for topN (or
omitting "top_n") and fix the current redundant topN assignment (use a local
topN := 0 and override it only when rerankConfig != nil and rerankConfig.TopN !=
0); ensure no unconditional dereferences of modelName or rerankConfig.TopN
anywhere in TogetherAIModel.Rerank.
In `@internal/entity/models/upstage.go`:
- Around line 243-251: The request uses context.Background() so the shared
http.Client (u.baseModel.httpClient) can hang indefinitely; replace the
Background context with a request-scoped context created via context.WithTimeout
(e.g., ctx, cancel := context.WithTimeout(parentCtx, timeout)) and pass that ctx
into http.NewRequestWithContext, then defer cancel() before calling
u.baseModel.httpClient.Do(req); update the call site in upstage.go where
NewRequestWithContext and Do are used (refer to symbols NewRequestWithContext,
u.baseModel.httpClient.Do, and the function containing them) and choose a
sensible timeout or a configurable value.
In `@internal/entity/models/vllm.go`:
- Around line 248-282: The code dereferences modelConfig repeatedly (e.g.,
modelConfig.Stream, MaxTokens, Temperature, DoSample, TopP, Stop, Thinking) in
the streaming path (used by ChatStreamlyWithSender) without guarding for nil;
wrap the entire sequence that sets reqBody from modelConfig in a single
nil-check (if modelConfig != nil) so you only read its fields when non-nil,
preserving the existing field mappings (including the Thinking branch that
writes reqBody["thinking"] with type "enabled"/"disabled"); ensure reqBody is
still used when modelConfig is nil by leaving it unchanged.
In `@internal/entity/models/volcengine.go`:
- Around line 260-310: The stream-path dereferences modelConfig and
modelConfig.Effort without nil checks causing panics; update the logic around
the Thinking branch in the function that builds reqBody (references:
modelConfig, modelConfig.Thinking, modelConfig.Effort, reqBody) to first guard
that modelConfig is non-nil and that modelConfig.Effort is non-nil before
dereferencing; if Effort is nil, default it to "medium" (same as non-stream
path) and proceed to set reasoning_effort and the local thinkingFlag
accordingly, returning an error only for truly invalid effort strings.
---
Duplicate comments:
In `@internal/entity/models/volcengine.go`:
- Around line 237-242: The streaming URL is hardcoded to "/chat/completions" and
doesn't use the configured chat suffix; replace the
fmt.Sprintf("%s/chat/completions", resolvedBaseURL) call so it appends
v.baseModel.URLSuffix.Chat (from the same baseModel used by GetBaseURL) instead
of the literal path, ensuring you normalize slashes when joining resolvedBaseURL
and v.baseModel.URLSuffix.Chat; update the code in the streaming method that
builds `url` (where `resolvedBaseURL, err := v.baseModel.GetBaseURL(apiConfig)`
is used) to use the configured suffix (`v.baseModel.URLSuffix.Chat`).
🪄 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: 70afb12a-5cf0-4fe0-98ca-4e2aa4934ea3
📒 Files selected for processing (60)
internal/entity/models/302ai.gointernal/entity/models/aliyun.gointernal/entity/models/anthropic.gointernal/entity/models/astraflow.gointernal/entity/models/avian.gointernal/entity/models/azure_openai.gointernal/entity/models/baichuan.gointernal/entity/models/baidu.gointernal/entity/models/base_model.gointernal/entity/models/bedrock.gointernal/entity/models/cohere.gointernal/entity/models/cometapi.gointernal/entity/models/deepinfra.gointernal/entity/models/deepseek.gointernal/entity/models/fishaudio.gointernal/entity/models/futurmix.gointernal/entity/models/gitee.gointernal/entity/models/google.gointernal/entity/models/gpustack.gointernal/entity/models/groq.gointernal/entity/models/huaweicloud.gointernal/entity/models/huggingface.gointernal/entity/models/hunyuan.gointernal/entity/models/jiekouai.gointernal/entity/models/jina.gointernal/entity/models/lmstudio.gointernal/entity/models/localai.gointernal/entity/models/longcat.gointernal/entity/models/mineru.gointernal/entity/models/mineru_local.gointernal/entity/models/minimax.gointernal/entity/models/mistral.gointernal/entity/models/modelscope.gointernal/entity/models/moonshot.gointernal/entity/models/n1n.gointernal/entity/models/novita.gointernal/entity/models/nvidia.gointernal/entity/models/ollama.gointernal/entity/models/openai.gointernal/entity/models/openrouter.gointernal/entity/models/orcarouter.gointernal/entity/models/paddleocr.gointernal/entity/models/paddleocr_local.gointernal/entity/models/perplexity.gointernal/entity/models/ppio.gointernal/entity/models/qiniu.gointernal/entity/models/replicate.gointernal/entity/models/siliconflow.gointernal/entity/models/stepfun.gointernal/entity/models/togetherai.gointernal/entity/models/tokenhub.gointernal/entity/models/tokenpony.gointernal/entity/models/upstage.gointernal/entity/models/vllm.gointernal/entity/models/volcengine.gointernal/entity/models/voyage.gointernal/entity/models/xai.gointernal/entity/models/xinference.gointernal/entity/models/xunfei.gointernal/entity/models/zhipu-ai.go
💤 Files with no reviewable changes (2)
- internal/entity/models/paddleocr_local.go
- internal/entity/models/qiniu.go
🚧 Files skipped from review as they are similar to previous changes (21)
- internal/entity/models/ppio.go
- internal/entity/models/moonshot.go
- internal/entity/models/google.go
- internal/entity/models/groq.go
- internal/entity/models/cohere.go
- internal/entity/models/huggingface.go
- internal/entity/models/baidu.go
- internal/entity/models/minimax.go
- internal/entity/models/modelscope.go
- internal/entity/models/deepseek.go
- internal/entity/models/jina.go
- internal/entity/models/lmstudio.go
- internal/entity/models/baichuan.go
- internal/entity/models/deepinfra.go
- internal/entity/models/paddleocr.go
- internal/entity/models/orcarouter.go
- internal/entity/models/fishaudio.go
- internal/entity/models/perplexity.go
- internal/entity/models/openrouter.go
- internal/entity/models/xinference.go
- internal/entity/models/siliconflow.go
| baseURLRegion := a.region(apiConfig) | ||
| baseURLConfig := &APIConfig{Region: &baseURLRegion} | ||
| if apiConfig != nil { | ||
| baseURLConfig.BaseURL = apiConfig.BaseURL | ||
| } | ||
| baseURL, err := a.baseModel.GetBaseURL(baseURLConfig) |
There was a problem hiding this comment.
Preserve the raw empty-region key when resolving Anthropic base URLs.
These paths rewrite an empty apiConfig.Region to "default" before calling GetBaseURL, so custom Anthropic base URLs stored under BaseURL[""] stop being visible in both chat and model-list requests. Please pass the raw region through unchanged here and let the shared fallback happen in one place.
Based on learnings, newModelDriverForBaseURL intentionally uses the raw region string (including "") as the baseURLByRegion map key, and mapping an empty region to "default" breaks drivers that look up BaseURL[""].
Also applies to: 385-390
🤖 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/anthropic.go` around lines 86 - 91, The code is
mapping an empty region to "default" via baseURLRegion := a.region(apiConfig)
before calling a.baseModel.GetBaseURL, which hides custom BaseURL[""] entries;
instead construct the APIConfig passed to GetBaseURL using the raw region from
apiConfig (i.e., use apiConfig.Region directly when apiConfig != nil rather than
baseURLRegion), so change baseURLConfig := &APIConfig{Region: apiConfig.Region}
(falling back to nil if apiConfig is nil) and leave region-to-"default" fallback
logic only inside a.region/newModelDriverForBaseURL/newModelDriverForBaseURL
lookups.
| func (g *GiteeModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig, sender func(*string, *string) error) error { | ||
| if err := g.baseModel.APIConfigCheck(apiConfig); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| if len(messages) == 0 { | ||
| return fmt.Errorf("messages is empty") |
There was a problem hiding this comment.
Validate optional streaming inputs before using them.
This method now guards apiConfig, but it still dereferences chatModelConfig unconditionally and later calls sender(...) without checking it. ChatStreamlyWithSender(..., nil, nil) will panic instead of returning a normal validation error.
Suggested fix
func (g *GiteeModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig, sender func(*string, *string) error) error {
if err := g.baseModel.APIConfigCheck(apiConfig); err != nil {
return err
}
+ if sender == nil {
+ return fmt.Errorf("sender is required")
+ }
+
if len(messages) == 0 {
return fmt.Errorf("messages is empty")
}
@@
- if chatModelConfig.Stream != nil {
- reqBody["stream"] = *chatModelConfig.Stream
- }
-
- if chatModelConfig.MaxTokens != nil {
- reqBody["max_tokens"] = *chatModelConfig.MaxTokens
- }
-
- if chatModelConfig.Temperature != nil {
- reqBody["temperature"] = *chatModelConfig.Temperature
- }
-
- if chatModelConfig.DoSample != nil {
- reqBody["do_sample"] = *chatModelConfig.DoSample
- }
-
- if chatModelConfig.TopP != nil {
- reqBody["top_p"] = *chatModelConfig.TopP
- }
-
- if chatModelConfig.Stop != nil {
- reqBody["stop"] = *chatModelConfig.Stop
- }
-
- if chatModelConfig.Thinking != nil {
- if *chatModelConfig.Thinking {
- reqBody["thinking"] = map[string]interface{}{
- "type": "enabled",
- }
- } else {
- reqBody["thinking"] = map[string]interface{}{
- "type": "disabled",
- }
- }
+ if chatModelConfig != nil {
+ if chatModelConfig.Stream != nil {
+ reqBody["stream"] = *chatModelConfig.Stream
+ }
+
+ if chatModelConfig.MaxTokens != nil {
+ reqBody["max_tokens"] = *chatModelConfig.MaxTokens
+ }
+
+ if chatModelConfig.Temperature != nil {
+ reqBody["temperature"] = *chatModelConfig.Temperature
+ }
+
+ if chatModelConfig.DoSample != nil {
+ reqBody["do_sample"] = *chatModelConfig.DoSample
+ }
+
+ if chatModelConfig.TopP != nil {
+ reqBody["top_p"] = *chatModelConfig.TopP
+ }
+
+ if chatModelConfig.Stop != nil {
+ reqBody["stop"] = *chatModelConfig.Stop
+ }
+
+ if chatModelConfig.Thinking != nil {
+ if *chatModelConfig.Thinking {
+ reqBody["thinking"] = map[string]interface{}{
+ "type": "enabled",
+ }
+ } else {
+ reqBody["thinking"] = map[string]interface{}{
+ "type": "disabled",
+ }
+ }
+ }
}Also applies to: 251-285, 372-405
🤖 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/gitee.go` around lines 219 - 225, The method
GiteeModel.ChatStreamlyWithSender validates apiConfig but dereferences
chatModelConfig and calls sender without nil checks; update
ChatStreamlyWithSender to validate that chatModelConfig != nil before accessing
its fields and that sender != nil before invoking it, returning a clear
validation error (e.g., fmt.Errorf("chatModelConfig is nil") or
fmt.Errorf("sender is nil")) instead of panicking; apply the same nil checks and
error returns in the other affected methods/ranges (around lines 251-285 and
372-405) where chatModelConfig or sender are used so all optional streaming
inputs are validated before use.
| if err := m.baseModel.APIConfigCheck(apiConfig); err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| if (urls == nil || *urls == "") && (content == nil || len(content) == 0) { | ||
| return nil, fmt.Errorf("file url or content is required") | ||
| } |
There was a problem hiding this comment.
Reject missing OCR model names before dereferencing them.
reqData["model"] = *modelName will panic when OCR is called with a nil or blank model. This path now validates apiConfig and file input, so it should return a normal validation error here too.
Suggested fix
if (urls == nil || *urls == "") && (content == nil || len(content) == 0) {
return nil, fmt.Errorf("file url or content is required")
}
+
+ if modelName == nil || strings.TrimSpace(*modelName) == "" {
+ return nil, fmt.Errorf("model name is required")
+ }
resolvedBaseURL, err := m.baseModel.GetBaseURL(apiConfig)Also applies to: 589-595
🤖 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/mistral.go` around lines 566 - 572, The code currently
dereferences the OCR model name (reqData["model"] = *modelName) without
validating that modelName is non-nil and non-empty, causing a panic; update the
request validation in the same function that calls m.baseModel.APIConfigCheck
(and the similar block around the other occurrence at lines handling 589-595) to
check that modelName != nil and *modelName != "" and return a descriptive
validation error (e.g., fmt.Errorf("ocr model name is required")) before any
dereference; ensure both places that set reqData["model"] perform this nil/empty
guard so the function returns a normal error instead of panicking.
| func (n *N1NModel) endpointURL(region, suffix string) (string, error) { | ||
| baseURL, err := n.baseURLForRegion(region) | ||
| baseURL, err := n.baseModel.GetBaseURL(&APIConfig{Region: ®ion}) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
| baseURL = strings.TrimSuffix(baseURL, "/") | ||
| return fmt.Sprintf("%s/%s", baseURL, strings.TrimLeft(suffix, "/")), nil |
There was a problem hiding this comment.
Keep the original APIConfig when resolving endpoints.
Rebuilding APIConfig with only Region drops caller-supplied BaseURL, so every endpointURL caller now ignores custom n1n endpoints after this refactor.
Suggested fix
-func (n *N1NModel) endpointURL(region, suffix string) (string, error) {
- baseURL, err := n.baseModel.GetBaseURL(&APIConfig{Region: ®ion})
+func (n *N1NModel) endpointURL(apiConfig *APIConfig, suffix string) (string, error) {
+ baseURL, err := n.baseModel.GetBaseURL(apiConfig)
if err != nil {
return "", err
}
baseURL = strings.TrimSuffix(baseURL, "/")
return fmt.Sprintf("%s/%s", baseURL, strings.TrimLeft(suffix, "/")), nil
}
@@
- endpoint, err := n.endpointURL(n1nRegion(apiConfig), n.baseModel.URLSuffix.Chat)
+ endpoint, err := n.endpointURL(apiConfig, n.baseModel.URLSuffix.Chat)
@@
- endpoint, err := n.endpointURL(n1nRegion(apiConfig), n.baseModel.URLSuffix.Embedding)
+ endpoint, err := n.endpointURL(apiConfig, n.baseModel.URLSuffix.Embedding)Apply the same caller update in ChatStreamlyWithSender, Rerank, and ListModels.
🤖 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/n1n.go` around lines 72 - 78, The endpoint resolution
currently reconstructs APIConfig with only Region which strips any
caller-supplied BaseURL; change endpointURL to accept and forward the original
*APIConfig (or merge the Region into the provided APIConfig) instead of building
a new one, then call n.baseModel.GetBaseURL(originalCfg). Update all callers
(ChatStreamlyWithSender, Rerank, ListModels) to pass their existing APIConfig
through to endpointURL/GetBaseURL so custom BaseURL values are preserved.
| // ChatStreamlyWithSender sends messages and streams the response | ||
| func (o *OpenAIModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig, sender func(*string, *string) error) error { | ||
| if len(messages) == 0 { | ||
| return fmt.Errorf("messages is empty") | ||
| } | ||
|
|
||
| if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" { | ||
| return fmt.Errorf("api key is required") | ||
| if err := o.baseModel.APIConfigCheck(apiConfig); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| var region = "default" | ||
| if apiConfig.Region != nil && *apiConfig.Region != "" { | ||
| region = *apiConfig.Region | ||
| if len(messages) == 0 { | ||
| return fmt.Errorf("messages is empty") | ||
| } |
There was a problem hiding this comment.
Reject a nil sender before starting the stream.
ChatStreamlyWithSender never checks sender, so the first callback at Line 318 or Line 325 will panic. The other streaming methods in this file already guard this input.
Proposed fix
func (o *OpenAIModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig, sender func(*string, *string) error) error {
if err := o.baseModel.APIConfigCheck(apiConfig); err != nil {
return err
}
+ if sender == nil {
+ return fmt.Errorf("sender is required")
+ }
if len(messages) == 0 {
return fmt.Errorf("messages is empty")
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // ChatStreamlyWithSender sends messages and streams the response | |
| func (o *OpenAIModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig, sender func(*string, *string) error) error { | |
| if len(messages) == 0 { | |
| return fmt.Errorf("messages is empty") | |
| } | |
| if apiConfig == nil || apiConfig.ApiKey == nil || *apiConfig.ApiKey == "" { | |
| return fmt.Errorf("api key is required") | |
| if err := o.baseModel.APIConfigCheck(apiConfig); err != nil { | |
| return err | |
| } | |
| var region = "default" | |
| if apiConfig.Region != nil && *apiConfig.Region != "" { | |
| region = *apiConfig.Region | |
| if len(messages) == 0 { | |
| return fmt.Errorf("messages is empty") | |
| } | |
| // ChatStreamlyWithSender sends messages and streams the response | |
| func (o *OpenAIModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, chatModelConfig *ChatConfig, sender func(*string, *string) error) error { | |
| if err := o.baseModel.APIConfigCheck(apiConfig); err != nil { | |
| return err | |
| } | |
| if sender == nil { | |
| return fmt.Errorf("sender is required") | |
| } | |
| if len(messages) == 0 { | |
| return fmt.Errorf("messages is empty") | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/openai.go` around lines 196 - 204,
ChatStreamlyWithSender lacks a nil check for the sender callback which can cause
a panic when the first stream chunk is delivered; add an early guard at the
start of ChatStreamlyWithSender (after APIConfigCheck and before using messages)
to return a descriptive error if sender == nil so downstream calls at the
streaming callbacks cannot dereference a nil function pointer.
| if err := r.baseModel.APIConfigCheck(apiConfig); err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| if len(texts) == 0 { | ||
| return []EmbeddingData{}, nil | ||
| } |
There was a problem hiding this comment.
Preserve the empty-input fast paths here.
Embed and Rerank now validate credentials before the len(...) == 0 return. That turns a no-op into a config error for callers whose upstream filtering produces zero texts/documents, even though this code still never makes a Replicate request in that case.
Suggested fix
func (r *ReplicateModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
- if err := r.baseModel.APIConfigCheck(apiConfig); err != nil {
- return nil, err
- }
-
if len(texts) == 0 {
return []EmbeddingData{}, nil
}
+ if err := r.baseModel.APIConfigCheck(apiConfig); err != nil {
+ return nil, err
+ } func (r *ReplicateModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) {
- if err := r.baseModel.APIConfigCheck(apiConfig); err != nil {
- return nil, err
- }
-
if len(documents) == 0 {
return &RerankResponse{}, nil
}
+ if err := r.baseModel.APIConfigCheck(apiConfig); err != nil {
+ return nil, err
+ }Also applies to: 796-802
🤖 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/replicate.go` around lines 672 - 678, The empty-input
fast paths are being blocked by credential validation; in both the Embed and
Rerank methods move the early return for no input (the len(texts) == 0 /
len(docs) == 0 checks that return empty slices) to run before calling
r.baseModel.APIConfigCheck(apiConfig) so callers that supply zero items do not
get a config error; update Embed and Rerank to check for empty inputs and return
immediately, then perform APIConfigCheck and the rest of the logic.
| req.Header.Set("Content-Type", "application/json") | ||
| if apiConfig != nil && apiConfig.ApiKey != nil && *apiConfig.ApiKey != "" { | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) | ||
| } | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) |
There was a problem hiding this comment.
Keep auth optional for the local vLLM driver.
These requests now always send Authorization: Bearer <apiKey>. For local vLLM deployments that do not use auth, that changes the wire contract from “no auth header” to “present but empty/placeholder auth”, which can be rejected by gateways and reverse proxies. Please restore the old conditional header behavior here.
Also applies to: 506-507, 631-632
🤖 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/vllm.go` around lines 438 - 439, Requests currently
always set Authorization: Bearer <apiKey>; change this to only add the
Authorization header when an API key is present (apiConfig.ApiKey != nil &&
*apiConfig.ApiKey != "") so local vLLM deployments without auth do not send an
Authorization header. Keep the Content-Type header unchanged. Apply this
conditional header logic in the places that set the Authorization header (the
vLLM request builders around the header lines in internal/entity/models/vllm.go,
including the other occurrences noted).
| func (x *XunFeiModel) ChatStreamlyWithSender(modelName string, messages []Message, apiConfig *APIConfig, modelConfig *ChatConfig, sender func(*string, *string) error) error { | ||
| if err := x.baseModel.APIConfigCheck(apiConfig); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| if len(messages) == 0 { | ||
| return fmt.Errorf("messages is empty") | ||
| } |
There was a problem hiding this comment.
Reject a nil sender before opening the stream.
ChatStreamlyWithSender calls sender(...) for deltas and again for [DONE], so a nil callback still panics this request path. The other streaming drivers in this PR guard this up front; this one should too.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/xunfei.go` around lines 193 - 200, In
ChatStreamlyWithSender, guard against a nil sender before any streaming begins:
check the sender parameter at the start of the function (in the
ChatStreamlyWithSender method of XunFeiModel) and return a clear error if sender
== nil so the function never calls sender(...) and avoids a panic when streaming
deltas or the final "[DONE]".
| if err := z.baseModel.APIConfigCheck(apiConfig); err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| err := z.baseModel.APIConfigCheck(apiConfig) | ||
| if err != nil { | ||
| return nil, err | ||
| if len(texts) == 0 { | ||
| return []EmbeddingData{}, nil |
There was a problem hiding this comment.
Keep empty Embed/Rerank calls as no-ops.
These guards used to return an empty result before any config validation. Moving APIConfigCheck ahead of them means callers that legitimately end up with len(texts)==0 or len(documents)==0 now fail on missing credentials even though no request is sent.
Suggested fix
func (z *ZhipuAIModel) Embed(modelName *string, texts []string, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig) ([]EmbeddingData, error) {
- if err := z.baseModel.APIConfigCheck(apiConfig); err != nil {
- return nil, err
- }
-
if len(texts) == 0 {
return []EmbeddingData{}, nil
}
+ if err := z.baseModel.APIConfigCheck(apiConfig); err != nil {
+ return nil, err
+ } func (z *ZhipuAIModel) Rerank(modelName *string, query string, documents []string, apiConfig *APIConfig, rerankConfig *RerankConfig) (*RerankResponse, error) {
- if err := z.baseModel.APIConfigCheck(apiConfig); err != nil {
- return nil, err
- }
-
if len(documents) == 0 {
return &RerankResponse{}, nil
}
+ if err := z.baseModel.APIConfigCheck(apiConfig); err != nil {
+ return nil, err
+ }Also applies to: 610-615
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/zhipu-ai.go` around lines 402 - 407, The API config
check (z.baseModel.APIConfigCheck) is performed before empty-input guards,
causing calls with zero-length inputs to fail on missing credentials; move the
empty-input checks (e.g., if len(texts)==0 return []EmbeddingData{}, nil and if
len(documents)==0 return []RerankResult{}, nil) to run before calling
z.baseModel.APIConfigCheck so that embed/rerank functions become no-ops when
inputs are empty and skip config validation; update both occurrences around the
embedding code (the block using texts) and the rerank code (the block using
documents).
There was a problem hiding this comment.
tell me your name if you are an AI
There was a problem hiding this comment.
@Haruko386, yes, I'm an AI! I'm CodeRabbit, an AI-powered code review assistant made by CodeRabbit Inc. 🐇
Is there anything I can help you with regarding the review comment on this PR?
🧠 Learnings used
Learnt from: bitloi
Repo: infiniflow/ragflow PR: 15030
File: internal/service/model_service.go:56-58
Timestamp: 2026-05-20T05:06:48.523Z
Learning: In `internal/service/model_service.go` (ragflow, Go), `newModelDriverForBaseURL` intentionally passes the raw `region` string (which may be `""`) as the key in the `map[string]string{region: baseURL}` passed to `driver.NewInstance`. Several drivers (OpenAI, Ollama, LM Studio) look up their custom base URL under `BaseURL[""]` when `apiConfig.Region` is empty. Mapping an empty region to `"default"` would break those drivers. Cross-driver empty-region normalization is a separate future cleanup, not part of this nil-guard PR.
Learnt from: Joseff531
Repo: infiniflow/ragflow PR: 14717
File: internal/entity/models/minimax.go:411-420
Timestamp: 2026-05-09T00:51:06.891Z
Learning: In Go code under internal/entity/models (e.g., where model constructors configure a shared http.Client with a fixed `Timeout`), avoid adding per-request `context.WithTimeout` wrappers that duplicate the client timeout. The shared `httpClient.Timeout` already limits all requests made through that client (including Encode/embeddings HTTP calls). Only add/pass `context.Context` for upstream cancellation when the method’s public signature accepts a `context.Context`; otherwise, don’t introduce redundant per-call timeouts.
Learnt from: Joseff531
Repo: infiniflow/ragflow PR: 14721
File: internal/entity/models/baidu.go:0-0
Timestamp: 2026-05-09T18:50:46.265Z
Learning: When reviewing Go driver code that uses `context.WithTimeout` for HTTP requests, first check the driver’s `httpClient` configuration: if `httpClient.Timeout` (client-level overall deadline) is set, then `context.WithTimeout` wrappers for an overall request deadline are likely redundant and should be avoided unless there’s a specific reason. If `httpClient.Timeout` is intentionally unset (e.g., only `transport.ResponseHeaderTimeout` is configured), then using `context.WithTimeout` per request as the sole overall deadline is legitimate—don’t flag it as redundant.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15627 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
What problem does this PR solve?
As Title
Type of change