Repository navigation
Feat: get model list from remote - #15711
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 with no reviewable changes (1)
📝 WalkthroughWalkthroughThis PR adds remote model discovery via a ModelMeta framework (Ollama implemented, VolcEngine stubbed), registers and exports ModelMeta, merges remote and static model lists in the provider service, makes the list route async and forwards optional api_key/base_url, and changes ChangesRemote Model Discovery Integration
Sequence DiagramsequenceDiagram
participant Client
participant RouteHandler as list_provider_models (route)
participant Service as list_provider_models (service)
participant ModelMeta as ModelMeta[provider]
participant OllamaAPI as Ollama HTTP API
Client->>RouteHandler: GET /providers/{provider}/models?api_key=X&base_url=Y
RouteHandler->>Service: await list_provider_models(provider, api_key, base_url)
Service->>Service: Build static_llms from FACTORY_LLM_INFOS
alt api_key or base_url provided
Service->>ModelMeta: ModelMeta[provider](api_key, base_url).get_model_list()
ModelMeta->>OllamaAPI: GET /api/tags, then GET /api/show per model
OllamaAPI-->>ModelMeta: tags and model details
ModelMeta-->>Service: remote_models list
Service->>Service: Merge remote_models (override) + static_llms
end
Service->>Service: Validate models not empty
Service-->>RouteHandler: models list or error
RouteHandler-->>Client: JSON response (success or error)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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: 7
🧹 Nitpick comments (2)
api/apps/restful_apis/provider_api.py (1)
202-242: ⚡ Quick winAdd logging for the remote model discovery flow.
The route handler was converted to async and now triggers remote model fetching, but no logging was added to track this new behavior. Add log statements for observability.
📋 Example logging addition
async def list_provider_models(provider_name: str): try: api_key = request.args.get("api_key") base_url = request.args.get("base_url") + logging.info(f"Listing models for provider '{provider_name}' with remote fetch: api_key={'<redacted>' if api_key else 'None'}, base_url={base_url}") success, result = await provider_api_service.list_provider_models(provider_name, api_key, base_url) if success: + logging.debug(f"Successfully listed {len(result)} models for provider '{provider_name}'") return get_result(data=result)As per coding guidelines: "Add logging for new flows" applies to
**/*.py.🤖 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 `@api/apps/restful_apis/provider_api.py` around lines 202 - 242, The list_provider_models route now performs remote model discovery but lacks observability; add logging in async def list_provider_models to record when discovery starts (include provider_name and whether api_key/base_url were supplied—mask/full omit sensitive api_key), log an informational entry before calling provider_api_service.list_provider_models, log the outcome on success (number of models or summary) and on failure (include result message), and ensure the exception handler logs the error with context (provider_name) using logging.exception; reference the function name list_provider_models and the call site provider_api_service.list_provider_models when adding these log statements.rag/llm/model_meta.py (1)
1-114: ⚡ Quick winAdd logging for the new remote model discovery flow.
The file introduces a new flow for fetching model metadata from remote providers but has no logging. Add log statements to track when remote fetches occur, their outcomes, and any errors.
📋 Example logging additions
import logging class Ollama(Base): async def get_model_list(self): if not self.base_url: logging.debug("Ollama: No base_url provided, skipping remote model fetch") return [] logging.info(f"Fetching Ollama models from {self.base_url}") # ... existing code ... logging.info(f"Successfully fetched {len(res)} models from Ollama") return resAs per coding guidelines: "Add logging for new flows" applies to
**/*.py.🤖 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 `@rag/llm/model_meta.py` around lines 1 - 114, Add logging to the remote model discovery flow: import logging at top, then instrument Ollama.get_model_list (and optionally VolcEngine.get_model_list when implemented) to log key events — log.debug when base_url is missing, logging.info when starting a fetch with the base_url, logging.warning or logging.error when HTTP responses are non-200 (include status and URL) and when session.post for model details fails, and logging.info after successfully building res with the count of models; also catch and log unexpected exceptions around the aiohttp session/requests to ensure errors are recorded.
🤖 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 `@api/apps/restful_apis/provider_api.py`:
- Line 233: Replace the insecure retrieval of the API key from query params
(api_key = request.args.get("api_key")) so the endpoint reads credentials from a
safer location: either from an Authorization header (e.g.,
request.headers.get("Authorization") and parse a "Bearer <key>" or "ApiKey
<key>" scheme) or from a POST JSON body (request.get_json().get("api_key"))
after changing the route to accept POST and validating Content-Type. Update the
endpoint handler (where api_key is referenced) to refuse keys from request.args,
remove any logging of the raw key, and add input validation and clear error
responses when the header/body key is missing; also update associated tests and
API docs to reflect the new header/body-based authentication.
In `@api/apps/services/provider_api_service.py`:
- Around line 191-193: Wrap the call to ModelMeta[provider_name](api_key,
model_base_url).get_model_list() in a try/except block: catch broad exceptions
from network/parsing (e.g., requests/HTTP/timeout/ValueError), log the full
exception and context (include provider_name, api_key redacted, model_base_url)
using the module logger, and return a safe fallback (empty remote_models) or
raise a controlled error/HTTPException with a clear message instead of letting
the raw exception propagate; update references to remote_models, ModelMeta,
get_model_list, provider_name, api_key, and model_base_url accordingly and
ensure logging is added per project guidelines.
In `@rag/llm/model_meta.py`:
- Around line 61-63: The VolcEngine.get_model_list method is synchronous but
must match the async signature of Base.get_model_list so callers can await it;
change VolcEngine.get_model_list to be async (async def get_model_list(self):)
and either implement the token-auth comment or keep raising NotImplementedError
from within the async coroutine, ensuring the signature aligns with
Base.get_model_list and the service call await
ModelMeta[provider_name](...).get_model_list() will work.
- Around line 106-111: The code builds max_tokens_key and reads nested fields
from model_info unsafely; update the accesses to use safe .get() calls and
defaults so missing keys don't raise KeyError: compute family =
model_info.get("details", {}).get("family", "") and max_tokens =
model_info.get("model_info", {}).get(max_tokens_key, 8192), and ensure the list
comprehensions that use model_info.get("capabilities", []) reference that safe
value; modify the res.append call (and any references to max_tokens_key,
capability_to_model_type_mapping, capability_to_feature_mapping, and model_info)
to use these guarded lookups.
- Line 103: The debug print call print(resp, flush=True) in
rag/llm/model_meta.py should be replaced with a logging call: import the logging
module if missing, create or use a module-level logger (e.g.,
logging.getLogger(__name__)), and replace the print with an appropriate logger
method (logger.debug or logger.info) to record resp; remove the flush and ensure
the log message gives enough context about resp.
- Around line 31-36: The _get_model_list_url method currently uses a fragile
substring check on self.base_url causing false matches; instead parse
self.base_url with urllib.parse.urlparse, inspect and normalize the parsed.path
(only treat a leading "/v1" path segment as the API version), then construct a
new URL using urllib.parse.urlunparse with the original scheme and netloc and a
normalized path of "/v1/models" (preserving no accidental query/fragment
matching); update the method to return None if base_url is falsy and otherwise
return the reconstructed URL so that _get_model_list_url safely handles URLs
without matching "/v1" in host/query parts.
- Around line 38-46: In _get_raw_model_list, add a per-request timeout and
exception handling: create an aiohttp.ClientTimeout (e.g., total/Connect/read
values) and pass it to aiohttp.ClientSession (or use session.get with timeout)
and wrap the request in try/except to catch aiohttp.ClientError,
asyncio.TimeoutError and return None on failures; ensure non-200 responses still
return None and consider logging the exception/context before returning.
---
Nitpick comments:
In `@api/apps/restful_apis/provider_api.py`:
- Around line 202-242: The list_provider_models route now performs remote model
discovery but lacks observability; add logging in async def list_provider_models
to record when discovery starts (include provider_name and whether
api_key/base_url were supplied—mask/full omit sensitive api_key), log an
informational entry before calling provider_api_service.list_provider_models,
log the outcome on success (number of models or summary) and on failure (include
result message), and ensure the exception handler logs the error with context
(provider_name) using logging.exception; reference the function name
list_provider_models and the call site provider_api_service.list_provider_models
when adding these log statements.
In `@rag/llm/model_meta.py`:
- Around line 1-114: Add logging to the remote model discovery flow: import
logging at top, then instrument Ollama.get_model_list (and optionally
VolcEngine.get_model_list when implemented) to log key events — log.debug when
base_url is missing, logging.info when starting a fetch with the base_url,
logging.warning or logging.error when HTTP responses are non-200 (include status
and URL) and when session.post for model details fails, and logging.info after
successfully building res with the count of models; also catch and log
unexpected exceptions around the aiohttp session/requests to ensure errors are
recorded.
🪄 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: 0278febd-9d78-4a01-8b1f-259f22247f0a
📒 Files selected for processing (4)
api/apps/restful_apis/provider_api.pyapi/apps/services/provider_api_service.pyrag/llm/__init__.pyrag/llm/model_meta.py
| """ | ||
| try: | ||
| success, result = provider_api_service.list_provider_models(provider_name) | ||
| api_key = request.args.get("api_key") |
There was a problem hiding this comment.
API key in query parameters exposes credentials.
Passing api_key via query string (request.args.get("api_key")) exposes the credential in server access logs, browser history, and proxy logs. API keys should be transmitted via request body or headers (e.g., Authorization header).
🔐 Proposed fix using request body
Update the endpoint to accept a POST body instead of query parameters for sensitive data:
-@manager.route("/providers/<provider_name>/models", methods=["GET"]) # noqa: F821
+@manager.route("/providers/<provider_name>/models", methods=["POST"]) # noqa: F821
`@login_required`
async def list_provider_models(provider_name: str):
"""
List models for a provider.
---
# ... update docstring to reflect POST with body ...
"""
try:
- api_key = request.args.get("api_key")
- base_url = request.args.get("base_url")
+ data = await request.get_json() or {}
+ api_key = data.get("api_key")
+ base_url = data.get("base_url")
success, result = await provider_api_service.list_provider_models(provider_name, api_key, base_url)Alternatively, if GET is required for caching, accept api_key only via the Authorization header.
🤖 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 `@api/apps/restful_apis/provider_api.py` at line 233, Replace the insecure
retrieval of the API key from query params (api_key =
request.args.get("api_key")) so the endpoint reads credentials from a safer
location: either from an Authorization header (e.g.,
request.headers.get("Authorization") and parse a "Bearer <key>" or "ApiKey
<key>" scheme) or from a POST JSON body (request.get_json().get("api_key"))
after changing the route to accept POST and validating Content-Type. Update the
endpoint handler (where api_key is referenced) to refuse keys from request.args,
remove any logging of the raw key, and add input validation and clear error
responses when the header/body key is missing; also update associated tests and
API docs to reflect the new header/body-based authentication.
| remote_models = [] | ||
| if provider_name in ModelMeta: | ||
| remote_models = await ModelMeta[provider_name](api_key, model_base_url).get_model_list() |
There was a problem hiding this comment.
Add error handling around remote model fetch.
The await ModelMeta[provider_name](...).get_model_list() call has no exception handling. If the remote provider's HTTP calls fail, timeout, or return malformed data (especially given the unsafe dict access in Ollama), the exception will propagate to the route handler and return a generic "Internal server error" instead of a meaningful error.
🔧 Proposed fix with error handling and logging
model_base_url = base_url or factory_info[0].get("url", "")
remote_models = []
if provider_name in ModelMeta:
- remote_models = await ModelMeta[provider_name](api_key, model_base_url).get_model_list()
+ try:
+ logging.info(f"Fetching remote models for provider '{provider_name}' from {model_base_url}")
+ remote_models = await ModelMeta[provider_name](api_key, model_base_url).get_model_list()
+ logging.info(f"Fetched {len(remote_models)} remote models for provider '{provider_name}'")
+ except Exception as e:
+ logging.warning(f"Failed to fetch remote models for provider '{provider_name}': {e}")
+ # Continue with static models onlyAs per coding guidelines: "Add logging for new flows" applies to **/*.py.
📝 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.
| remote_models = [] | |
| if provider_name in ModelMeta: | |
| remote_models = await ModelMeta[provider_name](api_key, model_base_url).get_model_list() | |
| remote_models = [] | |
| if provider_name in ModelMeta: | |
| try: | |
| logging.info(f"Fetching remote models for provider '{provider_name}' from {model_base_url}") | |
| remote_models = await ModelMeta[provider_name](api_key, model_base_url).get_model_list() | |
| logging.info(f"Fetched {len(remote_models)} remote models for provider '{provider_name}'") | |
| except Exception as e: | |
| logging.warning(f"Failed to fetch remote models for provider '{provider_name}': {e}") | |
| # Continue with static models only |
🤖 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 `@api/apps/services/provider_api_service.py` around lines 191 - 193, Wrap the
call to ModelMeta[provider_name](api_key, model_base_url).get_model_list() in a
try/except block: catch broad exceptions from network/parsing (e.g.,
requests/HTTP/timeout/ValueError), log the full exception and context (include
provider_name, api_key redacted, model_base_url) using the module logger, and
return a safe fallback (empty remote_models) or raise a controlled
error/HTTPException with a clear message instead of letting the raw exception
propagate; update references to remote_models, ModelMeta, get_model_list,
provider_name, api_key, and model_base_url accordingly and ensure logging is
added per project guidelines.
| def _get_model_list_url(self): | ||
| if not self.base_url: | ||
| return None | ||
| if "/v1" in self.base_url: | ||
| return self.base_url.split("/v1")[0].rstrip("/") + "/v1/models" | ||
| return self.base_url.rstrip("/") + "/v1/models" |
There was a problem hiding this comment.
Fragile URL parsing could construct malformed endpoints.
The substring check if "/v1" in self.base_url can match "/v1" anywhere in the URL (e.g., query parameters, domain names), and split("/v1")[0] doesn't validate URL structure. This could lead to incorrect model list URLs.
🔧 Proposed fix using urllib.parse
+from urllib.parse import urlparse, urljoin
+
class Base(ABC):
def __init__(self, api_key: str, base_url: str=None):
self.api_key = api_key
self.base_url = base_url
def _get_api_key(self):
return self.api_key
def _get_model_list_url(self):
if not self.base_url:
return None
- if "/v1" in self.base_url:
- return self.base_url.split("/v1")[0].rstrip("/") + "/v1/models"
- return self.base_url.rstrip("/") + "/v1/models"
+ parsed = urlparse(self.base_url)
+ base = f"{parsed.scheme}://{parsed.netloc}"
+ return urljoin(base, "/v1/models")🤖 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 `@rag/llm/model_meta.py` around lines 31 - 36, The _get_model_list_url method
currently uses a fragile substring check on self.base_url causing false matches;
instead parse self.base_url with urllib.parse.urlparse, inspect and normalize
the parsed.path (only treat a leading "/v1" path segment as the API version),
then construct a new URL using urllib.parse.urlunparse with the original scheme
and netloc and a normalized path of "/v1/models" (preserving no accidental
query/fragment matching); update the method to return None if base_url is falsy
and otherwise return the reconstructed URL so that _get_model_list_url safely
handles URLs without matching "/v1" in host/query parts.
| async def _get_raw_model_list(self): | ||
| url = self._get_model_list_url() | ||
| if not url: | ||
| return None | ||
| async with aiohttp.ClientSession() as session: | ||
| async with session.get(url, headers={"Authorization": f"Bearer {self._get_api_key()}"}) as resp: | ||
| if resp.status != 200: | ||
| return None | ||
| return await resp.json() |
There was a problem hiding this comment.
Missing timeout and error handling could hang requests indefinitely.
The aiohttp session has no timeout configured, and network exceptions (DNS failures, connection errors, timeouts) are not caught. If a remote provider is slow or unreachable, this will block the API request indefinitely or propagate unexpected exceptions to callers.
⏱️ Proposed fix with timeout and error handling
+import logging
+
async def _get_raw_model_list(self):
url = self._get_model_list_url()
if not url:
return None
- async with aiohttp.ClientSession() as session:
+ timeout = aiohttp.ClientTimeout(total=10)
+ try:
+ async with aiohttp.ClientSession(timeout=timeout) as session:
- async with session.get(url, headers={"Authorization": f"Bearer {self._get_api_key()}"}) as resp:
+ async with session.get(url, headers={"Authorization": f"Bearer {self._get_api_key()}"}) as resp:
- if resp.status != 200:
- return None
- return await resp.json()
+ if resp.status != 200:
+ logging.warning(f"Model list fetch failed: {url} returned {resp.status}")
+ return None
+ return await resp.json()
+ except Exception as e:
+ logging.error(f"Failed to fetch model list from {url}: {e}")
+ return None🤖 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 `@rag/llm/model_meta.py` around lines 38 - 46, In _get_raw_model_list, add a
per-request timeout and exception handling: create an aiohttp.ClientTimeout
(e.g., total/Connect/read values) and pass it to aiohttp.ClientSession (or use
session.get with timeout) and wrap the request in try/except to catch
aiohttp.ClientError, asyncio.TimeoutError and return None on failures; ensure
non-200 responses still return None and consider logging the exception/context
before returning.
| def get_model_list(self): | ||
| # todo implement access token auth | ||
| raise NotImplementedError |
There was a problem hiding this comment.
Method signature mismatch will cause runtime error.
VolcEngine.get_model_list() is defined as synchronous (def), but Base.get_model_list() is async (async def). The service layer calls await ModelMeta[provider_name](...).get_model_list() (line 193 in provider_api_service.py), which will fail when provider_name is "VolcEngine" because you cannot await a non-coroutine.
🐛 Proposed fix to match async signature
class VolcEngine(Base):
_FACTORY_NAME = "VolcEngine"
- def get_model_list(self):
+ async def get_model_list(self):
# todo implement access token auth
raise NotImplementedError📝 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.
| def get_model_list(self): | |
| # todo implement access token auth | |
| raise NotImplementedError | |
| async def get_model_list(self): | |
| # todo implement access token auth | |
| raise NotImplementedError |
🤖 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 `@rag/llm/model_meta.py` around lines 61 - 63, The VolcEngine.get_model_list
method is synchronous but must match the async signature of Base.get_model_list
so callers can await it; change VolcEngine.get_model_list to be async (async def
get_model_list(self):) and either implement the token-auth comment or keep
raising NotImplementedError from within the async coroutine, ensuring the
signature aligns with Base.get_model_list and the service call await
ModelMeta[provider_name](...).get_model_list() will work.
| max_tokens_key = "{}.context_length".format(model_info.get("details", {}).get("family", "")) | ||
| res.append({ | ||
| "name": model["name"], | ||
| "model_types": [capability_to_model_type_mapping[c] for c in model_info.get("capabilities", []) if c in capability_to_model_type_mapping], | ||
| "features": [capability_to_feature_mapping[c] for c in model_info.get("capabilities", []) if c in capability_to_feature_mapping], | ||
| "max_tokens": model_info["model_info"].get(max_tokens_key, 8192) |
There was a problem hiding this comment.
Unsafe nested dictionary access could raise KeyError.
Lines 106-111 access nested dictionary keys without validation. If model_info lacks "details", "family", or "model_info", the code will crash with a KeyError instead of gracefully handling malformed responses from Ollama.
🛡️ Proposed fix with safe access
model_info = await resp.json()
-max_tokens_key = "{}.context_length".format(model_info.get("details", {}).get("family", ""))
+details = model_info.get("details", {})
+family = details.get("family", "")
+max_tokens_key = f"{family}.context_length" if family else "context_length"
+model_info_dict = model_info.get("model_info", {})
+max_tokens = model_info_dict.get(max_tokens_key, 8192)
+
res.append({
"name": model["name"],
"model_types": [capability_to_model_type_mapping[c] for c in model_info.get("capabilities", []) if c in capability_to_model_type_mapping],
"features": [capability_to_feature_mapping[c] for c in model_info.get("capabilities", []) if c in capability_to_feature_mapping],
- "max_tokens": model_info["model_info"].get(max_tokens_key, 8192)
+ "max_tokens": max_tokens
})🤖 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 `@rag/llm/model_meta.py` around lines 106 - 111, The code builds max_tokens_key
and reads nested fields from model_info unsafely; update the accesses to use
safe .get() calls and defaults so missing keys don't raise KeyError: compute
family = model_info.get("details", {}).get("family", "") and max_tokens =
model_info.get("model_info", {}).get(max_tokens_key, 8192), and ensure the list
comprehensions that use model_info.get("capabilities", []) reference that safe
value; modify the res.append call (and any references to max_tokens_key,
capability_to_model_type_mapping, capability_to_feature_mapping, and model_info)
to use these guarded lookups.
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
api/apps/restful_apis/provider_api.py (2)
200-231:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winOpenAPI docstring missing new query parameters.
The handler now accepts
api_keyandbase_urlfrom query parameters (lines 233-234), but the docstring/OpenAPI spec (lines 206-230) doesn't document these parameters. This will cause incomplete API documentation.📝 Proposed fix to add parameter documentation
parameters: - in: path name: provider_name type: string required: true description: Provider name. + - in: query + name: api_key + type: string + required: false + description: API key for fetching remote models (optional). + - in: query + name: base_url + type: string + required: false + description: Base URL for the provider API (optional). - in: header name: Authorization🤖 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 `@api/apps/restful_apis/provider_api.py` around lines 200 - 231, The OpenAPI docstring for the list_provider_models handler is missing the two new query parameters (api_key and base_url); update the docstring inside the list_provider_models function to add parameter entries for query parameters named "api_key" and "base_url" (type: string, required: false, with short descriptions indicating they override the provider credentials and base URL respectively) so the generated API docs reflect the actual handler behavior.
329-331:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winOpenAPI spec shows
model_infoas object, but it's now a list.The docstring declares
model_infoastype: object(line 330), but the handler now defaults it to[]and the service expectslist[dict]. This mismatches the actual API contract. The same issue exists at lines 398-400 forverify_provider_api_key.📝 Proposed fix for create_provider_instance
model_info: - type: object - description: Model info. + type: array + items: + type: object + description: List of model info objects.🤖 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 `@api/apps/restful_apis/provider_api.py` around lines 329 - 331, The OpenAPI schema for model_info is declared as type: object but the handlers create_provider_instance and verify_provider_api_key treat it as a list (defaulting to [] and service expects list[dict]); update the OpenAPI/docstring for model_info in provider_api.py to type: array with items: type: object (or items: { type: object }) and keep the default as [] so the spec matches the actual handler/service expectation, and ensure any related parameter documentation for create_provider_instance and verify_provider_api_key is consistent with list[dict].
🤖 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 `@api/apps/services/provider_api_service.py`:
- Around line 293-299: The loop over model_info calling add_model_to_instance
can produce partial success (some models added, some failed) leaving the
instance in an inconsistent state; update the code in the model-addition block
(the loop that calls add_model_to_instance and the surrounding instance-creation
flow) to either perform an atomic operation or clean up on failure: wrap
instance creation + all add_model_to_instance calls in a DB transaction
(preferred) so the entire operation rolls back on any failure, or if
transactions are not available, track which models succeeded and on the first
failure delete the instance and any successfully-added models (use existing
delete_instance/remove_model_from_instance helpers), and change the return to a
structured response listing per-model success/failure instead of just
concatenated msg.
- Around line 250-258: Replace the Chinese comma character in the docstrings:
update the docstring that documents the model_info parameter (the block showing
"model_name": "name",) to use a standard ASCII comma (",") and likewise correct
the punctuation in the verify_api_key docstring referenced at line ~348; search
for the exact strings in provider_api_service.py (the model_info docstring and
the verify_api_key docstring) and swap any non-ASCII punctuation for the normal
ASCII equivalents to ensure consistent formatting.
- Around line 373-376: The list comprehension building factory_llms assumes
model.get("model_type") is a list, but callers may pass a string;
normalize/validate model_type before that comprehension by iterating over
model_info (or []) and converting any string model.get("model_type") into a
single-item list (or defaulting to [] when missing/None), so factory_llms can
safely iterate over model.get("model_type"); update the logic that prepares
model_info (or add a small pre-processing loop just above the factory_llms
comprehension) to perform this normalization for each model.
---
Outside diff comments:
In `@api/apps/restful_apis/provider_api.py`:
- Around line 200-231: The OpenAPI docstring for the list_provider_models
handler is missing the two new query parameters (api_key and base_url); update
the docstring inside the list_provider_models function to add parameter entries
for query parameters named "api_key" and "base_url" (type: string, required:
false, with short descriptions indicating they override the provider credentials
and base URL respectively) so the generated API docs reflect the actual handler
behavior.
- Around line 329-331: The OpenAPI schema for model_info is declared as type:
object but the handlers create_provider_instance and verify_provider_api_key
treat it as a list (defaulting to [] and service expects list[dict]); update the
OpenAPI/docstring for model_info in provider_api.py to type: array with items:
type: object (or items: { type: object }) and keep the default as [] so the spec
matches the actual handler/service expectation, and ensure any related parameter
documentation for create_provider_instance and verify_provider_api_key is
consistent with list[dict].
🪄 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: c4f3d52c-049a-4967-a372-e875e82bab3d
📒 Files selected for processing (2)
api/apps/restful_apis/provider_api.pyapi/apps/services/provider_api_service.py
| msg = "" | ||
| for model in model_info: | ||
| success, _msg = add_model_to_instance(tenant_id, provider_name, instance_name, **model) | ||
| if not success: | ||
| msg += _msg | ||
| if msg: | ||
| return False, msg |
There was a problem hiding this comment.
Partial failure leaves inconsistent state.
When iterating over model_info, if one model fails to add (e.g., duplicate check at line 584), the loop continues and accumulates errors. However, the instance and previously-added models remain in the database. This partial state may confuse users who see the instance created but with missing models.
Consider either:
- Rolling back the instance creation on any model failure, or
- Returning a structured response indicating which models succeeded/failed
🤖 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 `@api/apps/services/provider_api_service.py` around lines 293 - 299, The loop
over model_info calling add_model_to_instance can produce partial success (some
models added, some failed) leaving the instance in an inconsistent state; update
the code in the model-addition block (the loop that calls add_model_to_instance
and the surrounding instance-creation flow) to either perform an atomic
operation or clean up on failure: wrap instance creation + all
add_model_to_instance calls in a DB transaction (preferred) so the entire
operation rolls back on any failure, or if transactions are not available, track
which models succeeded and on the first failure delete the instance and any
successfully-added models (use existing
delete_instance/remove_model_from_instance helpers), and change the return to a
structured response listing per-model success/failure instead of just
concatenated msg.
| factory_llms = [{ | ||
| "model_type": _type, | ||
| "llm_name": model_info.get("model_name", ""), | ||
| } for _type in model_info.get("model_type", [])] | ||
| "llm_name": model.get("model_name", ""), | ||
| } for model in model_info if model for _type in model.get("model_type", []) ] |
There was a problem hiding this comment.
Missing validation for model_type being a list.
The comprehension at line 376 iterates over model.get("model_type", []), expecting it to be a list. If a caller passes model_type as a string (e.g., "chat" instead of ["chat"]), Python will iterate over characters ("c", "h", "a", "t"), producing invalid model type entries.
🛡️ Proposed fix to normalize model_type
factory_llms = [{
"model_type": _type,
"llm_name": model.get("model_name", ""),
- } for model in model_info if model for _type in model.get("model_type", []) ]
+ } for model in model_info if model for _type in (model.get("model_type", []) if isinstance(model.get("model_type"), list) else [model.get("model_type")]) if _type]Or validate earlier in the function:
for model in model_info or []:
if model and isinstance(model.get("model_type"), str):
model["model_type"] = [model["model_type"]]🤖 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 `@api/apps/services/provider_api_service.py` around lines 373 - 376, The list
comprehension building factory_llms assumes model.get("model_type") is a list,
but callers may pass a string; normalize/validate model_type before that
comprehension by iterating over model_info (or []) and converting any string
model.get("model_type") into a single-item list (or defaulting to [] when
missing/None), so factory_llms can safely iterate over model.get("model_type");
update the logic that prepares model_info (or add a small pre-processing loop
just above the factory_llms comprehension) to perform this normalization for
each model.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15711 +/- ##
=======================================
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:
|
…an, and Tencent Cloud (#15752) ### What problem does this PR solve? This PR adds `ModelMeta` implementations for four additional LLM/RAG ecosystem platforms, building on the ModelMeta infrastructure introduced in #15711. Currently, only `Ollama` and `VolcEngine` have `ModelMeta` classes that enable remote model list fetching. This PR extends that support to four more platforms. ### Changes Added four new `ModelMeta` subclasses in `rag/llm/model_meta.py`: | Platform | `_FACTORY_NAME` | Has model list | Has full model info | Approach | |----------|-----------------|----------------|---------------------|----------| | **Xinference** | `"Xinference"` | ✅ | ✅ | Parses `model_type` and `context_length` from `/v1/models` response. Maps 6 model types (LLM/embedding/rerank/image/TTS/speech2text). | | **LocalAI** | `"LocalAI"` | ✅ | ✅ | Uses Ollama-compatible `GET /api/tags` + `POST /api/show` endpoints. Returns capabilities (completion/embedding/vision/tools/thinking) and `general.context_length`. | | **BaiduYiyan** | `"BaiduYiyan"` | ✅ | ✅ | Uses Qianfan SDK static model catalog + `get_model_info()` for `max_input_tokens`. Returns 60 models (56 chat + 4 embedding) with real context lengths. | | **Tencent Cloud** | `"Tencent Cloud"` | ❌ | ❌ | `NotImplementedError` — uses SDK-based SID/SK HMAC signing, no model list REST API available. | All classes are automatically discovered and registered via the existing `__init__.py` mechanism — no additional configuration needed. ### Type of change - [x] New Feature (non-breaking change which adds functionality)
What problem does this PR solve?
Feat:
Type of change