Repository navigation
Go: implement provider: lm-studio - #14586
Conversation
📝 WalkthroughWalkthroughA new LMStudio model provider is added with full chat and streaming support, integrated into the factory, and Ollama model methods are refactored to use pointer receivers for consistency. ChangesLMStudio Provider Addition
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (2)
internal/entity/models/lmstudio.go (2)
39-53: 💤 Low valueDuplicate
http.Clientconstruction betweenNewLmStudioModelandNewInstance.The transport/timeout settings are repeated verbatim. Extracting a small helper (e.g.,
newLmStudioHTTPClient()) keeps the two paths in sync if the defaults ever change.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/lmstudio.go` around lines 39 - 53, The http.Client construction is duplicated between NewInstance and NewLmStudioModel; extract that common logic into a helper (e.g., newLmStudioHTTPClient) and have both NewInstance and NewLmStudioModel call it to build the client. Update LmStudioModel.NewInstance and the NewLmStudioModel constructor to remove the inline http.Client block and instead assign httpClient: newLmStudioHTTPClient(), keeping the same Timeout and Transport settings (MaxIdleConns, MaxIdleConnsPerHost, IdleConnTimeout, DisableCompression).
1-426: 🏗️ Heavy liftSignificant duplication with
ollama.go; consider extracting an OpenAI-compatible base driver.
ChatWithMessages,ChatStreamlyWithSender, andListModelshere are nearly identical to the Ollama driver — same payload shape, same SSE parsing, same response unpacking. Every fix to one (nil checks, error handling, scanner buffer, removal of qwen/glm detour, etc.) must be made in both places. Consider factoring the shared logic into an internal helper (e.g.,openAICompatibleChat(client, url, …)) that both drivers call, leaving only the per-provider differences (URL composition, headers, model-name quirks) in the wrappers.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/entity/models/lmstudio.go` around lines 1 - 426, Duplication: ChatWithMessages, ChatStreamlyWithSender, and ListModels in LmStudioModel duplicate the logic in ollama.go; extract a shared OpenAI-compatible helper to avoid drift. Create an internal helper (e.g., openAICompatibleChat and openAICompatibleStream, and openAICompatibleListModels) that encapsulates request JSON building, HTTP call, SSE parsing/scanner handling, response unmarshalling and error checks, and return a standardized result; then refactor LmStudioModel.ChatWithMessages, ChatStreamlyWithSender, and ListModels to call these helpers while keeping only provider-specific bits (URL selection, headers, model-name quirks like qwen/glm) in the wrapper; reference the existing symbols ChatWithMessages, ChatStreamlyWithSender, ListModels and ollama.go so the helpers can be used by both drivers.
🤖 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 `@conf/models/lmstudio.json`:
- Around line 3-6: The config is missing the async_chat suffix referenced by
URLSuffix.AsyncChat (causing an empty request path for qwen-/glm-prefixed
models) — either add "async_chat": "chat/completions" (or the proper endpoint)
to conf/models/lmstudio.json to populate URLSuffix.AsyncChat, or better: remove
the qwen/glm detour in internal/entity/models/lmstudio.go so the driver no
longer sets/uses URLSuffix.AsyncChat (look for the branches that reference
URLSuffix.AsyncChat and the qwen/glm model-name checks around the routing logic)
and let those models use the regular chat suffix instead.
In `@internal/entity/models/lmstudio.go`:
- Line 140: The code unconditionally dereferences apiConfig.ApiKey when setting
the Authorization header, which will panic if ApiKey == nil; update each site
(the req.Header.Set call at line 140 and the analogous calls inside
ChatStreamlyWithSender and ListModels) to first check that apiConfig.ApiKey !=
nil and only call req.Header.Set("Authorization", fmt.Sprintf("Bearer %s",
*apiConfig.ApiKey)) when a key exists, otherwise skip adding the header.
- Around line 72-76: The branch that special-cases modelType :=
strings.Split(modelName, "-")[0] for "qwen" or "glm" and switches url to
l.URLSuffix.AsyncChat must be removed because LM Studio uses a single
OpenAI-compatible chat endpoint and conf/models/lmstudio.json does not define
AsyncChat; update both ChatWithMessages and ChatStreamlyWithSender by deleting
the qwen/glm conditional and ensure the code always constructs the URL using the
LM Studio chat completions suffix (the existing l.URLSuffix.ChatCompletions /
default chat endpoint logic) so the URL does not collapse to "<base>/".
- Around line 95-127: The code guards building reqBody with "if chatModelConfig
!= nil" but later calls GetThinkingAndAnswer(chatModelConfig.ModelClass, ...)
without checking for nil, which can panic; fix by either validating
chatModelConfig at the start of the function and returning an error if nil (make
the parameter required), or provide a safe fallback ModelClass when
chatModelConfig is nil before calling GetThinkingAndAnswer (e.g., set a local
variable modelClass := defaultModelClass; if chatModelConfig != nil { modelClass
= chatModelConfig.ModelClass } and use modelClass), and ensure any other
dereferences of chatModelConfig follow the same nil-safe pattern (references:
chatModelConfig, GetThinkingAndAnswer).
- Around line 287-290: The bufio.Scanner created as scanner :=
bufio.NewScanner(resp.Body) can truncate long SSE lines; update the code that
processes resp.Body (where scanner is created and used) to handle larger tokens
by either calling scanner.Buffer with a bigger max token size (e.g., bump from
64KiB to ~1MiB) before the Scan loop, or replace the scanner loop with a
bufio.Reader and use ReadString('\n') to read full lines and handle
bufio.ErrTooLong/other errors appropriately; ensure you preserve existing logic
that logs each line (common.Info) and properly closes resp.Body and handles
EOF/errors.
- Around line 153-155: The error construction in the API response handling
includes user-supplied data (messages[0].Content); remove that portion so errors
don't leak PII or secrets. Update the fmt.Errorf call in the block that checks
resp.StatusCode != http.StatusOK to only include the status code and response
body (resp.StatusCode and body) and drop the trailing ":%s" and
messages[0].Content argument.
- Around line 226-260: The code dereferences fields on modelConfig (e.g.,
*modelConfig.Stream, *modelConfig.MaxTokens, *modelConfig.Temperature,
*modelConfig.DoSample, *modelConfig.TopP, *modelConfig.Stop,
*modelConfig.Thinking) without checking modelConfig for nil; wrap the entire
block in a single nil-check (if modelConfig != nil) like ChatWithMessages does,
then move the existing per-field nil checks inside that guard so callers using a
nil modelConfig won't panic while preserving the current field-handling logic.
- Around line 408-414: The code in lmstudio.go currently uses unchecked type
assertions on result["data"], each model entry, and modelMap["id"] which will
panic on missing or unexpected shapes; update the loop that builds models (where
result["data"].([]interface{}) and model.(map[string]interface{}) and
modelMap["id"].(string) are used) to perform safe type assertions using the
"value, ok := ..." form, skip entries that don't match the expected types, and
return or propagate a clear error if the outer result["data"] is missing or not
a slice; ensure the models slice is only appended with validated string ids and
add appropriate error messages when returning from the enclosing function.
---
Nitpick comments:
In `@internal/entity/models/lmstudio.go`:
- Around line 39-53: The http.Client construction is duplicated between
NewInstance and NewLmStudioModel; extract that common logic into a helper (e.g.,
newLmStudioHTTPClient) and have both NewInstance and NewLmStudioModel call it to
build the client. Update LmStudioModel.NewInstance and the NewLmStudioModel
constructor to remove the inline http.Client block and instead assign
httpClient: newLmStudioHTTPClient(), keeping the same Timeout and Transport
settings (MaxIdleConns, MaxIdleConnsPerHost, IdleConnTimeout,
DisableCompression).
- Around line 1-426: Duplication: ChatWithMessages, ChatStreamlyWithSender, and
ListModels in LmStudioModel duplicate the logic in ollama.go; extract a shared
OpenAI-compatible helper to avoid drift. Create an internal helper (e.g.,
openAICompatibleChat and openAICompatibleStream, and openAICompatibleListModels)
that encapsulates request JSON building, HTTP call, SSE parsing/scanner
handling, response unmarshalling and error checks, and return a standardized
result; then refactor LmStudioModel.ChatWithMessages, ChatStreamlyWithSender,
and ListModels to call these helpers while keeping only provider-specific bits
(URL selection, headers, model-name quirks like qwen/glm) in the wrapper;
reference the existing symbols ChatWithMessages, ChatStreamlyWithSender,
ListModels and ollama.go so the helpers can be used by both drivers.
🪄 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: 1c7c8cd9-1e9c-4a27-a01b-f5a6abd692ef
📒 Files selected for processing (4)
conf/models/lmstudio.jsoninternal/entity/models/factory.gointernal/entity/models/lmstudio.gointernal/entity/models/ollama.go
| "url_suffix": { | ||
| "chat": "chat/completions", | ||
| "models": "models" | ||
| }, |
There was a problem hiding this comment.
Missing async_chat URL suffix referenced by the driver.
internal/entity/models/lmstudio.go (lines 75 and 207) routes any model name starting with qwen or glm to l.URLSuffix.AsyncChat, but this config only declares chat and models. With the field unset, URLSuffix.AsyncChat is the empty string and the request URL becomes "<base>/", which will fail at runtime for every qwen-/glm-prefixed model name a user picks.
LM Studio is a local OpenAI-compatible server and does not have a separate async chat endpoint, so the cleaner fix is to drop the qwen/glm detour from the driver entirely (see the related comment in lmstudio.go). If you do intend to keep the branch, add the corresponding async_chat entry here.
🤖 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 `@conf/models/lmstudio.json` around lines 3 - 6, The config is missing the
async_chat suffix referenced by URLSuffix.AsyncChat (causing an empty request
path for qwen-/glm-prefixed models) — either add "async_chat":
"chat/completions" (or the proper endpoint) to conf/models/lmstudio.json to
populate URLSuffix.AsyncChat, or better: remove the qwen/glm detour in
internal/entity/models/lmstudio.go so the driver no longer sets/uses
URLSuffix.AsyncChat (look for the branches that reference URLSuffix.AsyncChat
and the qwen/glm model-name checks around the routing logic) and let those
models use the regular chat suffix instead.
| // For qwen/glm models, use async chat endpoint | ||
| modelType := strings.Split(modelName, "-")[0] | ||
| if modelType == "qwen" || modelType == "glm" { | ||
| url = fmt.Sprintf("%s/%s", l.BaseURL[region], l.URLSuffix.AsyncChat) | ||
| } |
There was a problem hiding this comment.
qwen/glm async-chat routing does not fit LM Studio and uses an unset URLSuffix.AsyncChat.
This branch is copy-pasted from the Ollama driver. conf/models/lmstudio.json does not define async_chat, so for any model whose name starts with qwen- or glm- the URL collapses to "<base>/" and the request will fail. LM Studio exposes a single OpenAI-compatible /chat/completions endpoint regardless of the underlying model family, so this special case should simply be removed in both ChatWithMessages and ChatStreamlyWithSender.
🐛 Proposed fix
url := fmt.Sprintf("%s/%s", l.BaseURL[region], l.URLSuffix.Chat)
-
- // For qwen/glm models, use async chat endpoint
- modelType := strings.Split(modelName, "-")[0]
- if modelType == "qwen" || modelType == "glm" {
- url = fmt.Sprintf("%s/%s", l.BaseURL[region], l.URLSuffix.AsyncChat)
- }(Same change at lines 205–208.)
Also applies to: 204-208
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/lmstudio.go` around lines 72 - 76, The branch that
special-cases modelType := strings.Split(modelName, "-")[0] for "qwen" or "glm"
and switches url to l.URLSuffix.AsyncChat must be removed because LM Studio uses
a single OpenAI-compatible chat endpoint and conf/models/lmstudio.json does not
define AsyncChat; update both ChatWithMessages and ChatStreamlyWithSender by
deleting the qwen/glm conditional and ensure the code always constructs the URL
using the LM Studio chat completions suffix (the existing
l.URLSuffix.ChatCompletions / default chat endpoint logic) so the URL does not
collapse to "<base>/".
| 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.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", | ||
| } | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
chatModelConfig is treated as optional at line 95 but unconditionally dereferenced at line 183.
The body-building block guards if chatModelConfig != nil, yet GetThinkingAndAnswer(chatModelConfig.ModelClass, …) later assumes it is non-nil. A caller passing nil (consistent with the apparent intent of the earlier guard) will panic with a nil pointer dereference. Either require the parameter to be non-nil up front (and document it) or fall back to a default ModelClass when it is nil.
🐛 Proposed fix
- thinking, answer := GetThinkingAndAnswer(chatModelConfig.ModelClass, &content)
+ var modelClass string
+ if chatModelConfig != nil {
+ modelClass = chatModelConfig.ModelClass
+ }
+ thinking, answer := GetThinkingAndAnswer(modelClass, &content)Also applies to: 183-188
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/lmstudio.go` around lines 95 - 127, The code guards
building reqBody with "if chatModelConfig != nil" but later calls
GetThinkingAndAnswer(chatModelConfig.ModelClass, ...) without checking for nil,
which can panic; fix by either validating chatModelConfig at the start of the
function and returning an error if nil (make the parameter required), or provide
a safe fallback ModelClass when chatModelConfig is nil before calling
GetThinkingAndAnswer (e.g., set a local variable modelClass :=
defaultModelClass; if chatModelConfig != nil { modelClass =
chatModelConfig.ModelClass } and use modelClass), and ensure any other
dereferences of chatModelConfig follow the same nil-safe pattern (references:
chatModelConfig, GetThinkingAndAnswer).
| } | ||
|
|
||
| req.Header.Set("Content-Type", "application/json") | ||
| req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) |
There was a problem hiding this comment.
Unconditional *apiConfig.ApiKey dereference will panic against LM Studio.
LM Studio is a local OpenAI-compatible server and does not require an API key by default; users routinely leave it unset. *apiConfig.ApiKey (and the analogous lines in ChatStreamlyWithSender at 273 and ListModels at 385) will nil-deref when ApiKey == nil. Guard each call and only set the Authorization header when a key is actually configured.
🛡️ Proposed fix (apply at all three sites)
req.Header.Set("Content-Type", "application/json")
- req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
+ if apiConfig.ApiKey != nil && *apiConfig.ApiKey != "" {
+ req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey))
+ }Also applies to: 273-273, 385-385
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/lmstudio.go` at line 140, The code unconditionally
dereferences apiConfig.ApiKey when setting the Authorization header, which will
panic if ApiKey == nil; update each site (the req.Header.Set call at line 140
and the analogous calls inside ChatStreamlyWithSender and ListModels) to first
check that apiConfig.ApiKey != nil and only call req.Header.Set("Authorization",
fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) when a key exists, otherwise skip
adding the header.
| if resp.StatusCode != http.StatusOK { | ||
| return nil, fmt.Errorf("API request failed with status %d: %s :%s", resp.StatusCode, string(body), messages[0].Content) | ||
| } |
There was a problem hiding this comment.
Don't include user-supplied message content in returned errors.
messages[0].Content is appended to the error string, which can contain arbitrary user input (PII, prompts, secrets). This propagates outward into application logs and any caller that surfaces the error. Drop the trailing :%s and the messages[0].Content argument; the status code and response body are sufficient for diagnostics.
🛡️ Proposed fix
- return nil, fmt.Errorf("API request failed with status %d: %s :%s", resp.StatusCode, string(body), messages[0].Content)
+ return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))📝 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.
| if resp.StatusCode != http.StatusOK { | |
| return nil, fmt.Errorf("API request failed with status %d: %s :%s", resp.StatusCode, string(body), messages[0].Content) | |
| } | |
| if resp.StatusCode != http.StatusOK { | |
| return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, 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/lmstudio.go` around lines 153 - 155, The error
construction in the API response handling includes user-supplied data
(messages[0].Content); remove that portion so errors don't leak PII or secrets.
Update the fmt.Errorf call in the block that checks resp.StatusCode !=
http.StatusOK to only include the status code and response body (resp.StatusCode
and body) and drop the trailing ":%s" and messages[0].Content argument.
| 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", | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
modelConfig is never nil-checked but each field is dereferenced.
Unlike ChatWithMessages, this method has no if modelConfig != nil guard before *modelConfig.Stream, *modelConfig.MaxTokens, etc. Any caller invoking the streaming path with a nil config will panic. Wrap the field accesses in a single nil guard for symmetry with ChatWithMessages.
🐛 Proposed fix
- if modelConfig.Stream != nil {
- reqBody["stream"] = *modelConfig.Stream
- }
- ...
- if modelConfig.Thinking != nil {
+ if modelConfig != nil {
+ if modelConfig.Stream != nil {
+ reqBody["stream"] = *modelConfig.Stream
+ }
+ // ... existing field checks ...
+ if modelConfig.Thinking != nil {
...
+ }
+ }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/lmstudio.go` around lines 226 - 260, The code
dereferences fields on modelConfig (e.g., *modelConfig.Stream,
*modelConfig.MaxTokens, *modelConfig.Temperature, *modelConfig.DoSample,
*modelConfig.TopP, *modelConfig.Stop, *modelConfig.Thinking) without checking
modelConfig for nil; wrap the entire block in a single nil-check (if modelConfig
!= nil) like ChatWithMessages does, then move the existing per-field nil checks
inside that guard so callers using a nil modelConfig won't panic while
preserving the current field-handling logic.
| scanner := bufio.NewScanner(resp.Body) | ||
| for scanner.Scan() { | ||
| line := scanner.Text() | ||
| common.Info(line) |
There was a problem hiding this comment.
bufio.Scanner default buffer can truncate long SSE lines.
Default MaxScanTokenSize is 64 KiB. LM Studio chat completion streams are typically small per delta, but a single data: frame containing a large reasoning block or a coalesced chunk will return bufio.ErrTooLong and abort the stream. Either raise the buffer (scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)) or use bufio.Reader.ReadString('\n').
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/lmstudio.go` around lines 287 - 290, The bufio.Scanner
created as scanner := bufio.NewScanner(resp.Body) can truncate long SSE lines;
update the code that processes resp.Body (where scanner is created and used) to
handle larger tokens by either calling scanner.Buffer with a bigger max token
size (e.g., bump from 64KiB to ~1MiB) before the Scan loop, or replace the
scanner loop with a bufio.Reader and use ReadString('\n') to read full lines and
handle bufio.ErrTooLong/other errors appropriately; ensure you preserve existing
logic that logs each line (common.Info) and properly closes resp.Body and
handles EOF/errors.
| // convert result["data"] 2 []map[string]interface{} | ||
| models := make([]string, 0) | ||
| for _, model := range result["data"].([]interface{}) { | ||
| modelMap := model.(map[string]interface{}) | ||
| modelName := modelMap["id"].(string) | ||
| models = append(models, modelName) | ||
| } |
There was a problem hiding this comment.
Unchecked type assertions on the models response will panic on errors or shape changes.
result["data"].([]interface{}), model.(map[string]interface{}), and modelMap["id"].(string) all panic if the field is missing, nil, or has a different type — exactly what happens when LM Studio returns an error envelope or when an entry lacks an id. Use the value, ok := … form and skip/return errors gracefully.
🛡️ Proposed fix
- // convert result["data"] 2 []map[string]interface{}
- models := make([]string, 0)
- for _, model := range result["data"].([]interface{}) {
- modelMap := model.(map[string]interface{})
- modelName := modelMap["id"].(string)
- models = append(models, modelName)
- }
+ data, ok := result["data"].([]interface{})
+ if !ok {
+ return nil, fmt.Errorf("invalid models response: missing data field")
+ }
+ models := make([]string, 0, len(data))
+ for _, m := range data {
+ modelMap, ok := m.(map[string]interface{})
+ if !ok {
+ continue
+ }
+ if id, ok := modelMap["id"].(string); ok {
+ models = append(models, id)
+ }
+ }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/entity/models/lmstudio.go` around lines 408 - 414, The code in
lmstudio.go currently uses unchecked type assertions on result["data"], each
model entry, and modelMap["id"] which will panic on missing or unexpected
shapes; update the loop that builds models (where result["data"].([]interface{})
and model.(map[string]interface{}) and modelMap["id"].(string) are used) to
perform safe type assertions using the "value, ok := ..." form, skip entries
that don't match the expected types, and return or propagate a clear error if
the outer result["data"] is missing or not a slice; ensure the models slice is
only appended with validated string ids and add appropriate error messages when
returning from the enclosing function.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14586 +/- ##
=======================================
Coverage 94.16% 94.16%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 662 662
Misses 25 25
Partials 16 16 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
### What problem does this PR solve? Add a Go driver for OpenAI (GPT models). The config file conf/models/openai.json has been in the repo for a while with the full GPT-5 model list, but internal/entity/models/factory.go had no case for "openai". So any tenant that configured OpenAI as a model provider in the Go layer fell through to the default branch and got the dummy driver. Chat, list models, and check connection all returned dummy responses instead of reaching the API. OpenAI is the most commonly requested provider and the JSON config already ships with the repo, so this gap is high impact even though the JSON has been there for some time. ### What this PR includes - New file internal/entity/models/openai.go with an OpenAIModel that implements the ModelDriver interface. - factory.go: route the "openai" provider name to NewOpenAIModel. - conf/models/openai.json: add "models": "models" under url_suffix so ListModels can hit /v1/models with no hardcoded fallback. ### How the driver works - OpenAI exposes the canonical OpenAI-compatible API at https://api.openai.com/v1. - ChatWithMessages and ChatStreamlyWithSender post to /chat/completions in the same shape the moonshot, vllm, and xai drivers use. - ListModels and CheckConnection call /models to list available ids and confirm the API key works. - reasoning_content is passed through for the o-series and other reasoning models, in both the non-stream and stream paths. - Encode (embeddings) is left as "not implemented" for now, the same way the other recent provider drivers do it. Rerank and Balance are not part of OpenAI's public API surface in this layer and return a clear "not implemented" or "no such method" error. ### Type of change - [x] New Feature (non-breaking change which adds functionality) ### How was this tested? - go build ./internal/entity/models/... in a clean go 1.25 image (the go.mod minimum) returns exit 0 with no errors. - Method set of OpenAIModel matches the ModelDriver interface: NewInstance, Name, ChatWithMessages, ChatStreamlyWithSender, Encode, Rerank, ListModels, Balance, CheckConnection. - Pattern parity with the merged moonshot (#14433), volcengine (#14460), minimax (#14478), vllm (#14532), xai (#14550), and lm-studio (#14586) PRs. Closes #14604
### What problem does this PR solve? Add a Go driver for OpenAI (GPT models). The config file conf/models/openai.json has been in the repo for a while with the full GPT-5 model list, but internal/entity/models/factory.go had no case for "openai". So any tenant that configured OpenAI as a model provider in the Go layer fell through to the default branch and got the dummy driver. Chat, list models, and check connection all returned dummy responses instead of reaching the API. OpenAI is the most commonly requested provider and the JSON config already ships with the repo, so this gap is high impact even though the JSON has been there for some time. ### What this PR includes - New file internal/entity/models/openai.go with an OpenAIModel that implements the ModelDriver interface. - factory.go: route the "openai" provider name to NewOpenAIModel. - conf/models/openai.json: add "models": "models" under url_suffix so ListModels can hit /v1/models with no hardcoded fallback. ### How the driver works - OpenAI exposes the canonical OpenAI-compatible API at https://api.openai.com/v1. - ChatWithMessages and ChatStreamlyWithSender post to /chat/completions in the same shape the moonshot, vllm, and xai drivers use. - ListModels and CheckConnection call /models to list available ids and confirm the API key works. - reasoning_content is passed through for the o-series and other reasoning models, in both the non-stream and stream paths. - Encode (embeddings) is left as "not implemented" for now, the same way the other recent provider drivers do it. Rerank and Balance are not part of OpenAI's public API surface in this layer and return a clear "not implemented" or "no such method" error. ### Type of change - [x] New Feature (non-breaking change which adds functionality) ### How was this tested? - go build ./internal/entity/models/... in a clean go 1.25 image (the go.mod minimum) returns exit 0 with no errors. - Method set of OpenAIModel matches the ModelDriver interface: NewInstance, Name, ChatWithMessages, ChatStreamlyWithSender, Encode, Rerank, ListModels, Balance, CheckConnection. - Pattern parity with the merged moonshot (infiniflow#14433), volcengine (infiniflow#14460), minimax (infiniflow#14478), vllm (infiniflow#14532), xai (infiniflow#14550), and lm-studio (infiniflow#14586) PRs. Closes infiniflow#14604
What problem does this PR solve?
implement
lm-studioproviderType of change