Skip to content

Update create model instance command - #14441

Merged
JinHai-CN merged 7 commits into
infiniflow:mainfrom
JinHai-CN:fix406
Apr 29, 2026
Merged

JinHai-CN merged 7 commits into
infiniflow:mainfrom
JinHai-CN:fix406

Conversation

@JinHai-CN

@JinHai-CN JinHai-CN commented Apr 28, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

  1. support command:
RAGFlow(user)> create provider 'vllm' instance 'test' key 'test-key' url 'base-url' region 'abc';
SUCCESS
RAGFlow(user)> list instances from 'vllm';
+----------+----------------------------------------+----------------------------------+--------------+----------------------------------+--------+
| apiKey   | extra                                  | id                               | instanceName | providerID                       | status |
+----------+----------------------------------------+----------------------------------+--------------+----------------------------------+--------+
| test-key | {"base_url":"base-url","region":"abc"} | 40213c89430311f1a7cf38a74640adcc | test         | b4d40e6142d311f1a4f938a74640adcc | enable |
+----------+----------------------------------------+----------------------------------+--------------+----------------------------------+--------+
  1. support add vllm model
RAGFlow(user)> add model 'Qwen/Qwen2-0.5B' to provider 'vllm' instance 'test' with tokens 131072 chat;
SUCCESS
  1. add vllm chat

Type of change

  • New Feature (non-breaking change which adds functionality)
  • Refactoring

@coderabbitai

coderabbitai Bot commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR introduces support for vLLM (a local model serving framework) and enables custom model registration within provider instances. It adds CLI commands for model creation, extends the model driver interface with instance factories, implements the vLLM driver, and updates service-layer logic to handle local-deployed models.

Changes

Cohort / File(s) Summary
vLLM Configuration & Model Driver
conf/models/vllm.json, internal/entity/models/vllm.go
Introduces vLLM model configuration and a complete driver implementation with HTTP request handling, response parsing, thinking-content extraction, and Bearer token authentication for chat operations.
Model Driver Interface & Factory
internal/entity/models/types.go, internal/entity/models/factory.go, internal/entity/models/{aliyun,deepseek,dummy,gitee,google,minimax,moonshot,siliconflow,volcengine,zhipu-ai}.go
Extends ModelDriver interface with NewInstance method; adds vLLM case to factory switch; implements stubbed NewInstance methods across ten existing model drivers (returning nil).
CLI Lexer & Token Types
internal/cli/lexer.go, internal/cli/types.go
Adds recognition of REGION and URL keywords in CLI lexer; defines new TokenRegion and TokenURL token types.
CLI Command Parsing
internal/cli/user_parser.go
Adds parseAddModel function for new ADD MODEL command syntax; extends CREATE PROVIDER INSTANCE parsing to support optional URL and REGION tokens; enforces mutually-exclusive model-type options and validates duplicate directives.
CLI Command Execution
internal/cli/client.go, internal/cli/user_command.go
Routes add_custom_model command to new AddCustomModel handler; extends CreateProviderInstance to include base_url and region in request payload; implements full AddCustomModel command with validation and HTTP POST.
HTTP Client Configuration
internal/cli/http_client.go
Increases HTTP client timeout from 60 to 300 seconds.
API Handler & Routing
internal/handler/providers.go, internal/router/router.go
Adds AddCustomModel HTTP endpoint handler with request validation; updates CreateProviderInstanceRequest to include base_url and region fields; wires POST /:provider_name/instances/:instance_name/models route.
Service Layer
internal/service/model_service.go
Extends CreateProviderInstance to persist baseURL and region in instance metadata; refactors model listing to include active tenant models; adds ChatToModel logic for local-deployed models with instance-based routing; implements AddCustomModel service method with validation and custom model persistence.
Model Listing
internal/entity/model.go
Removes "features" field from ListModels response; renames local slice from models to modelList.

Sequence Diagram

sequenceDiagram
    participant User as User
    participant CLI as CLI Parser
    participant Handler as HTTP Handler
    participant Service as Model Service
    participant DAO as Database Layer
    participant Driver as Model Driver

    User->>CLI: add_custom_model provider instance model
    CLI->>Handler: POST /provider/instance/models
    Handler->>Service: AddCustomModel(request)
    Service->>DAO: Check provider exists
    DAO-->>Service: Provider found
    Service->>DAO: Check instance exists
    DAO-->>Service: Instance found
    Service->>DAO: Check model not already registered
    DAO-->>Service: Model availability confirmed
    Service->>DAO: Create tenant model with metadata
    DAO-->>Service: Model created
    Service-->>Handler: Success response
    Handler-->>CLI: Response with result code
    CLI-->>User: Command result
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 A vLLM hops into the warren with pride,
Custom models now register far and wide,
With tokens new and timeouts now long,
The driver ecosystem grows strong! 🌟
twitches nose ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Update create model instance command' is partially related to the changeset but does not capture the main additions: vllm provider support and custom model registration.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The PR description provides a clear problem statement with concrete command examples, identifies the new feature and refactoring changes, but lacks detail on implementation approach and broader context.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@JinHai-CN JinHai-CN added the ci Continue Integration label Apr 29, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review April 29, 2026 07:49
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code 💞 feature Feature request, pull request that fullfill a new feature. labels Apr 29, 2026
@codecov

codecov Bot commented Apr 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.30%. Comparing base (decf673) to head (4e8c35e).
⚠️ Report is 7 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14441   +/-   ##
=======================================
  Coverage   95.30%   95.30%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          670      670           
  Misses         16       16           
  Partials       17       17           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 11

Caution

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

⚠️ Outside diff range comments (2)
internal/service/model_service.go (1)

296-303: ⚠️ Potential issue | 🟠 Major

Return parsed extra metadata, not the raw JSON string.

The code already unmarshals instance.Extra, but the response puts the original JSON string back under "extra". That forces every client to decode it a second time and makes base_url / region harder to consume.

