Skip to content

Feat: get model list from remote - #15711

Merged
wangq8 merged 4 commits into
infiniflow:mainfrom
Lynn-Inf:feat/model-list
Jun 8, 2026
Merged

wangq8 merged 4 commits into
infiniflow:mainfrom
Lynn-Inf:feat/model-list

Conversation

@Lynn-Inf

@Lynn-Inf Lynn-Inf commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Feat:

  • Get model list from remote provider.

Type of change

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

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 5, 2026
@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: dbd53e65-cbd1-4d4a-bda6-91fd13c0149d

📥 Commits

Reviewing files that changed from the base of the PR and between 3ca321d and c25b869.

📒 Files selected for processing (1)
  • rag/llm/model_meta.py
💤 Files with no reviewable changes (1)
  • rag/llm/model_meta.py

📝 Walkthrough

Walkthrough

This 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 model_info to a list shape for create/verify flows.

Changes

Remote Model Discovery Integration

Layer / File(s) Summary
Model metadata framework
rag/llm/model_meta.py
Introduces abstract Base provider with API-key/base_url handling, async HTTP fetch, and formatting hook; adds VolcEngine stub and Ollama implementation that fetches /api/tags and per-model /api/show, mapping capabilities to LLMType, features, and max_tokens.
Registry definition and export
rag/llm/__init__.py
Defines ModelMeta registry, registers it in MODULE_MAPPING under "model_meta" for dynamic population, and exports it via __all__.
Service model discovery & model_info shape changes
api/apps/services/provider_api_service.py
Converts list_provider_models to async with optional api_key and base_url; builds static_llms from FACTORY_LLM_INFOS, optionally fetches remote_models via ModelMeta[provider_name], requires at least one non-empty source, merges remote over static by name, and updates create_provider_instance/verify_api_key to accept model_info: list[dict] and iterate/expand entries.
Route handler async update & request shape defaults
api/apps/restful_apis/provider_api.py
Converts list_provider_models handler to async, reads api_key and base_url from query args and awaits the service call; updates create_provider_instance and verify_provider_api_key to default model_info to [].

Sequence Diagram

sequenceDiagram
  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)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I fetched the tags and hopped through each show,
Merged local and remote so the model lists grow,
Async paws tapped, requests carried along,
Credentials passed gently, responses turned strong,
A tiny rabbit cheers: discovery's a song!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 45.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: adding functionality to retrieve model lists from remote providers, which aligns with the PR's primary objective.
Description check ✅ Passed The description follows the template structure with required sections present, but the problem statement is minimal and the feature explanation could be more detailed.
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.

✏️ 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.

❤️ Share

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

@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: 7

🧹 Nitpick comments (2)
api/apps/restful_apis/provider_api.py (1)

202-242: ⚡ Quick win

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

Add 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 res

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 `@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

📥 Commits

Reviewing files that changed from the base of the PR and between 1deb131 and 781742f.

📒 Files selected for processing (4)
  • api/apps/restful_apis/provider_api.py
  • api/apps/services/provider_api_service.py
  • rag/llm/__init__.py
  • rag/llm/model_meta.py

"""
try:
success, result = provider_api_service.list_provider_models(provider_name)
api_key = request.args.get("api_key")

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 | ⚡ Quick win

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.

Comment on lines +191 to +193
remote_models = []
if provider_name in ModelMeta:
remote_models = await ModelMeta[provider_name](api_key, model_base_url).get_model_list()

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 | ⚡ Quick win

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 only

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

Suggested change
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.

Comment thread rag/llm/model_meta.py
Comment on lines +31 to +36
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"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Comment thread rag/llm/model_meta.py
Comment on lines +38 to +46
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()

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 | ⚡ Quick win

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.

Comment thread rag/llm/model_meta.py
Comment on lines +61 to +63
def get_model_list(self):
# todo implement access token auth
raise NotImplementedError

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 | ⚡ Quick win

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.

Suggested change
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.

Comment thread rag/llm/model_meta.py Resolved
Comment thread rag/llm/model_meta.py
Comment on lines +106 to +111
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)

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 | ⚡ Quick win

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.

@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: 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 win

OpenAPI docstring missing new query parameters.

The handler now accepts api_key and base_url from 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 win

OpenAPI spec shows model_info as object, but it's now a list.

The docstring declares model_info as type: object (line 330), but the handler now defaults it to [] and the service expects list[dict]. This mismatches the actual API contract. The same issue exists at lines 398-400 for verify_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

📥 Commits

Reviewing files that changed from the base of the PR and between 781742f and 3ca321d.

📒 Files selected for processing (2)
  • api/apps/restful_apis/provider_api.py
  • api/apps/services/provider_api_service.py

Comment on lines +293 to 299
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

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 | ⚡ Quick win

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:

  1. Rolling back the instance creation on any model failure, or
  2. 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.

Comment on lines 373 to +376
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", []) ]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

@Lynn-Inf Lynn-Inf added the ci Continue Integration label Jun 8, 2026
@Lynn-Inf
Lynn-Inf marked this pull request as draft June 8, 2026 02:27
@Lynn-Inf
Lynn-Inf marked this pull request as ready for review June 8, 2026 02:27
@codecov

codecov Bot commented Jun 8, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (b0a4580) to head (c25b869).

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

@wangq8
wangq8 merged commit b05d5a5 into infiniflow:main Jun 8, 2026
1 check passed
This was referenced Jun 8, 2026
wangq8 pushed a commit that referenced this pull request Jun 8, 2026
…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)
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. size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants