Repository navigation
Fix: replace tenant_llm apis - #16131
Conversation
…low into fix/v0.26.1-model-provider
|
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)
📝 WalkthroughWalkthroughLegacy ChangesProvider/Model API Migration
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
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: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
admin/client/ragflow_client.py (1)
1076-1076:⚠️ Potential issue | 🔴 Critical | ⚡ Quick win
_get_default_modelsmethod is undefined - will cause AttributeError.This line calls
self._get_default_models()but the method was removed (per AI summary). This will crash at runtime withAttributeError: 'RAGFlowClient' object has no attribute '_get_default_models'.The same issue exists at line 1366 in
list_user_default_models.Either restore the method or migrate these callers to use the new API pattern.
🤖 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 `@admin/client/ragflow_client.py` at line 1076, The RAGFlowClient class calls the undefined method _get_default_models() at two locations: line 1076 in the default_models assignment and line 1366 in the list_user_default_models method. Either restore the _get_default_models method implementation that was removed, or replace both calls to this method with the appropriate new API pattern that is being used elsewhere in the codebase to retrieve default models.api/db/init_data.py (1)
89-101:⚠️ Potential issue | 🟠 Major | ⚡ Quick winModel validation may crash if provider instances aren't configured.
get_tenant_default_model_by_typeraises exceptions when the provider instance doesn't exist (seetenant_model_service.py:157-159). Since the oldinit_llm_factorythat seeded these configurations is now removed, a fresh installation withsettings.CHAT_MDLorsettings.EMBEDDING_MDLset but no provider configured will crash here.Consider wrapping in try/except to log warnings instead of crashing:
Suggested fix
if tenant["llm_id"]: - chat_model_config = get_tenant_default_model_by_type(tenant["id"], LLMType.CHAT) - chat_mdl = LLMBundle(tenant["id"], chat_model_config) - msg = asyncio.run(chat_mdl.async_chat(system="", history=[{"role": "user", "content": "Hello!"}], gen_conf={})) - if msg.find("ERROR: ") == 0: - logging.error("'{}' doesn't work. {}".format( tenant["llm_id"], msg)) + try: + chat_model_config = get_tenant_default_model_by_type(tenant["id"], LLMType.CHAT) + chat_mdl = LLMBundle(tenant["id"], chat_model_config) + msg = asyncio.run(chat_mdl.async_chat(system="", history=[{"role": "user", "content": "Hello!"}], gen_conf={})) + if msg.find("ERROR: ") == 0: + logging.error("'{}' doesn't work. {}".format(tenant["llm_id"], msg)) + except Exception as e: + logging.warning("Chat model '{}' validation skipped: {}".format(tenant["llm_id"], e)) if tenant["embd_id"]: - embd_model_config = get_tenant_default_model_by_type(tenant["id"], LLMType.EMBEDDING) - embd_mdl = LLMBundle(tenant["id"], embd_model_config) - v, c = embd_mdl.encode(["Hello!"]) - if c == 0: - logging.error("'{}' doesn't work!".format(tenant["embd_id"])) + try: + embd_model_config = get_tenant_default_model_by_type(tenant["id"], LLMType.EMBEDDING) + embd_mdl = LLMBundle(tenant["id"], embd_model_config) + v, c = embd_mdl.encode(["Hello!"]) + if c == 0: + logging.error("'{}' doesn't work!".format(tenant["embd_id"])) + except Exception as e: + logging.warning("Embedding model '{}' validation skipped: {}".format(tenant["embd_id"], e))🤖 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/db/init_data.py` around lines 89 - 101, The model validation code in the chat model validation block (where `get_tenant_default_model_by_type` is called for `LLMType.CHAT`) and the embedding model validation block (where `get_tenant_default_model_by_type` is called for `LLMType.EMBEDDING`) can crash if provider instances aren't configured. Wrap each of these validation blocks in try/except handlers to catch exceptions from `get_tenant_default_model_by_type`, the `LLMBundle` instantiation, the `async_chat` call, and the `encode` call. In the except blocks, log warnings using logging.warning instead of allowing the exception to propagate and crash the initialization.
🧹 Nitpick comments (3)
test/benchmark/cli.py (1)
229-244: ⚡ Quick winAdd logs around tenant default-model updates.
This new setup flow mutates tenant defaults in a loop without observability. Add per-model info/debug logs before/after each
set_default_modelcall.As per coding guidelines,
**/*.py: Add logging for new flows.Also applies to: 279-279
🤖 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 `@test/benchmark/cli.py` around lines 229 - 244, The function _set_default_models_from_args loops through model specifications and calls auth.set_default_model without any logging, making it difficult to observe what's happening during tenant default-model updates. Add info or debug log statements before and after each auth.set_default_model call within the loop to provide visibility into the model updates. The logs should include relevant context such as the model_id, type_key, model_provider, model_instance, and model_name being updated to help with debugging and observability.Source: Coding guidelines
test/benchmark/auth.py (1)
57-64: ⚡ Quick winAdd structured logging in the new provider/default-model flows.
These new API mutation/listing paths are currently silent unless they fail. Add debug/info logs so benchmark setup failures are diagnosable without reproducing locally.
♻️ Suggested patch
+import logging from typing import Any, Dict, Optional from .http_client import HttpClient +logger = logging.getLogger(__name__) + @@ def get_my_llms(client: HttpClient) -> Dict[str, Any]: @@ res = client.request_json("GET", "/providers", use_api_base=True, auth_kind="login") @@ providers = res.get("data", []) + logger.debug("Listed providers: count=%s", len(providers) if isinstance(providers, list) else "unknown") return {p.get("name", ""): p for p in providers} if isinstance(providers, list) else {} @@ def set_llm_api_key( @@ ) -> None: @@ + logger.info("Ensuring provider exists: %s", llm_factory) provider_payload = {"provider_name": llm_factory} @@ + logger.info("Ensuring default instance exists for provider: %s", llm_factory) instance_payload = { @@ def set_default_model( @@ ) -> None: @@ + logger.info( + "Setting tenant default model: type=%s provider=%s instance=%s model=%s", + model_type, + model_provider, + model_instance, + model_name, + ) res = client.request_json("PATCH", "/models/default", use_api_base=True, auth_kind="login", json_body=payload)As per coding guidelines,
**/*.py: Add logging for new flows.Also applies to: 66-90, 92-117
🤖 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 `@test/benchmark/auth.py` around lines 57 - 64, The get_my_llms function and related API interaction functions (also at lines 66-90 and 92-117) lack logging which makes benchmark setup failures difficult to diagnose. Add debug or info level logging to these functions to track execution flow, including when API calls are being made, successful responses with relevant data counts or details, and any conditional branching decisions. This will provide visibility into the benchmark setup process without requiring local reproduction of failures.Source: Coding guidelines
test/testcases/conftest.py (1)
224-251: ⚡ Quick winUse logger calls instead of
Switch the new diagnostic
print(...)lines tologging.info/warning(...)for consistent capture in CI and local test runs.As per coding guidelines,
**/*.py: Add logging for new flows.Also applies to: 329-333
🤖 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 `@test/testcases/conftest.py` around lines 224 - 251, Replace the two diagnostic print statements in the instance registration block with logging calls for consistency with CI and local test runs. The first print statement that outputs the "already exists, skipping" message and the second print statement that outputs the "blocked by API" message should both be changed to use logging.info() or logging.warning() instead of print(). Additionally, apply the same logging replacement to the print statements mentioned in lines 329-333 of the same file to maintain consistency throughout the test setup flow.Source: Coding guidelines
🤖 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 `@admin/client/ragflow_client.py`:
- Around line 782-790: The _MODEL_TYPE_MAP dictionary contains a typo where the
key is "reranker_id" but should be "rerank_id" to match the actual model type
keys used in the tenant model (as referenced in list_user_default_models and
tenant_model_service.py). Change the key from "reranker_id" to "rerank_id" in
the mapping so that users passing "rerank_id" as the model type will correctly
map to the "rerank" API value instead of encountering an "Unknown model type"
error.
In `@test/benchmark/cli.py`:
- Around line 202-216: The _parse_model_id function currently accepts empty
segments in the model_id string (e.g., "`@CI`@ZHIPU-AI" or "model@@provider")
without validation, causing failures to occur later in the backend. Add
validation after splitting the model_id by "@" to check that all resulting parts
are non-empty strings, and raise a clear, descriptive ValueError immediately if
any empty segments are detected. This ensures malformed inputs fail fast with a
client-side error rather than deferring to backend failures.
In `@test/testcases/conftest.py`:
- Around line 228-233: The requests.post call in the fixture lacks an explicit
timeout parameter, which can cause the HTTP request to block indefinitely during
network issues and hang the entire test session. Add a timeout parameter set to
30 seconds to the requests.post call shown in the diff. Additionally, apply the
same timeout parameter to all other requests calls throughout the conftest.py
file (approximately 9 total locations) to ensure consistent timeout handling
across all HTTP requests in the test fixtures.
---
Outside diff comments:
In `@admin/client/ragflow_client.py`:
- Line 1076: The RAGFlowClient class calls the undefined method
_get_default_models() at two locations: line 1076 in the default_models
assignment and line 1366 in the list_user_default_models method. Either restore
the _get_default_models method implementation that was removed, or replace both
calls to this method with the appropriate new API pattern that is being used
elsewhere in the codebase to retrieve default models.
In `@api/db/init_data.py`:
- Around line 89-101: The model validation code in the chat model validation
block (where `get_tenant_default_model_by_type` is called for `LLMType.CHAT`)
and the embedding model validation block (where
`get_tenant_default_model_by_type` is called for `LLMType.EMBEDDING`) can crash
if provider instances aren't configured. Wrap each of these validation blocks in
try/except handlers to catch exceptions from `get_tenant_default_model_by_type`,
the `LLMBundle` instantiation, the `async_chat` call, and the `encode` call. In
the except blocks, log warnings using logging.warning instead of allowing the
exception to propagate and crash the initialization.
---
Nitpick comments:
In `@test/benchmark/auth.py`:
- Around line 57-64: The get_my_llms function and related API interaction
functions (also at lines 66-90 and 92-117) lack logging which makes benchmark
setup failures difficult to diagnose. Add debug or info level logging to these
functions to track execution flow, including when API calls are being made,
successful responses with relevant data counts or details, and any conditional
branching decisions. This will provide visibility into the benchmark setup
process without requiring local reproduction of failures.
In `@test/benchmark/cli.py`:
- Around line 229-244: The function _set_default_models_from_args loops through
model specifications and calls auth.set_default_model without any logging,
making it difficult to observe what's happening during tenant default-model
updates. Add info or debug log statements before and after each
auth.set_default_model call within the loop to provide visibility into the model
updates. The logs should include relevant context such as the model_id,
type_key, model_provider, model_instance, and model_name being updated to help
with debugging and observability.
In `@test/testcases/conftest.py`:
- Around line 224-251: Replace the two diagnostic print statements in the
instance registration block with logging calls for consistency with CI and local
test runs. The first print statement that outputs the "already exists, skipping"
message and the second print statement that outputs the "blocked by API" message
should both be changed to use logging.info() or logging.warning() instead of
print(). Additionally, apply the same logging replacement to the print
statements mentioned in lines 329-333 of the same file to maintain consistency
throughout the test setup flow.
🪄 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: 5de53f9d-b205-4034-9c1d-a3f6f148e02e
📒 Files selected for processing (8)
admin/client/ragflow_client.pyapi/db/init_data.pyapi/db/services/llm_service.pysdk/python/test/conftest.pytest/benchmark/README.mdtest/benchmark/auth.pytest/benchmark/cli.pytest/testcases/conftest.py
💤 Files with no reviewable changes (2)
- api/db/services/llm_service.py
- sdk/python/test/conftest.py
| # Mapping from legacy model_type keys to API model_type values | ||
| _MODEL_TYPE_MAP = { | ||
| "llm_id": "chat", | ||
| "embd_id": "embedding", | ||
| "img2txt_id": "vision", | ||
| "reranker_id": "rerank", | ||
| "asr_id": "asr", | ||
| "tts_id": "tts", | ||
| } |
There was a problem hiding this comment.
Typo: reranker_id should be rerank_id.
The tenant model uses rerank_id (see list_user_default_models at line 1378 and tenant_model_service.py:154), but this map has reranker_id. Users passing rerank_id as the model type will get "Unknown model type" error.
_MODEL_TYPE_MAP = {
"llm_id": "chat",
"embd_id": "embedding",
"img2txt_id": "vision",
- "reranker_id": "rerank",
+ "rerank_id": "rerank",
"asr_id": "asr",
"tts_id": "tts",
}📝 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.
| # Mapping from legacy model_type keys to API model_type values | |
| _MODEL_TYPE_MAP = { | |
| "llm_id": "chat", | |
| "embd_id": "embedding", | |
| "img2txt_id": "vision", | |
| "reranker_id": "rerank", | |
| "asr_id": "asr", | |
| "tts_id": "tts", | |
| } | |
| # Mapping from legacy model_type keys to API model_type values | |
| _MODEL_TYPE_MAP = { | |
| "llm_id": "chat", | |
| "embd_id": "embedding", | |
| "img2txt_id": "vision", | |
| "rerank_id": "rerank", | |
| "asr_id": "asr", | |
| "tts_id": "tts", | |
| } |
🤖 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 `@admin/client/ragflow_client.py` around lines 782 - 790, The _MODEL_TYPE_MAP
dictionary contains a typo where the key is "reranker_id" but should be
"rerank_id" to match the actual model type keys used in the tenant model (as
referenced in list_user_default_models and tenant_model_service.py). Change the
key from "reranker_id" to "rerank_id" in the mapping so that users passing
"rerank_id" as the model type will correctly map to the "rerank" API value
instead of encountering an "Unknown model type" error.
| def _parse_model_id(model_id: str): | ||
| """Parse model_id into (model_name, model_instance, model_provider). | ||
|
|
||
| Accepted formats: | ||
| - model_name@instance@provider -> (model_name, instance, provider) | ||
| - model_name@provider -> (model_name, "default", provider) | ||
| - model_name -> (model_name, "default", "") | ||
| """ | ||
| parts = model_id.split("@") | ||
| if len(parts) >= 3: | ||
| return parts[0], parts[1], parts[-1] | ||
| elif len(parts) == 2: | ||
| return parts[0], "default", parts[1] | ||
| else: | ||
| return model_id, "default", "" |
There was a problem hiding this comment.
Validate malformed model_id inputs early.
_parse_model_id currently accepts empty segments (e.g. @CI@ZHIPU-AI, model@@provider) and defers failure to backend PATCH errors. Validate and fail fast with a clear client-side error.
🐛 Suggested patch
-def _parse_model_id(model_id: str):
+def _parse_model_id(model_id: str) -> tuple[str, str, str]:
@@
- parts = model_id.split("@")
- if len(parts) >= 3:
- return parts[0], parts[1], parts[-1]
- elif len(parts) == 2:
- return parts[0], "default", parts[1]
- else:
- return model_id, "default", ""
+ parts = [p.strip() for p in model_id.split("@")]
+ if len(parts) == 1:
+ if not parts[0]:
+ raise AuthError("Invalid model_id: model name is required")
+ return parts[0], "default", ""
+ if len(parts) == 2:
+ model_name, provider = parts
+ if not model_name or not provider:
+ raise AuthError(f"Invalid model_id '{model_id}': expected <model>@<provider>")
+ return model_name, "default", provider
+ if len(parts) == 3:
+ model_name, instance, provider = parts
+ if not model_name or not instance or not provider:
+ raise AuthError(f"Invalid model_id '{model_id}': expected <model>@<instance>@<provider>")
+ return model_name, instance, provider
+ raise AuthError(
+ f"Invalid model_id '{model_id}': expected <model>, <model>@<provider>, or <model>@<instance>@<provider>"
+ )🤖 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 `@test/benchmark/cli.py` around lines 202 - 216, The _parse_model_id function
currently accepts empty segments in the model_id string (e.g., "`@CI`@ZHIPU-AI" or
"model@@provider") without validation, causing failures to occur later in the
backend. Add validation after splitting the model_id by "@" to check that all
resulting parts are non-empty strings, and raise a clear, descriptive ValueError
immediately if any empty segments are detected. This ensures malformed inputs
fail fast with a client-side error rather than deferring to backend failures.
| add_instance_response = requests.post(url=add_instance_api, headers=authorization, json={ | ||
| "instance_name": instance_name, | ||
| "api_key": api_key, | ||
| "region": "default", | ||
| "base_url": "" | ||
| }) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
python - <<'PY'
import pathlib, re
path = pathlib.Path("test/testcases/conftest.py")
lines = path.read_text(encoding="utf-8").splitlines()
for i, line in enumerate(lines, 1):
if re.search(r"requests\.(post|get|put|patch|delete)\(", line):
window = " ".join(lines[i-1:i+10])
if "timeout=" not in window:
print(f"Possible missing timeout near Line {i}: {line.strip()}")
PYRepository: infiniflow/ragflow
Length of output: 975
🏁 Script executed:
cat -n test/testcases/conftest.py | sed -n '130,140p;140,150p;160,170p;170,180p;205,215p;225,235p;278,290p;298,310p;315,330p'Repository: infiniflow/ragflow
Length of output: 4895
Add explicit timeouts to the new outbound HTTP calls.
These fixture calls can block indefinitely on network issues and hang the whole test session. The issue affects multiple requests calls throughout the file (at least 9 total locations). The suggested timeout value of 30 seconds is reasonable for CI/test scenarios.
🐛 Suggested patch
+REQUEST_TIMEOUT_S = 30
@@
add_instance_response = requests.post(url=add_instance_api, headers=authorization, json={
"instance_name": instance_name,
"api_key": api_key,
"region": "default",
"base_url": ""
- })
+ }, timeout=REQUEST_TIMEOUT_S)
@@
set_default_rerank_response = requests.patch(
url=url,
headers=authorization,
json={
"model_provider": "SILICONFLOW",
"model_instance": "CI",
"model_type": "rerank",
"model_name": "BAAI/bge-reranker-v2-m3"
- }
+ },
+ timeout=REQUEST_TIMEOUT_S,
)🤖 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 `@test/testcases/conftest.py` around lines 228 - 233, The requests.post call in
the fixture lacks an explicit timeout parameter, which can cause the HTTP
request to block indefinitely during network issues and hang the entire test
session. Add a timeout parameter set to 30 seconds to the requests.post call
shown in the diff. Additionally, apply the same timeout parameter to all other
requests calls throughout the conftest.py file (approximately 9 total locations)
to ensure consistent timeout handling across all HTTP requests in the test
fixtures.
Source: Linters/SAST tools
What problem does this PR solve?
Replace tenant_llm apis with provider-instance apis.
Type of change