📦 Proposed fix
 		result = append(result, map[string]interface{}{
 			"id":           instance.ID,
 			"instanceName": instance.InstanceName,
 			"providerID":   instance.ProviderID,
 			"apiKey":       instance.APIKey,
 			"status":       instance.Status,
-			"extra":        instance.Extra,
+			"extra":        extra,
 		})
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/model_service.go` around lines 296 - 303, The response
currently returns the raw JSON string at "extra" instead of the parsed object;
update the append call in the block that builds the result (the map appended to
result for each instance) to set "extra" to the unmarshaled value (the parsed
variable used when decoding instance.Extra) instead of instance.Extra, and
ensure you handle/unset parse errors (e.g., default to nil or an empty map) so
clients receive a parsed JSON object for fields like base_url/region.
internal/cli/user_parser.go (1)

1392-1431: ⚠️ Potential issue | 🟠 Major

Parse URL and REGION in a loop instead of assuming a fixed order.

Right now only URL ... REGION ... is handled. REGION ... URL ... is accepted but misparsed because the parser reads REGION once, then skips the following URL token during the final p.nextToken().

🔧 Suggested structure
-	baseURL := ""
-	if p.curToken.Type == TokenURL {
-		p.nextToken()
-		baseURL, err = p.parseQuotedString()
-		if err != nil {
-			return nil, fmt.Errorf("expected base URL: %w", err)
-		}
-		p.nextToken()
-	}
-
-	region := ""
-	if p.curToken.Type == TokenRegion {
-		p.nextToken()
-		region, err = p.parseQuotedString()
-		if err != nil {
-			return nil, fmt.Errorf("expected base URL: %w", err)
-		}
-		p.nextToken()
-	}
+	baseURL := ""
+	region := ""
+	for p.curToken.Type == TokenURL || p.curToken.Type == TokenRegion {
+		switch p.curToken.Type {
+		case TokenURL:
+			if baseURL != "" {
+				return nil, fmt.Errorf("URL already specified")
+			}
+			p.nextToken()
+			baseURL, err = p.parseQuotedString()
+			if err != nil {
+				return nil, fmt.Errorf("expected base URL: %w", err)
+			}
+			p.nextToken()
+		case TokenRegion:
+			if region != "" {
+				return nil, fmt.Errorf("REGION already specified")
+			}
+			p.nextToken()
+			region, err = p.parseQuotedString()
+			if err != nil {
+				return nil, fmt.Errorf("expected region: %w", err)
+			}
+			p.nextToken()
+		}
+	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/cli/user_parser.go` around lines 1392 - 1431, The parser currently
assumes URL then REGION and calls p.nextToken() incorrectly causing the second
option to be skipped; replace the sequential parse with a loop that consumes any
number/order of TokenURL and TokenRegion tokens: while p.curToken.Type is
TokenURL or TokenRegion, switch on the token type, call p.nextToken(), parse the
quoted string via parseQuotedString() (returning error with the correct message
for each case), set baseURL or region accordingly, and do not call an extra
p.nextToken() after the loop that would skip the following token; keep the
existing logic that sets region = instanceName when baseURL is set and region is
empty, and preserve the semicolon handling and
NewCommand("create_provider_instance") param population.
♻️ Duplicate comments (6)
internal/entity/models/google.go (1)

41-43: ⚠️ Potential issue | 🟠 Major

Same NewInstance stub needs a real implementation.

Returning nil leaves this driver unusable on the new instance path. Please return a cloned GoogleModel with the overridden BaseURL.

Suggested fix
 func (z *GoogleModel) NewInstance(baseURL map[string]string) ModelDriver {
-	return nil
+	return &GoogleModel{
+		BaseURL:   baseURL,
+		URLSuffix: z.URLSuffix,
+	}
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/google.go` around lines 41 - 43, Implement
GoogleModel.NewInstance to return a cloned GoogleModel with BaseURL overridden
instead of nil; create a shallow copy of the receiver (z) and set its BaseURL
field to the provided baseURL map, then return the copy as ModelDriver (e.g.,
newZ := *z; newZ.BaseURL = baseURL; return &newZ) so the driver is usable via
the NewInstance path.
internal/entity/models/zhipu-ai.go (1)

55-57: ⚠️ Potential issue | 🟠 Major

Same NewInstance stub needs a real implementation.

Returning nil leaves this driver unusable on the new instance path. Please return a cloned ZhipuAIModel with the overridden BaseURL.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/zhipu-ai.go` around lines 55 - 57, Implement
ZhipuAIModel.NewInstance so it returns a cloned *ZhipuAIModel (satisfying
ModelDriver) with its BaseURL overridden by the provided baseURL map instead of
nil; locate the NewInstance method on type ZhipuAIModel and create a shallow
copy (copy fields or use value copy) of the receiver, set the
newInstance.BaseURL = baseURL (or merge as appropriate), and return the new
instance so callers get a usable driver.
internal/entity/models/moonshot.go (1)

55-57: ⚠️ Potential issue | 🟠 Major

Same NewInstance stub needs a real implementation.

Returning nil leaves this driver unusable on the new instance path. Please return a cloned MoonshotModel with the overridden BaseURL.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/moonshot.go` around lines 55 - 57, The NewInstance
method currently returns nil; implement it to return a cloned MoonshotModel that
satisfies ModelDriver with its BaseURL replaced by the provided baseURL map.
Locate the MoonshotModel type and implement NewInstance(baseURL
map[string]string) ModelDriver to create a shallow copy of the receiver
(preserving other fields) then set copy.BaseURL = baseURL (or deep-copy if
BaseURL must not alias) and return the copy as a ModelDriver so the new instance
uses the overridden BaseURL.
internal/entity/models/gitee.go (1)

55-57: ⚠️ Potential issue | 🟠 Major

Same NewInstance stub needs a real implementation.

Returning nil leaves this driver unusable on the new instance path. Please return a cloned GiteeModel with the overridden BaseURL.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/gitee.go` around lines 55 - 57, The NewInstance method
on GiteeModel currently returns nil; implement it to return a cloned GiteeModel
with its BaseURL replaced by the provided baseURL map so the driver can be used
for new instances — e.g., copy the receiver (deep enough for fields used,
typically via newModel := *z), set newModel.BaseURL = baseURL, and return
&newModel as the ModelDriver from NewInstance to preserve other fields from the
original while overriding BaseURL.
internal/entity/models/aliyun.go (1)

55-57: ⚠️ Potential issue | 🟠 Major

Same NewInstance stub needs a real implementation.

Returning nil leaves this driver unusable on the new instance path. Please return a cloned AliyunModel with the overridden BaseURL.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/aliyun.go` around lines 55 - 57, The NewInstance stub
in AliyunModel must return a cloned driver with the provided BaseURL instead of
nil; implement AliyunModel.NewInstance(baseURL map[string]string) to create and
return a copy of the receiver (preserving existing fields) but with its BaseURL
field set to the supplied baseURL map so callers get a usable ModelDriver
instance (refer to the AliyunModel type and the NewInstance method signature).
internal/entity/models/minimax.go (1)

50-52: ⚠️ Potential issue | 🟠 Major

Same NewInstance stub needs a real implementation.

Returning nil leaves this driver unusable on the new instance path. Please return a cloned MinimaxModel with the overridden BaseURL.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/minimax.go` around lines 50 - 52, Implement
MinimaxModel.NewInstance to return a cloned MinimaxModel that overrides its
BaseURL: create a shallow copy of the receiver (z) into a new MinimaxModel, set
newModel.BaseURL to the provided baseURL map (or copy the map if you want
isolation), and return the address as a ModelDriver; update the method on
MinimaxModel named NewInstance to perform this clone-and-override instead of
returning nil.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@conf/models/vllm.json`:
- Around line 3-6: The vllm config is missing the async_chat suffix referenced
by URLSuffix.AsyncChat, so add an "async_chat" property to conf/models/vllm.json
next to "chat" and "models" and set it to the correct endpoint suffix used for
async chat requests (for example "async_chat" or "async_chat/completions"), so
that the routing in internal/entity/models/vllm.go (which selects
URLSuffix.AsyncChat for model types qwen/glm) resolves to a non-empty suffix.

In `@internal/entity/model.go`:
- Around line 323-329: ListModels() currently omits the capability metadata
("features") from modelData, causing a silent API contract break; restore the
"features" field in the map you build for each model (the modelData created
inside the loop over provider.Models) or add explicit API versioning.
Specifically, update the map constructed in the loop (where you set "name",
"max_tokens", "model_types") to also include "features": model.Features (or the
appropriate field on the model struct) so the provider/model listing endpoints
return the original capability metadata, or if you prefer breaking change
semantics, bump the API version where ListModels is used.

In `@internal/entity/models/deepseek.go`:
- Around line 55-57: Implement DeepSeekModel.NewInstance to return a cloned
driver with BaseURL overridden instead of nil; locate DeepSeekModel.NewInstance
in internal/entity/models/deepseek.go and follow the VllmModel.NewInstance
pattern: deep-copy the receiver's state into a new DeepSeekModel value, set
newInstance.BaseURL = baseURL (the argument), and return &newInstance as a
ModelDriver so callers (e.g., model_service.go that immediately calls .Chat())
won't panic.

In `@internal/entity/models/dummy.go`:
- Around line 37-39: The NewInstance method on DummyModel currently returns nil
which causes callers expecting a ModelDriver to panic; update
DummyModel.NewInstance(baseURL map[string]string) to return a non-nil dummy
driver implementing ModelDriver (for example an initialized DummyModel or a
dedicated dummyDriver instance) that safely implements the ModelDriver methods
and embeds or stores baseURL so it can be used by the fallback provider; ensure
the returned value satisfies the ModelDriver interface instead of nil.

In `@internal/entity/models/siliconflow.go`:
- Around line 55-57: The NewInstance method currently returns nil causing
callers to receive a nil ModelDriver; implement SiliconflowModel.NewInstance to
return a concrete driver by constructing and returning a new SiliconflowModel
initialized with the provided baseURL (i.e., create a new SiliconflowModel
instance using the baseURL map and return it as a ModelDriver), ensuring the
returned type satisfies the ModelDriver interface.

In `@internal/entity/models/vllm.go`:
- Around line 86-91: The current model-family detection using modelType :=
strings.Split(*modelName, "-")[0] fails for variants like "qwen3-0.6b" or
"Qwen2-0.5B"; update the logic in the block that sets url (where modelType is
computed and compared) to normalize case and match prefixes instead of exact
equality—e.g., compute lower := strings.ToLower(*modelName); family :=
strings.Split(lower, "-")[0]; then use strings.HasPrefix(family, "qwen") ||
strings.HasPrefix(family, "glm") before selecting z.BaseURL[region] with
z.URLSuffix.AsyncChat so names like Qwen/Qwen2-0.5B, qwen3-0.6b, glm-4.7 etc.
are correctly detected.

In `@internal/entity/models/volcengine.go`:
- Around line 55-57: NewInstance currently returns nil which causes a panic when
callers do NewInstance(...).Chat(...); implement NewInstance to return a
concrete ModelDriver that references the parent VolcEngine and the provided
baseURL (for example return &volcModel{engine: z, baseURL: baseURL} or call an
existing constructor like NewVolcInstance(z, baseURL)). Ensure the returned type
implements the ModelDriver interface (including Chat) and initializes any
required fields (API client, auth, or config) so Chat can be invoked safely.

In `@internal/handler/providers.go`:
- Around line 650-708: The handler AddCustomModel currently trusts
req.ProviderName and req.InstanceName from the JSON body; instead read the route
params via c.Param("provider_name") and c.Param("instance_name"), assign them to
req.ProviderName and req.InstanceName, and use those values as the authoritative
source before calling h.modelProviderService.AddCustomModel. Validate that the
route params are non-empty (return HTTP 400 with an appropriate message if
missing) and remove/ignore the earlier body-based provider/instance checks so
only model-specific fields (e.g., ModelName, ModelType) are validated from the
request body; keep using c.ShouldBindJSON for the rest of the payload and then
call AddCustomModel with the updated req and userID.

In `@internal/service/model_service.go`:
- Around line 525-539: The loop that appends tenant custom models to allModels
currently pushes only {"name": ...}, losing metadata; update the block that
iterates disabledModels (in the code around
dao.GetModelProviderManager().ListModels and variable allModels) so that when
model.Status == "active" you append the full model representation (include the
same keys used by built-in models such as "name", "model_types" and "max_tokens"
or the exact fields on the disabledModels struct collected by AddCustomModel)
instead of a map with only "name"; ensure field names match the built-in model
objects so clients can consume both kinds uniformly.

---

Outside diff comments:
In `@internal/cli/user_parser.go`:
- Around line 1392-1431: The parser currently assumes URL then REGION and calls
p.nextToken() incorrectly causing the second option to be skipped; replace the
sequential parse with a loop that consumes any number/order of TokenURL and
TokenRegion tokens: while p.curToken.Type is TokenURL or TokenRegion, switch on
the token type, call p.nextToken(), parse the quoted string via
parseQuotedString() (returning error with the correct message for each case),
set baseURL or region accordingly, and do not call an extra p.nextToken() after
the loop that would skip the following token; keep the existing logic that sets
region = instanceName when baseURL is set and region is empty, and preserve the
semicolon handling and NewCommand("create_provider_instance") param population.

In `@internal/service/model_service.go`:
- Around line 296-303: The response currently returns the raw JSON string at
"extra" instead of the parsed object; update the append call in the block that
builds the result (the map appended to result for each instance) to set "extra"
to the unmarshaled value (the parsed variable used when decoding instance.Extra)
instead of instance.Extra, and ensure you handle/unset parse errors (e.g.,
default to nil or an empty map) so clients receive a parsed JSON object for
fields like base_url/region.

---

Duplicate comments:
In `@internal/entity/models/aliyun.go`:
- Around line 55-57: The NewInstance stub in AliyunModel must return a cloned
driver with the provided BaseURL instead of nil; implement
AliyunModel.NewInstance(baseURL map[string]string) to create and return a copy
of the receiver (preserving existing fields) but with its BaseURL field set to
the supplied baseURL map so callers get a usable ModelDriver instance (refer to
the AliyunModel type and the NewInstance method signature).

In `@internal/entity/models/gitee.go`:
- Around line 55-57: The NewInstance method on GiteeModel currently returns nil;
implement it to return a cloned GiteeModel with its BaseURL replaced by the
provided baseURL map so the driver can be used for new instances — e.g., copy
the receiver (deep enough for fields used, typically via newModel := *z), set
newModel.BaseURL = baseURL, and return &newModel as the ModelDriver from
NewInstance to preserve other fields from the original while overriding BaseURL.

In `@internal/entity/models/google.go`:
- Around line 41-43: Implement GoogleModel.NewInstance to return a cloned
GoogleModel with BaseURL overridden instead of nil; create a shallow copy of the
receiver (z) and set its BaseURL field to the provided baseURL map, then return
the copy as ModelDriver (e.g., newZ := *z; newZ.BaseURL = baseURL; return &newZ)
so the driver is usable via the NewInstance path.

In `@internal/entity/models/minimax.go`:
- Around line 50-52: Implement MinimaxModel.NewInstance to return a cloned
MinimaxModel that overrides its BaseURL: create a shallow copy of the receiver
(z) into a new MinimaxModel, set newModel.BaseURL to the provided baseURL map
(or copy the map if you want isolation), and return the address as a
ModelDriver; update the method on MinimaxModel named NewInstance to perform this
clone-and-override instead of returning nil.

In `@internal/entity/models/moonshot.go`:
- Around line 55-57: The NewInstance method currently returns nil; implement it
to return a cloned MoonshotModel that satisfies ModelDriver with its BaseURL
replaced by the provided baseURL map. Locate the MoonshotModel type and
implement NewInstance(baseURL map[string]string) ModelDriver to create a shallow
copy of the receiver (preserving other fields) then set copy.BaseURL = baseURL
(or deep-copy if BaseURL must not alias) and return the copy as a ModelDriver so
the new instance uses the overridden BaseURL.

In `@internal/entity/models/zhipu-ai.go`:
- Around line 55-57: Implement ZhipuAIModel.NewInstance so it returns a cloned
*ZhipuAIModel (satisfying ModelDriver) with its BaseURL overridden by the
provided baseURL map instead of nil; locate the NewInstance method on type
ZhipuAIModel and create a shallow copy (copy fields or use value copy) of the
receiver, set the newInstance.BaseURL = baseURL (or merge as appropriate), and
return the new instance so callers get a usable driver.
🪄 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: 015ff274-c768-4596-bbf1-3ed67e69c0d5

📥 Commits

Reviewing files that changed from the base of the PR and between decf673 and 4e8c35e.

📒 Files selected for processing (24)
  • conf/models/vllm.json
  • internal/cli/client.go
  • internal/cli/http_client.go
  • internal/cli/lexer.go
  • internal/cli/types.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/entity/model.go
  • internal/entity/models/aliyun.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/dummy.go
  • internal/entity/models/factory.go
  • internal/entity/models/gitee.go
  • internal/entity/models/google.go
  • internal/entity/models/minimax.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/types.go
  • internal/entity/models/vllm.go
  • internal/entity/models/volcengine.go
  • internal/entity/models/zhipu-ai.go
  • internal/handler/providers.go
  • internal/router/router.go
  • internal/service/model_service.go

Comment thread conf/models/vllm.json
Comment on lines +3 to +6
"url_suffix": {
"chat": "chat/completions",
"models": "models"
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n "AsyncChat|AsyncResult|URLSuffix" internal/entity/models conf/models

Repository: infiniflow/ragflow

Length of output: 6328


🏁 Script executed:

cat conf/models/vllm.json

Repository: infiniflow/ragflow

Length of output: 180


🏁 Script executed:

sed -n '80,100p' internal/entity/models/vllm.go

Repository: infiniflow/ragflow

Length of output: 832


Add the async_chat suffix to vllm.json.

The driver at internal/entity/models/vllm.go:90 routes models with prefixes qwen or glm through URLSuffix.AsyncChat, but the config only defines chat and models. Requests for these model types will resolve to an empty suffix and fail.

Code reference
// vllm.go:84-90
url := fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.Chat)

modelType := strings.Split(*modelName, "-")[0]
if modelType == "qwen" || modelType == "glm" {
	url = fmt.Sprintf("%s/%s", z.BaseURL[region], z.URLSuffix.AsyncChat)
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@conf/models/vllm.json` around lines 3 - 6, The vllm config is missing the
async_chat suffix referenced by URLSuffix.AsyncChat, so add an "async_chat"
property to conf/models/vllm.json next to "chat" and "models" and set it to the
correct endpoint suffix used for async chat requests (for example "async_chat"
or "async_chat/completions"), so that the routing in
internal/entity/models/vllm.go (which selects URLSuffix.AsyncChat for model
types qwen/glm) resolves to a non-empty suffix.

Comment thread internal/entity/model.go
Comment on lines 323 to +329
for _, model := range provider.Models {
modelData := map[string]interface{}{
"name": model.Name,
"max_tokens": model.MaxTokens,
"model_types": model.ModelTypes,
"features": GetFeatures(model),
}
models = append(models, modelData)
modelList = append(modelList, modelData)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Restore the features field or version this API change.

ListModels() now drops capability metadata entirely, but the result is still returned directly by the provider/model listing endpoints. That makes this a silent response-contract break for existing clients.

💡 Minimal compatibility fix
 	for _, model := range provider.Models {
 		modelData := map[string]interface{}{
 			"name":        model.Name,
 			"max_tokens":  model.MaxTokens,
 			"model_types": model.ModelTypes,
+			"features":    GetFeatures(model),
 		}
 		modelList = append(modelList, modelData)
 	}

Also applies to: 332-336

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/model.go` around lines 323 - 329, ListModels() currently
omits the capability metadata ("features") from modelData, causing a silent API
contract break; restore the "features" field in the map you build for each model
(the modelData created inside the loop over provider.Models) or add explicit API
versioning. Specifically, update the map constructed in the loop (where you set
"name", "max_tokens", "model_types") to also include "features": model.Features
(or the appropriate field on the model struct) so the provider/model listing
endpoints return the original capability metadata, or if you prefer breaking
change semantics, bump the API version where ListModels is used.

Comment on lines +55 to +57
func (z *DeepSeekModel) NewInstance(baseURL map[string]string) ModelDriver {
return nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail
rg -n -C 4 '\.NewInstance\(' internal

Repository: infiniflow/ragflow

Length of output: 681


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find ModelDriver interface definition
echo "=== ModelDriver Interface Definition ==="
rg -n 'type ModelDriver interface' internal

# Find all NewInstance implementations
echo -e "\n=== All NewInstance Implementations ==="
rg -n 'func.*NewInstance.*ModelDriver' internal

# Get full context around the usage in model_service.go
echo -e "\n=== Full context of NewInstance call ==="
sed -n '690,715p' internal/service/model_service.go

Repository: infiniflow/ragflow

Length of output: 2343


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Get the full ModelDriver interface definition
echo "=== ModelDriver Interface (types.go) ==="
sed -n '10,30p' internal/entity/models/types.go

# Compare with a working implementation (e.g., Aliyun)
echo -e "\n=== AliyunModel.NewInstance Implementation ==="
sed -n '55,65p' internal/entity/models/aliyun.go

# Check DeepSeek implementation again
echo -e "\n=== DeepSeekModel.NewInstance Implementation ==="
sed -n '55,57p' internal/entity/models/deepseek.go

Repository: infiniflow/ragflow

Length of output: 1890


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Check a few more implementations
echo "=== VllmModel.NewInstance ==="
sed -n '53,63p' internal/entity/models/vllm.go

echo -e "\n=== DummyModel.NewInstance ==="
sed -n '37,47p' internal/entity/models/dummy.go

echo -e "\n=== GoogleModel.NewInstance ==="
sed -n '41,51p' internal/entity/models/google.go

# Check broader context in model_service.go for any error handling
echo -e "\n=== Check for nil handling after NewInstance call ==="
sed -n '701,710p' internal/service/model_service.go

Repository: infiniflow/ragflow

Length of output: 1594


Implement NewInstance instead of returning nil.

This factory sits on the instance-rehydration path used by model_service.go at line 704, where the return value is immediately used to call .Chat() without nil guards. Returning nil will cause a panic. Clone the driver state and override BaseURL like VllmModel does.

Suggested fix
 func (z *DeepSeekModel) NewInstance(baseURL map[string]string) ModelDriver {
-	return nil
+	return &DeepSeekModel{
+		BaseURL:    baseURL,
+		URLSuffix:  z.URLSuffix,
+		httpClient: z.httpClient,
+	}
 }
📝 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.

Suggested change
func (z *DeepSeekModel) NewInstance(baseURL map[string]string) ModelDriver {
return nil
}
func (z *DeepSeekModel) NewInstance(baseURL map[string]string) ModelDriver {
return &DeepSeekModel{
BaseURL: baseURL,
URLSuffix: z.URLSuffix,
httpClient: z.httpClient,
}
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/deepseek.go` around lines 55 - 57, Implement
DeepSeekModel.NewInstance to return a cloned driver with BaseURL overridden
instead of nil; locate DeepSeekModel.NewInstance in
internal/entity/models/deepseek.go and follow the VllmModel.NewInstance pattern:
deep-copy the receiver's state into a new DeepSeekModel value, set
newInstance.BaseURL = baseURL (the argument), and return &newInstance as a
ModelDriver so callers (e.g., model_service.go that immediately calls .Chat())
won't panic.

Comment on lines +37 to +39
func (z *DummyModel) NewInstance(baseURL map[string]string) ModelDriver {
return nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Don’t return nil from the dummy driver’s NewInstance.

The factory still uses DummyModel as the fallback provider, so this now turns unsupported-provider handling into a nil-dereference path. Return a non-nil dummy instance instead.

🔧 Suggested fix
 func (z *DummyModel) NewInstance(baseURL map[string]string) ModelDriver {
-	return nil
+	return NewDummyModel(baseURL, z.URLSuffix)
 }
📝 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.

Suggested change
func (z *DummyModel) NewInstance(baseURL map[string]string) ModelDriver {
return nil
}
func (z *DummyModel) NewInstance(baseURL map[string]string) ModelDriver {
return NewDummyModel(baseURL, z.URLSuffix)
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/dummy.go` around lines 37 - 39, The NewInstance method
on DummyModel currently returns nil which causes callers expecting a ModelDriver
to panic; update DummyModel.NewInstance(baseURL map[string]string) to return a
non-nil dummy driver implementing ModelDriver (for example an initialized
DummyModel or a dedicated dummyDriver instance) that safely implements the
ModelDriver methods and embeds or stores baseURL so it can be used by the
fallback provider; ensure the returned value satisfies the ModelDriver interface
instead of nil.

Comment on lines +55 to +57
func (z *SiliconflowModel) NewInstance(baseURL map[string]string) ModelDriver {
return nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Return a concrete driver instead of nil.

This method is now part of the instance-based model flow, so returning nil will hand callers a nil ModelDriver and break the first follow-up call. Create a new SiliconflowModel with the supplied baseURL instead.

🔧 Suggested fix
 func (z *SiliconflowModel) NewInstance(baseURL map[string]string) ModelDriver {
-	return nil
+	return NewSiliconflowModel(baseURL, z.URLSuffix)
 }
📝 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.

Suggested change
func (z *SiliconflowModel) NewInstance(baseURL map[string]string) ModelDriver {
return nil
}
func (z *SiliconflowModel) NewInstance(baseURL map[string]string) ModelDriver {
return NewSiliconflowModel(baseURL, z.URLSuffix)
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/siliconflow.go` around lines 55 - 57, The NewInstance
method currently returns nil causing callers to receive a nil ModelDriver;
implement SiliconflowModel.NewInstance to return a concrete driver by
constructing and returning a new SiliconflowModel initialized with the provided
baseURL (i.e., create a new SiliconflowModel instance using the baseURL map and
return it as a ModelDriver), ensuring the returned type satisfies the
ModelDriver interface.

Comment on lines +214 to +223
func (z *VllmModel) ListModels(apiConfig *APIConfig) ([]string, error) {
return nil, fmt.Errorf("not implemented")
}

func (z *VllmModel) Balance(apiConfig *APIConfig) (map[string]interface{}, error) {
return nil, fmt.Errorf("no such method")
}

func (z *VllmModel) CheckConnection(apiConfig *APIConfig) error {
return fmt.Errorf("no such method")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Implement ListModels and CheckConnection before exposing vllm as a provider.

The provider flow already calls these interface methods for LIST SUPPORTED MODELS and CHECK INSTANCE. With the current stubs, those commands will fail immediately for every vllm instance.

Comment on lines +55 to +57
func (z *VolcEngine) NewInstance(baseURL map[string]string) ModelDriver {
return nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Implement NewInstance instead of returning nil.

The new active-model chat path calls NewInstance(...).Chat(...) directly. Returning nil here will panic as soon as a VolcEngine-backed custom/active model is used.

🐛 Proposed fix
 func (z *VolcEngine) NewInstance(baseURL map[string]string) ModelDriver {
-	return nil
+	return NewVolcEngine(baseURL, z.URLSuffix)
 }
📝 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.

Suggested change
func (z *VolcEngine) NewInstance(baseURL map[string]string) ModelDriver {
return nil
}
func (z *VolcEngine) NewInstance(baseURL map[string]string) ModelDriver {
return NewVolcEngine(baseURL, z.URLSuffix)
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/entity/models/volcengine.go` around lines 55 - 57, NewInstance
currently returns nil which causes a panic when callers do
NewInstance(...).Chat(...); implement NewInstance to return a concrete
ModelDriver that references the parent VolcEngine and the provided baseURL (for
example return &volcModel{engine: z, baseURL: baseURL} or call an existing
constructor like NewVolcInstance(z, baseURL)). Ensure the returned type
implements the ModelDriver interface (including Chat) and initializes any
required fields (API client, auth, or config) so Chat can be invoked safely.

Comment on lines +650 to +708
func (h *ProviderHandler) AddCustomModel(c *gin.Context) {
var req service.AddCustomModelRequest
if err := c.ShouldBindJSON(&req); err != nil {
println("JSON bind error: %v (type: %T)", err, err)
c.JSON(http.StatusOK, gin.H{
"code": common.CodeBadRequest,
"message": err.Error(),
})
return
}

if req.ProviderName == "" {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": "Provider name is required",
})
return
}

if req.InstanceName == "" {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": "Instance name is required",
})
return
}

if req.ModelName == "" {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": "Model name is required",
})
return
}

if req.ModelType == "" {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": "Model type is required",
})
return
}

userID := c.GetString("user_id")

errorCode, err := h.modelProviderService.AddCustomModel(&req, userID)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": errorCode,
"message": err.Error(),
})
return
}

c.JSON(http.StatusOK, gin.H{
"code": common.CodeSuccess,
})

}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Use the route params as the source of truth for provider and instance.

This endpoint is mounted under /:provider_name/instances/:instance_name/models, but the handler ignores both path params and trusts req.ProviderName / req.InstanceName from the body. A request can therefore hit one URL while creating a model under a different resource.

✅ Safer pattern
 func (h *ProviderHandler) AddCustomModel(c *gin.Context) {
+	providerName := c.Param("provider_name")
+	instanceName := c.Param("instance_name")
+
 	var req service.AddCustomModelRequest
 	if err := c.ShouldBindJSON(&req); err != nil {
 		c.JSON(http.StatusOK, gin.H{
 			"code":    common.CodeBadRequest,
 			"message": err.Error(),
 		})
 		return
 	}
 
-	if req.ProviderName == "" {
+	if providerName == "" {
 		c.JSON(http.StatusBadRequest, gin.H{
 			"code":    400,
 			"message": "Provider name is required",
 		})
 		return
 	}
 
-	if req.InstanceName == "" {
+	if instanceName == "" {
 		c.JSON(http.StatusBadRequest, gin.H{
 			"code":    400,
 			"message": "Instance name is required",
 		})
 		return
 	}
+
+	req.ProviderName = providerName
+	req.InstanceName = instanceName
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/handler/providers.go` around lines 650 - 708, The handler
AddCustomModel currently trusts req.ProviderName and req.InstanceName from the
JSON body; instead read the route params via c.Param("provider_name") and
c.Param("instance_name"), assign them to req.ProviderName and req.InstanceName,
and use those values as the authoritative source before calling
h.modelProviderService.AddCustomModel. Validate that the route params are
non-empty (return HTTP 400 with an appropriate message if missing) and
remove/ignore the earlier body-based provider/instance checks so only
model-specific fields (e.g., ModelName, ModelType) are validated from the
request body; keep using c.ShouldBindJSON for the rest of the payload and then
call AddCustomModel with the updated req and userID.

Comment on lines +525 to +539
allModels, err := dao.GetModelProviderManager().ListModels(providerName)

// insert models name into a set
modelNames := make(map[string]bool)
for _, model := range disabledModels {
modelNames[model.ModelName] = true
}
if model.Status == "active" {
modelData := map[string]interface{}{
"name": model.ModelName,
}
allModels = append(allModels, modelData)
} else {
modelNames[model.ModelName] = true
}

allModels, err := dao.GetModelProviderManager().ListModels(providerName)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Keep custom models in the same response shape as built-in models.

Active tenant models are appended as {"name": ...} only. That drops the model_types and max_tokens metadata that the new AddCustomModel flow just collected, so clients cannot distinguish or display those models consistently.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/service/model_service.go` around lines 525 - 539, The loop that
appends tenant custom models to allModels currently pushes only {"name": ...},
losing metadata; update the block that iterates disabledModels (in the code
around dao.GetModelProviderManager().ListModels and variable allModels) so that
when model.Status == "active" you append the full model representation (include
the same keys used by built-in models such as "name", "model_types" and
"max_tokens" or the exact fields on the disabledModels struct collected by
AddCustomModel) instead of a map with only "name"; ensure field names match the
built-in model objects so clients can consume both kinds uniformly.

Comment on lines +902 to +964
func (m *ModelProviderService) AddCustomModel(request *AddCustomModelRequest, userID string) (common.ErrorCode, error) {
// Get tenant ID from user
tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
if err != nil {
return common.CodeServerError, err
}

if len(tenants) == 0 {
return common.CodeNotFound, errors.New("user has no tenants")
}

tenantID := tenants[0].TenantID

// Check if provider exists
provider, err := m.modelProviderDAO.GetByTenantIDAndProviderName(tenantID, request.ProviderName)
if err != nil {
return common.CodeServerError, err
}

instance, err := m.modelInstanceDAO.GetByProviderIDAndInstanceName(provider.ID, request.InstanceName)
if err != nil {
return common.CodeServerError, err
}

_, err = m.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName(provider.ID, instance.ID, request.ModelName)
if err == nil {
return common.CodeConflict, errors.New("model already exists")
}

modelID, err := generateUUID1Hex()
if err != nil {
return common.CodeServerError, errors.New("fail to get UUID")
}

extra := make(map[string]interface{})
extra["max_tokens"] = request.MaxTokens
if request.Thinking != nil {
extra["thinking"] = *request.Thinking
}
// convert extra to string
extraByte, err := json.Marshal(extra)
if err != nil {
return common.CodeServerError, errors.New("fail to marshal extra")
}
extraStr := string(extraByte)

model := &entity.TenantModel{
ID: modelID,
ModelName: request.ModelName,
ModelType: request.ModelType,
ProviderID: provider.ID,
InstanceID: instance.ID,
Status: "active",
Extra: extraStr,
}

err = m.modelDAO.Create(model)
if err != nil {
return common.CodeServerError, err
}

return common.CodeSuccess, nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Validate custom-model inputs before persisting an active model.

This currently stores whatever model_type and max_tokens arrive, and it does not verify that the target instance is actually local-capable. That makes it easy to create active models that are unusable later: unknown types, max_tokens <= 0, or instances without a usable base_url / instance-specific driver.

🛡️ Suggested guardrails
 func (m *ModelProviderService) AddCustomModel(request *AddCustomModelRequest, userID string) (common.ErrorCode, error) {
+	if request.MaxTokens <= 0 {
+		return common.CodeBadRequest, errors.New("max_tokens must be greater than 0")
+	}
+
+	validTypes := map[string]struct{}{
+		"chat": {}, "vision": {}, "embedding": {}, "rerank": {},
+		"tts": {}, "asr": {}, "ocr": {},
+	}
+	if _, ok := validTypes[request.ModelType]; !ok {
+		return common.CodeBadRequest, fmt.Errorf("unsupported model type %q", request.ModelType)
+	}
+
 	// Get tenant ID from user
 	tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
 	if err != nil {
 		return common.CodeServerError, err
 	}
@@
 	instance, err := m.modelInstanceDAO.GetByProviderIDAndInstanceName(provider.ID, request.InstanceName)
 	if err != nil {
 		return common.CodeServerError, err
 	}
+
+	var instanceExtra map[string]string
+	if err := json.Unmarshal([]byte(instance.Extra), &instanceExtra); err != nil {
+		return common.CodeServerError, err
+	}
+	if instanceExtra["base_url"] == "" {
+		return common.CodeBadRequest, errors.New("custom models require an instance with base_url configured")
+	}
📝 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.

Suggested change
func (m *ModelProviderService) AddCustomModel(request *AddCustomModelRequest, userID string) (common.ErrorCode, error) {
// Get tenant ID from user
tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
if err != nil {
return common.CodeServerError, err
}
if len(tenants) == 0 {
return common.CodeNotFound, errors.New("user has no tenants")
}
tenantID := tenants[0].TenantID
// Check if provider exists
provider, err := m.modelProviderDAO.GetByTenantIDAndProviderName(tenantID, request.ProviderName)
if err != nil {
return common.CodeServerError, err
}
instance, err := m.modelInstanceDAO.GetByProviderIDAndInstanceName(provider.ID, request.InstanceName)
if err != nil {
return common.CodeServerError, err
}
_, err = m.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName(provider.ID, instance.ID, request.ModelName)
if err == nil {
return common.CodeConflict, errors.New("model already exists")
}
modelID, err := generateUUID1Hex()
if err != nil {
return common.CodeServerError, errors.New("fail to get UUID")
}
extra := make(map[string]interface{})
extra["max_tokens"] = request.MaxTokens
if request.Thinking != nil {
extra["thinking"] = *request.Thinking
}
// convert extra to string
extraByte, err := json.Marshal(extra)
if err != nil {
return common.CodeServerError, errors.New("fail to marshal extra")
}
extraStr := string(extraByte)
model := &entity.TenantModel{
ID: modelID,
ModelName: request.ModelName,
ModelType: request.ModelType,
ProviderID: provider.ID,
InstanceID: instance.ID,
Status: "active",
Extra: extraStr,
}
err = m.modelDAO.Create(model)
if err != nil {
return common.CodeServerError, err
}
return common.CodeSuccess, nil
}
func (m *ModelProviderService) AddCustomModel(request *AddCustomModelRequest, userID string) (common.ErrorCode, error) {
if request.MaxTokens <= 0 {
return common.CodeBadRequest, errors.New("max_tokens must be greater than 0")
}
validTypes := map[string]struct{}{
"chat": {}, "vision": {}, "embedding": {}, "rerank": {},
"tts": {}, "asr": {}, "ocr": {},
}
if _, ok := validTypes[request.ModelType]; !ok {
return common.CodeBadRequest, fmt.Errorf("unsupported model type %q", request.ModelType)
}
// Get tenant ID from user
tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
if err != nil {
return common.CodeServerError, err
}
if len(tenants) == 0 {
return common.CodeNotFound, errors.New("user has no tenants")
}
tenantID := tenants[0].TenantID
// Check if provider exists
provider, err := m.modelProviderDAO.GetByTenantIDAndProviderName(tenantID, request.ProviderName)
if err != nil {
return common.CodeServerError, err
}
instance, err := m.modelInstanceDAO.GetByProviderIDAndInstanceName(provider.ID, request.InstanceName)
if err != nil {
return common.CodeServerError, err
}
var instanceExtra map[string]string
if err := json.Unmarshal([]byte(instance.Extra), &instanceExtra); err != nil {
return common.CodeServerError, err
}
if instanceExtra["base_url"] == "" {
return common.CodeBadRequest, errors.New("custom models require an instance with base_url configured")
}
_, err = m.modelDAO.GetModelByProviderIDAndInstanceIDAndModelName(provider.ID, instance.ID, request.ModelName)
if err == nil {
return common.CodeConflict, errors.New("model already exists")
}
modelID, err := generateUUID1Hex()
if err != nil {
return common.CodeServerError, errors.New("fail to get UUID")
}
extra := make(map[string]interface{})
extra["max_tokens"] = request.MaxTokens
if request.Thinking != nil {
extra["thinking"] = *request.Thinking
}
// convert extra to string
extraByte, err := json.Marshal(extra)
if err != nil {
return common.CodeServerError, errors.New("fail to marshal extra")
}
extraStr := string(extraByte)
model := &entity.TenantModel{
ID: modelID,
ModelName: request.ModelName,
ModelType: request.ModelType,
ProviderID: provider.ID,
InstanceID: instance.ID,
Status: "active",
Extra: extraStr,
}
err = m.modelDAO.Create(model)
if err != nil {
return common.CodeServerError, err
}
return common.CodeSuccess, nil
}

@JinHai-CN
JinHai-CN merged commit bb05a8b into infiniflow:main Apr 29, 2026
2 checks passed
TIMBLOCKER pushed a commit to TIMBLOCKER/kira that referenced this pull request Apr 29, 2026
### What problem does this PR solve?

1. support command:

```
RAGFlow(user)> create provider 'vllm' instance 'test' key 'test-key' url 'base-url' region 'abc';
SUCCESS
RAGFlow(user)> list instances from 'vllm';
+----------+----------------------------------------+----------------------------------+--------------+----------------------------------+--------+
| apiKey   | extra                                  | id                               | instanceName | providerID                       | status |
+----------+----------------------------------------+----------------------------------+--------------+----------------------------------+--------+
| test-key | {"base_url":"base-url","region":"abc"} | 40213c89430311f1a7cf38a74640adcc | test         | b4d40e6142d311f1a4f938a74640adcc | enable |
+----------+----------------------------------------+----------------------------------+--------------+----------------------------------+--------+
```
2. support add vllm model
```
RAGFlow(user)> add model 'Qwen/Qwen2-0.5B' to provider 'vllm' instance 'test' with tokens 131072 chat;
SUCCESS
```
3. add vllm chat

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
- [x] Refactoring

---------

Signed-off-by: Jin Hai <[email protected]>
TIMBLOCKER pushed a commit to TIMBLOCKER/kira that referenced this pull request May 7, 2026
### What problem does this PR solve?

1. support command:

```
RAGFlow(user)> create provider 'vllm' instance 'test' key 'test-key' url 'base-url' region 'abc';
SUCCESS
RAGFlow(user)> list instances from 'vllm';
+----------+----------------------------------------+----------------------------------+--------------+----------------------------------+--------+
| apiKey   | extra                                  | id                               | instanceName | providerID                       | status |
+----------+----------------------------------------+----------------------------------+--------------+----------------------------------+--------+
| test-key | {"base_url":"base-url","region":"abc"} | 40213c89430311f1a7cf38a74640adcc | test         | b4d40e6142d311f1a4f938a74640adcc | enable |
+----------+----------------------------------------+----------------------------------+--------------+----------------------------------+--------+
```
2. support add vllm model
```
RAGFlow(user)> add model 'Qwen/Qwen2-0.5B' to provider 'vllm' instance 'test' with tokens 131072 chat;
SUCCESS
```
3. add vllm chat

### Type of change

- [x] New Feature (non-breaking change which adds functionality)
- [x] Refactoring

---------

Signed-off-by: Jin Hai <[email protected]>
@coderabbitai coderabbitai Bot mentioned this pull request May 13, 2026
1 task done
@coderabbitai coderabbitai Bot mentioned this pull request May 25, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. ☯️ refactor Pull request that refactor/refine code size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant