Repository navigation
Fix: model list - #15860
Fix: model list#15860
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughDisables automatic tenant-scoped TenantLLM init/persistence and related deletions; adds env-driven OpenDataLoader helpers and tenant-model query APIs; migrates OCR and embedding model-name resolution to the new helpers; adds a deprecation TODO for the legacy LLM factory. ChangesOCR and Embedding Model Management Refactor
Sequence Diagram(s)sequenceDiagram
participant EnvCollector
participant TenantModelJointService
participant TenantModelService
EnvCollector->>TenantModelJointService: _ensure_ocr_provider_from_env(OPENDATALOADER_ENV_KEYS, OPENDATALOADER_DEFAULT_CONFIG)
TenantModelJointService->>TenantModelService: aggregate TenantModel rows by provider instances and model_type
TenantModelService->>TenantModelService: return model list (tenant-scoped)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (1 warning, 2 inconclusive)
✅ Passed checks (2 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: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
rag/app/naive.py (3)
287-291:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winSame attribute bug:
llm_nameshould bemodel_name.Same issue as the other OCR parsers.
🐛 Proposed fix
candidates = get_models_by_tenant_and_provider_and_model_type(tenant_id=tenant_id, provider_name="PaddleOCR", model_type=LLMType.OCR) if candidates: - paddleocr_llm_name = candidates[0].llm_name + paddleocr_llm_name = candidates[0].model_name elif env_name: paddleocr_llm_name = env_name🤖 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/app/naive.py` around lines 287 - 291, The code uses the wrong attribute name for the returned candidate model; in the get_models_by_tenant_and_provider_and_model_type result you should access model_name instead of llm_name—update the assignment to set paddleocr_llm_name = candidates[0].model_name (and keep the existing fallback to env_name unchanged) so the OCR parser uses the correct model attribute; locate this in the block that calls get_models_by_tenant_and_provider_and_model_type and updates paddleocr_llm_name.
226-230:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winSame attribute bug:
llm_nameshould bemodel_name.Same issue as in
by_mineru- accessing non-existentllm_nameattribute.🐛 Proposed fix
candidates = get_models_by_tenant_and_provider_and_model_type(tenant_id=tenant_id, provider_name="OpenDataLoader", model_type=LLMType.OCR) if candidates: - opendataloader_llm_name = candidates[0].llm_name + opendataloader_llm_name = candidates[0].model_name elif env_name: opendataloader_llm_name = env_name🤖 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/app/naive.py` around lines 226 - 230, The code in the branch that sets opendataloader_llm_name uses a non-existent attribute llm_name on the returned candidate objects; update the assignment to use the correct attribute model_name (i.e., when handling the first candidate from get_models_by_tenant_and_provider_and_model_type(tenant_id=tenant_id, provider_name="OpenDataLoader", model_type=LLMType.OCR), set opendataloader_llm_name = candidates[0].model_name) and keep the existing fallback to env_name unchanged.
143-147:⚠️ Potential issue | 🔴 CriticalFix runtime AttributeError when selecting MinerU OCR model
In
rag/app/naive.py(by_mineru),candidates[0]is aTenantModelinstance, which exposesmodel_name(notllm_name). The currentcandidates[0].llm_nameaccess can raiseAttributeErrorat runtime.🐛 Proposed fix
candidates = get_models_by_tenant_and_provider_and_model_type(tenant_id=tenant_id, provider_name="MinerU", model_type=LLMType.OCR) if candidates: - mineru_llm_name = candidates[0].llm_name + mineru_llm_name = candidates[0].model_name elif env_name: mineru_llm_name = env_name🤖 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/app/naive.py` around lines 143 - 147, In by_mineru, the code reads candidates[0].llm_name but TenantModel exposes model_name, causing an AttributeError; update the selection logic in by_mineru (the block that calls get_models_by_tenant_and_provider_and_model_type) to use candidates[0].model_name instead of llm_name and keep the existing fallback to env_name so mineru_llm_name is set to the TenantModel.model_name when candidates exist, otherwise to env_name.
🧹 Nitpick comments (4)
api/db/joint_services/tenant_model_service.py (2)
266-266: 💤 Low valueInconsistent logger usage.
Line 266 uses
logging.warningdirectly, but the module defineslogger = logging.getLogger(__name__)at line 28. For consistent, named logging, uselogger.warning(...)instead.The same issue applies to lines 338-339 and 410-411.
♻️ Suggested fix
- logging.warning("MinerU env model %s already exists for tenant %s, retry with next name", candidate, tenant_id) + logger.warning("MinerU env model %s already exists for tenant %s, retry with next name", candidate, tenant_id)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/db/joint_services/tenant_model_service.py` at line 266, Replace direct calls to the root logging module with the module-level logger instance to ensure consistent named logging: change any usage of logging.warning(...) to logger.warning(...) in tenant_model_service.py (notably the occurrence in the candidate-name retry message inside the function that generates MinerU env model names and the two occurrences around lines 338-339 and 410-411). Locate the functions/methods that perform tenant model creation/retry and update those logging calls to use the existing logger = logging.getLogger(__name__) defined at the top of the module so all warnings are emitted via logger.warning(...).
200-413: ⚖️ Poor tradeoffConsider extracting shared logic into a generic helper.
The three
ensure_*_from_envfunctions share ~90% identical code. A single parameterized helper would reduce duplication and maintenance burden:def _ensure_ocr_model_from_env( tenant_id: str, provider_name: str, collect_env_config_fn, default_config: dict, env_keys: list, base_name: str, ) -> str | None: # shared implementationThis is optional given the current scope but would improve maintainability if more OCR providers are added.
🤖 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/joint_services/tenant_model_service.py` around lines 200 - 413, The three functions ensure_mineru_from_env, ensure_paddleocr_from_env, and ensure_opendataloader_from_env duplicate almost identical logic; extract a single parameterized helper (e.g. _ensure_ocr_model_from_env with params tenant_id, provider_name, collect_env_config_fn, default_config, env_keys, base_name) that implements: collect cfg, parse api_key, find provider and matching instance/models, compute used_names, iterate candidate names, create provider/instance and insert model, and handle IntegrityError retry; then simplify each ensure_*_from_env to call this helper with the appropriate provider name, env collector (TenantLLMService._collect_*_env_config), DEFAULT_CONFIG constant, ENV_KEYS list, and base_name to remove duplication and centralize behavior.api/apps/restful_apis/user_api.py (1)
30-33: 💤 Low valueRemove unused imports.
These imports are no longer used after commenting out the LLM initialization:
TenantLLM(line 30)get_init_tenant_llm(line 32)TenantLLMService(line 33)🤖 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/user_api.py` around lines 30 - 33, Remove the three unused imports from the top of the module: TenantLLM, get_init_tenant_llm, and TenantLLMService; locate them in the import block that also imports FileService and simply delete those three identifiers so only used imports remain (you can run the linter/flake8 or mypy after to verify no references remain).admin/server/auth.py (1)
136-139: 💤 Low valueRemove commented-out code instead of leaving it.
Commented-out code can confuse future maintainers. If the LLM initialization is being permanently removed, delete these lines. If this is a temporary change, consider adding a TODO comment explaining when/why it should be restored.
🤖 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/server/auth.py` around lines 136 - 139, Remove the two commented-out LLM-related lines (the call to get_init_tenant_llm and the TenantLLMService.insert_many) instead of leaving them in place; if this LLM initialization is intended to be temporary, replace the commented lines with a single TODO that references get_init_tenant_llm and TenantLLMService.insert_many explaining when/why to restore them, otherwise delete them so only TenantService.insert(**tenant) and UserTenantService.insert(**usr_tenant) remain.
🤖 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/db/services/tenant_model_service.py`:
- Around line 38-45: The method
TenantModelService.get_by_provider_id_and_instance_id_and_model_type currently
uses cls.model.get_or_none (returns a single TenantModel or None) but callers
expect an iterable and call extend(); change the method to return a list: fetch
the single object with cls.model.get_or_none (or use a select/filter) and then
return [obj] if obj is not None else [] so callers can safely call
results.extend(models); update the method body to wrap the get_or_none result
into a list rather than returning the raw object.
In `@rag/flow/parser/parser.py`:
- Around line 453-456: In parser.py, the code that selects a fallback model uses
candidates[0].llm_name but the model objects expose model_name; update the
selection to read candidates[0].model_name (within the
get_models_by_tenant_and_provider_and_model_type result handling) so the
function get_models_by_tenant_and_provider_and_model_type and the surrounding
branch that returns a model name use the correct attribute (replace llm_name
with model_name).
- Around line 374-377: The code calls
get_models_by_tenant_and_provider_and_model_type and then returns
candidates[0].llm_name, but the TenantModel defines model_name (same bug as in
naive.py); update the attribute access to return candidates[0].model_name
(preserving the same fallback to env_name) so
get_models_by_tenant_and_provider_and_model_type, the candidates handling, and
the LLMType.OCR branch use model_name correctly.
- Around line 558-561: The code accesses a non-existent attribute llm_name on
candidate objects; in the block using
get_models_by_tenant_and_provider_and_model_type(tenant_id=tenant_id,
provider_name="PaddleOCR", model_type=LLMType.OCR) replace
candidates[0].llm_name with candidates[0].model_name so the correct property is
used (keep the existing fallback to env_name).
---
Outside diff comments:
In `@rag/app/naive.py`:
- Around line 287-291: The code uses the wrong attribute name for the returned
candidate model; in the get_models_by_tenant_and_provider_and_model_type result
you should access model_name instead of llm_name—update the assignment to set
paddleocr_llm_name = candidates[0].model_name (and keep the existing fallback to
env_name unchanged) so the OCR parser uses the correct model attribute; locate
this in the block that calls get_models_by_tenant_and_provider_and_model_type
and updates paddleocr_llm_name.
- Around line 226-230: The code in the branch that sets opendataloader_llm_name
uses a non-existent attribute llm_name on the returned candidate objects; update
the assignment to use the correct attribute model_name (i.e., when handling the
first candidate from
get_models_by_tenant_and_provider_and_model_type(tenant_id=tenant_id,
provider_name="OpenDataLoader", model_type=LLMType.OCR), set
opendataloader_llm_name = candidates[0].model_name) and keep the existing
fallback to env_name unchanged.
- Around line 143-147: In by_mineru, the code reads candidates[0].llm_name but
TenantModel exposes model_name, causing an AttributeError; update the selection
logic in by_mineru (the block that calls
get_models_by_tenant_and_provider_and_model_type) to use
candidates[0].model_name instead of llm_name and keep the existing fallback to
env_name so mineru_llm_name is set to the TenantModel.model_name when candidates
exist, otherwise to env_name.
---
Nitpick comments:
In `@admin/server/auth.py`:
- Around line 136-139: Remove the two commented-out LLM-related lines (the call
to get_init_tenant_llm and the TenantLLMService.insert_many) instead of leaving
them in place; if this LLM initialization is intended to be temporary, replace
the commented lines with a single TODO that references get_init_tenant_llm and
TenantLLMService.insert_many explaining when/why to restore them, otherwise
delete them so only TenantService.insert(**tenant) and
UserTenantService.insert(**usr_tenant) remain.
In `@api/apps/restful_apis/user_api.py`:
- Around line 30-33: Remove the three unused imports from the top of the module:
TenantLLM, get_init_tenant_llm, and TenantLLMService; locate them in the import
block that also imports FileService and simply delete those three identifiers so
only used imports remain (you can run the linter/flake8 or mypy after to verify
no references remain).
In `@api/db/joint_services/tenant_model_service.py`:
- Line 266: Replace direct calls to the root logging module with the
module-level logger instance to ensure consistent named logging: change any
usage of logging.warning(...) to logger.warning(...) in tenant_model_service.py
(notably the occurrence in the candidate-name retry message inside the function
that generates MinerU env model names and the two occurrences around lines
338-339 and 410-411). Locate the functions/methods that perform tenant model
creation/retry and update those logging calls to use the existing logger =
logging.getLogger(__name__) defined at the top of the module so all warnings are
emitted via logger.warning(...).
- Around line 200-413: The three functions ensure_mineru_from_env,
ensure_paddleocr_from_env, and ensure_opendataloader_from_env duplicate almost
identical logic; extract a single parameterized helper (e.g.
_ensure_ocr_model_from_env with params tenant_id, provider_name,
collect_env_config_fn, default_config, env_keys, base_name) that implements:
collect cfg, parse api_key, find provider and matching instance/models, compute
used_names, iterate candidate names, create provider/instance and insert model,
and handle IntegrityError retry; then simplify each ensure_*_from_env to call
this helper with the appropriate provider name, env collector
(TenantLLMService._collect_*_env_config), DEFAULT_CONFIG constant, ENV_KEYS
list, and base_name to remove duplication and centralize behavior.
🪄 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: acc275a9-8839-403d-95c6-1e3223652a4f
📒 Files selected for processing (10)
admin/server/auth.pyapi/apps/restful_apis/chunk_api.pyapi/apps/restful_apis/user_api.pyapi/apps/services/dataset_api_service.pyapi/db/init_data.pyapi/db/joint_services/tenant_model_service.pyapi/db/joint_services/user_account_service.pyapi/db/services/tenant_model_service.pyrag/app/naive.pyrag/flow/parser/parser.py
| @classmethod | ||
| @DB.connection_context() | ||
| def get_by_provider_id_and_instance_id_and_model_type(cls, provider_id, instance_id, model_type): | ||
| return cls.model.get_or_none( | ||
| cls.model.provider_id == provider_id, | ||
| cls.model.instance_id == instance_id, | ||
| cls.model.model_type == model_type | ||
| ) |
There was a problem hiding this comment.
Method returns single object but caller expects a list.
get_or_none() returns a single TenantModel or None, but the caller at api/db/joint_services/tenant_model_service.py:429-431 does:
models = TenantModelService.get_by_provider_id_and_instance_id_and_model_type(...)
if models:
results.extend(models)Calling extend() on a non-list object will fail or produce incorrect results. Either return a list like the similar method at lines 25-26, or have the caller use append().
🐛 Recommended fix: return a list
`@classmethod`
`@DB.connection_context`()
def get_by_provider_id_and_instance_id_and_model_type(cls, provider_id, instance_id, model_type):
- return cls.model.get_or_none(
+ return list(cls.model.select().where(
cls.model.provider_id == provider_id,
cls.model.instance_id == instance_id,
cls.model.model_type == 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/db/services/tenant_model_service.py` around lines 38 - 45, The method
TenantModelService.get_by_provider_id_and_instance_id_and_model_type currently
uses cls.model.get_or_none (returns a single TenantModel or None) but callers
expect an iterable and call extend(); change the method to return a list: fetch
the single object with cls.model.get_or_none (or use a select/filter) and then
return [obj] if obj is not None else [] so callers can safely call
results.extend(models); update the method body to wrap the get_or_none result
into a list rather than returning the raw object.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15860 +/- ##
=======================================
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:
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
test/testcases/restful_api/test_user_tenant_routes_unit.py (1)
1052-1055: ⚡ Quick winRemove unused
_RaisingDeleteQueryclass.The
_RaisingDeleteQueryclass appears to be dead code left over from the removal of tenant_llm deletion logic. Sincerollback_user_registrationno longer deletes tenant_llm records, this mock is no longer needed.🧹 Proposed cleanup
monkeypatch.setattr(module.TenantService, "delete_by_id", lambda _tenant_id: (_ for _ in ()).throw(RuntimeError("t boom"))) monkeypatch.setattr(module.UserTenantService, "query", lambda **_kwargs: (_ for _ in ()).throw(RuntimeError("ut boom"))) - class _RaisingDeleteQuery: - def where(self, *_args, **_kwargs): - raise RuntimeError("llm boom") - module.rollback_user_registration("user-2")🤖 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/restful_api/test_user_tenant_routes_unit.py` around lines 1052 - 1055, Remove the dead mock class _RaisingDeleteQuery from the test file since rollback_user_registration no longer deletes tenant_llm records; locate the class definition "class _RaisingDeleteQuery" in test_user_tenant_routes_unit.py and delete it (and any imports or references only used by that class) so the test contains only relevant mocks for current rollback_user_registration behavior.
🤖 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.
Nitpick comments:
In `@test/testcases/restful_api/test_user_tenant_routes_unit.py`:
- Around line 1052-1055: Remove the dead mock class _RaisingDeleteQuery from the
test file since rollback_user_registration no longer deletes tenant_llm records;
locate the class definition "class _RaisingDeleteQuery" in
test_user_tenant_routes_unit.py and delete it (and any imports or references
only used by that class) so the test contains only relevant mocks for current
rollback_user_registration behavior.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 759c8cc7-1855-4606-8ecb-0e6ecba0a64b
📒 Files selected for processing (1)
test/testcases/restful_api/test_user_tenant_routes_unit.py
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 (1)
rag/app/naive.py (1)
222-229:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winIncomplete OpenDataLoader refactoring spans two files.
Both
rag/app/naive.py(lines 222–229) andrag/flow/parser/parser.py(lines 450–456) suffer from:
- Runtime crash: accessing
.llm_nameonTenantModel(which definesmodel_name, notllm_name)- Inconsistent pattern: manually selecting the first candidate instead of using
get_first_provider_model_name(...)like MinerU/PaddleOCRThe shared root cause is incomplete migration to the unified helper. Adopt the same pattern across all three OCR providers.
🤖 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/app/naive.py` around lines 222 - 229, The code in the OpenDataLoader selection block incorrectly accesses TenantModel.llm_name and manually picks candidates[0], causing crashes and inconsistency; replace this manual logic with a call to the unified helper get_first_provider_model_name(tenant_id, provider_name="OpenDataLoader", model_type=LLMType.OCR) and fall back to ensure_opendataloader_from_env(tenant_id) only if that helper returns None, and ensure you read the model name via the helper (or TenantModel.model_name) rather than .llm_name; update the selection in the opendataloader logic in the naive flow to match the MinerU/PaddleOCR pattern.
🧹 Nitpick comments (1)
api/db/joint_services/tenant_model_service.py (1)
309-325: ⚡ Quick winAdd logging for model aggregation query.
This new helper lacks logging. Debugging tenant-specific model lookups requires visibility into what was found.
📝 Suggested logging
def get_models_by_tenant_and_provider_and_model_type(tenant_id: str, provider_name: str, model_type: str): """ Query TenantModel records by tenant_id, provider_name and model_name. Returns all matching model records under all instances of the specified provider. """ provider_obj = TenantModelProviderService.get_by_tenant_id_and_provider_name(tenant_id, provider_name) if not provider_obj: + logger.debug(f"Provider {provider_name} not found for tenant {tenant_id}") return [] instances = TenantModelInstanceService.get_all_by_provider_id(provider_obj.id) if not instances: + logger.debug(f"No instances found for provider {provider_name}, tenant {tenant_id}") return [] results = [] for inst in instances: models = TenantModelService.get_by_provider_id_and_instance_id_and_model_type(provider_obj.id, inst.id, model_type) if models: results.extend(models) + logger.debug(f"Found {len(results)} {model_type} models for {provider_name}, tenant {tenant_id}") return resultsAs per coding guidelines,
**/*.py: Add logging for new flows.🤖 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/joint_services/tenant_model_service.py` around lines 309 - 325, The function get_models_by_tenant_and_provider_and_model_type lacks any logging; add logs inside that function (using the module logger) to record key events and counts: log when provider_obj is not found (include tenant_id and provider_name), log the number of instances returned from TenantModelInstanceService.get_all_by_provider_id(provider_obj.id), for each inst log the instance id and number of models returned by TenantModelService.get_by_provider_id_and_instance_id_and_model_type(provider_obj.id, inst.id, model_type), and finally log the total number of aggregated results before returning; place logs at appropriate levels (info/debug) to aid debugging of tenant-specific model lookups.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 `@api/db/joint_services/tenant_model_service.py`:
- Around line 76-110: The _ensure_ocr_provider_from_env function performs DB
inserts and lookups without any logs; add structured logging at key steps in
_ensure_ocr_provider_from_env: log when config is missing, when a
TenantModelProviderService lookup misses and you insert a provider (include
tenant_id and provider_name), when creating a TenantModelInstance via
TenantModelInstanceService.create_instance (include provider_id, model_name and
a masked/partial api_key), when inserting a TenantModelService model (include
provider_id, instance_id, model_name and model_type), and log any unexpected
failures or exceptions around these calls; use the module logger (or
logging.getLogger(__name__)) and avoid logging full secrets (mask api_key) to
meet guidelines.
- Around line 50-62: Add structured logging to the get_first_provider_model_name
flow: import and use the module logger and add logs in
TenantModelProviderService/TenantModelInstanceService/TenantModelService
interaction points — log when no provider found for tenant_id/provider_name, log
when skipping an instance because instance_obj.status !=
ActiveStatusEnum.ACTIVE.value (include instance id/name and
tenant_id/provider_name), log when skipping a model because model_obj.status !=
ActiveStatusEnum.ACTIVE.value or model_obj.model_type mismatch (include model
id/name/type), and log the resolved model string right before the return in
get_first_provider_model_name. Ensure logs include tenant_id, provider_name,
instance_obj.id/instance_name and model_obj.model_name to aid tenant-specific
debugging.
- Line 20: The file currently imports IntegrityError but never uses it; remove
the unused import by deleting IntegrityError from the import statement at the
top (the "from peewee import IntegrityError" reference) so the module no longer
contains a dead import and lints cleanly.
---
Outside diff comments:
In `@rag/app/naive.py`:
- Around line 222-229: The code in the OpenDataLoader selection block
incorrectly accesses TenantModel.llm_name and manually picks candidates[0],
causing crashes and inconsistency; replace this manual logic with a call to the
unified helper get_first_provider_model_name(tenant_id,
provider_name="OpenDataLoader", model_type=LLMType.OCR) and fall back to
ensure_opendataloader_from_env(tenant_id) only if that helper returns None, and
ensure you read the model name via the helper (or TenantModel.model_name) rather
than .llm_name; update the selection in the opendataloader logic in the naive
flow to match the MinerU/PaddleOCR pattern.
---
Nitpick comments:
In `@api/db/joint_services/tenant_model_service.py`:
- Around line 309-325: The function
get_models_by_tenant_and_provider_and_model_type lacks any logging; add logs
inside that function (using the module logger) to record key events and counts:
log when provider_obj is not found (include tenant_id and provider_name), log
the number of instances returned from
TenantModelInstanceService.get_all_by_provider_id(provider_obj.id), for each
inst log the instance id and number of models returned by
TenantModelService.get_by_provider_id_and_instance_id_and_model_type(provider_obj.id,
inst.id, model_type), and finally log the total number of aggregated results
before returning; place logs at appropriate levels (info/debug) to aid debugging
of tenant-specific model lookups.
🪄 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: 7465d05d-e9b5-4069-b76c-4c28c2793de0
📒 Files selected for processing (3)
api/db/joint_services/tenant_model_service.pyrag/app/naive.pyrag/flow/parser/parser.py
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
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 (1)
rag/app/naive.py (1)
222-229:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winIncomplete OpenDataLoader refactoring spans two files.
Both
rag/app/naive.py(lines 222–229) andrag/flow/parser/parser.py(lines 450–456) suffer from:
- Runtime crash: accessing
.llm_nameonTenantModel(which definesmodel_name, notllm_name)- Inconsistent pattern: manually selecting the first candidate instead of using
get_first_provider_model_name(...)like MinerU/PaddleOCRThe shared root cause is incomplete migration to the unified helper. Adopt the same pattern across all three OCR providers.
🤖 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/app/naive.py` around lines 222 - 229, The code in the OpenDataLoader selection block incorrectly accesses TenantModel.llm_name and manually picks candidates[0], causing crashes and inconsistency; replace this manual logic with a call to the unified helper get_first_provider_model_name(tenant_id, provider_name="OpenDataLoader", model_type=LLMType.OCR) and fall back to ensure_opendataloader_from_env(tenant_id) only if that helper returns None, and ensure you read the model name via the helper (or TenantModel.model_name) rather than .llm_name; update the selection in the opendataloader logic in the naive flow to match the MinerU/PaddleOCR pattern.
🧹 Nitpick comments (1)
api/db/joint_services/tenant_model_service.py (1)
309-325: ⚡ Quick winAdd logging for model aggregation query.
This new helper lacks logging. Debugging tenant-specific model lookups requires visibility into what was found.
📝 Suggested logging
def get_models_by_tenant_and_provider_and_model_type(tenant_id: str, provider_name: str, model_type: str): """ Query TenantModel records by tenant_id, provider_name and model_name. Returns all matching model records under all instances of the specified provider. """ provider_obj = TenantModelProviderService.get_by_tenant_id_and_provider_name(tenant_id, provider_name) if not provider_obj: + logger.debug(f"Provider {provider_name} not found for tenant {tenant_id}") return [] instances = TenantModelInstanceService.get_all_by_provider_id(provider_obj.id) if not instances: + logger.debug(f"No instances found for provider {provider_name}, tenant {tenant_id}") return [] results = [] for inst in instances: models = TenantModelService.get_by_provider_id_and_instance_id_and_model_type(provider_obj.id, inst.id, model_type) if models: results.extend(models) + logger.debug(f"Found {len(results)} {model_type} models for {provider_name}, tenant {tenant_id}") return resultsAs per coding guidelines,
**/*.py: Add logging for new flows.🤖 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/joint_services/tenant_model_service.py` around lines 309 - 325, The function get_models_by_tenant_and_provider_and_model_type lacks any logging; add logs inside that function (using the module logger) to record key events and counts: log when provider_obj is not found (include tenant_id and provider_name), log the number of instances returned from TenantModelInstanceService.get_all_by_provider_id(provider_obj.id), for each inst log the instance id and number of models returned by TenantModelService.get_by_provider_id_and_instance_id_and_model_type(provider_obj.id, inst.id, model_type), and finally log the total number of aggregated results before returning; place logs at appropriate levels (info/debug) to aid debugging of tenant-specific model lookups.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 `@api/db/joint_services/tenant_model_service.py`:
- Around line 76-110: The _ensure_ocr_provider_from_env function performs DB
inserts and lookups without any logs; add structured logging at key steps in
_ensure_ocr_provider_from_env: log when config is missing, when a
TenantModelProviderService lookup misses and you insert a provider (include
tenant_id and provider_name), when creating a TenantModelInstance via
TenantModelInstanceService.create_instance (include provider_id, model_name and
a masked/partial api_key), when inserting a TenantModelService model (include
provider_id, instance_id, model_name and model_type), and log any unexpected
failures or exceptions around these calls; use the module logger (or
logging.getLogger(__name__)) and avoid logging full secrets (mask api_key) to
meet guidelines.
- Around line 50-62: Add structured logging to the get_first_provider_model_name
flow: import and use the module logger and add logs in
TenantModelProviderService/TenantModelInstanceService/TenantModelService
interaction points — log when no provider found for tenant_id/provider_name, log
when skipping an instance because instance_obj.status !=
ActiveStatusEnum.ACTIVE.value (include instance id/name and
tenant_id/provider_name), log when skipping a model because model_obj.status !=
ActiveStatusEnum.ACTIVE.value or model_obj.model_type mismatch (include model
id/name/type), and log the resolved model string right before the return in
get_first_provider_model_name. Ensure logs include tenant_id, provider_name,
instance_obj.id/instance_name and model_obj.model_name to aid tenant-specific
debugging.
- Line 20: The file currently imports IntegrityError but never uses it; remove
the unused import by deleting IntegrityError from the import statement at the
top (the "from peewee import IntegrityError" reference) so the module no longer
contains a dead import and lints cleanly.
---
Outside diff comments:
In `@rag/app/naive.py`:
- Around line 222-229: The code in the OpenDataLoader selection block
incorrectly accesses TenantModel.llm_name and manually picks candidates[0],
causing crashes and inconsistency; replace this manual logic with a call to the
unified helper get_first_provider_model_name(tenant_id,
provider_name="OpenDataLoader", model_type=LLMType.OCR) and fall back to
ensure_opendataloader_from_env(tenant_id) only if that helper returns None, and
ensure you read the model name via the helper (or TenantModel.model_name) rather
than .llm_name; update the selection in the opendataloader logic in the naive
flow to match the MinerU/PaddleOCR pattern.
---
Nitpick comments:
In `@api/db/joint_services/tenant_model_service.py`:
- Around line 309-325: The function
get_models_by_tenant_and_provider_and_model_type lacks any logging; add logs
inside that function (using the module logger) to record key events and counts:
log when provider_obj is not found (include tenant_id and provider_name), log
the number of instances returned from
TenantModelInstanceService.get_all_by_provider_id(provider_obj.id), for each
inst log the instance id and number of models returned by
TenantModelService.get_by_provider_id_and_instance_id_and_model_type(provider_obj.id,
inst.id, model_type), and finally log the total number of aggregated results
before returning; place logs at appropriate levels (info/debug) to aid debugging
of tenant-specific model lookups.
🪄 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: 7465d05d-e9b5-4069-b76c-4c28c2793de0
📒 Files selected for processing (3)
api/db/joint_services/tenant_model_service.pyrag/app/naive.pyrag/flow/parser/parser.py
🛑 Comments failed to post (3)
api/db/joint_services/tenant_model_service.py (3)
20-20:
⚠️ Potential issue | 🟡 Minor🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Description: Check if IntegrityError is used in this file rg -n 'IntegrityError' api/db/joint_services/tenant_model_service.py -A 3 -B 3Repository: infiniflow/ragflow
Length of output: 437
🏁 Script executed:
#!/bin/bash set -euo pipefail FILE="api/db/joint_services/tenant_model_service.py" echo "== File line count ==" wc -l "$FILE" echo echo "== IntegrityError occurrences ==" rg -n --hidden --no-ignore-vcs 'IntegrityError' "$FILE" || true echo echo "Count:" rg -n 'IntegrityError' "$FILE" | wc -l || true echo echo "== Look for exception handling patterns ==" rg -n --hidden --no-ignore-vcs 'except\s+.*:' "$FILE" -S || true rg -n --hidden --no-ignore-vcs 'except\s+.*IntegrityError' "$FILE" -S || true echo echo "== Search for provider/instance creation call sites ==" rg -n --hidden --no-ignore-vcs 'provider|instance|create|upsert|insert|get_or_create|on_conflict' "$FILE" -S || trueRepository: infiniflow/ragflow
Length of output: 7184
🏁 Script executed:
#!/bin/bash set -euo pipefail FILE="api/db/joint_services/tenant_model_service.py" # Print top + likely relevant middle sections without dumping entire file echo "== Top 80 lines ==" sed -n '1,120p' "$FILE" | cat -n echo echo "== Lines 120-240 ==" sed -n '120,240p' "$FILE" | cat -nRepository: infiniflow/ragflow
Length of output: 11619
🏁 Script executed:
#!/bin/bash set -euo pipefail FILE="api/db/joint_services/tenant_model_service.py" echo "== File line count ==" wc -l "$FILE" echo echo "== IntegrityError occurrences ==" rg -n --hidden --no-ignore-vcs 'IntegrityError' "$FILE" || true echo echo "Count:" rg -n 'IntegrityError' "$FILE" | wc -l || true echo echo "== Look for exception handling patterns ==" rg -n --hidden --no-ignore-vcs 'except\s+.*IntegrityError' "$FILE" -S || true echo echo "All except clauses:" rg -n --hidden --no-ignore-vcs 'except\s+.*:' "$FILE" -S || true echo echo "== Search for provider/instance creation call sites ==" rg -n --hidden --no-ignore-vcs 'provider|instance|create|upsert|insert|get_or_create|on_conflict' "$FILE" -S || trueRepository: infiniflow/ragflow
Length of output: 7205
🏁 Script executed:
#!/bin/bash set -euo pipefail FILE="api/db/joint_services/tenant_model_service.py" echo "== Top 120 lines ==" sed -n '1,120p' "$FILE" | cat -n echo echo "== Lines 120-260 ==" sed -n '120,260p' "$FILE" | cat -nRepository: infiniflow/ragflow
Length of output: 12659
Remove unused
IntegrityErrorimport.
api/db/joint_services/tenant_model_service.pyimportsIntegrityErrorbut the file contains no other references to it (noexcept IntegrityErroror other usage), so it’s likely a dead import unless needed elsewhere.🤖 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/joint_services/tenant_model_service.py` at line 20, The file currently imports IntegrityError but never uses it; remove the unused import by deleting IntegrityError from the import statement at the top (the "from peewee import IntegrityError" reference) so the module no longer contains a dead import and lints cleanly.
50-62: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Add logging for new OCR model resolution flow.
This new helper lacks logging. Per coding guidelines, new flows should include logging to aid debugging tenant-specific model selection.
📝 Suggested logging additions
def get_first_provider_model_name(tenant_id: str, provider_name: str, model_type: str | enum.Enum) -> str | None: model_type_val = model_type if isinstance(model_type, str) else model_type.value provider_obj = TenantModelProviderService.get_by_tenant_id_and_provider_name(tenant_id, provider_name) if not provider_obj: + logger.info(f"Provider {provider_name} not found for tenant {tenant_id}") return None for instance_obj in TenantModelInstanceService.get_all_by_provider_id(provider_obj.id): if instance_obj.status != ActiveStatusEnum.ACTIVE.value: continue for model_obj in TenantModelService.get_models_by_instance_id(instance_obj.id): if model_obj.model_type == model_type_val and model_obj.status == ActiveStatusEnum.ACTIVE.value: + logger.debug(f"Selected {model_type_val} model {model_obj.model_name} for tenant {tenant_id}") return f"{model_obj.model_name}@{instance_obj.instance_name}@{provider_name}" + logger.warning(f"No active {model_type_val} model found for provider {provider_name}, tenant {tenant_id}") return NoneAs per coding guidelines,
**/*.py: Add logging for new flows.🤖 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/joint_services/tenant_model_service.py` around lines 50 - 62, Add structured logging to the get_first_provider_model_name flow: import and use the module logger and add logs in TenantModelProviderService/TenantModelInstanceService/TenantModelService interaction points — log when no provider found for tenant_id/provider_name, log when skipping an instance because instance_obj.status != ActiveStatusEnum.ACTIVE.value (include instance id/name and tenant_id/provider_name), log when skipping a model because model_obj.status != ActiveStatusEnum.ACTIVE.value or model_obj.model_type mismatch (include model id/name/type), and log the resolved model string right before the return in get_first_provider_model_name. Ensure logs include tenant_id, provider_name, instance_obj.id/instance_name and model_obj.model_name to aid tenant-specific debugging.Source: Coding guidelines
76-110: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Add logging for OCR provider provisioning.
_ensure_ocr_provider_from_envcreates database records but lacks logging. This makes tenant-specific OCR setup difficult to troubleshoot.📝 Suggested logging additions
def _ensure_ocr_provider_from_env(tenant_id: str, provider_name: str, model_name: str, config: dict | None) -> str | None: if not config: return None provider_obj = TenantModelProviderService.get_by_tenant_id_and_provider_name(tenant_id, provider_name) if not provider_obj: + logger.info(f"Creating {provider_name} provider for tenant {tenant_id}") TenantModelProviderService.insert(tenant_id=tenant_id, provider_name=provider_name) provider_obj = TenantModelProviderService.get_by_tenant_id_and_provider_name(tenant_id, provider_name) api_key = json.dumps(config) instance_obj = TenantModelInstanceService.get_by_provider_id_and_api_key(provider_obj.id, api_key) if not instance_obj: + logger.info(f"Creating {provider_name} instance '{model_name}' for tenant {tenant_id}") instance_obj = TenantModelInstanceService.create_instance( provider_id=provider_obj.id, instance_name=model_name, api_key=api_key, extra="{}", ) model_obj = TenantModelService.get_by_provider_id_and_instance_id_and_model_type_and_model_name( provider_obj.id, instance_obj.id, LLMType.OCR.value, model_name, ) if not model_obj: + logger.info(f"Creating OCR model '{model_name}' for tenant {tenant_id}") TenantModelService.insert( model_name=model_name, provider_id=provider_obj.id, instance_id=instance_obj.id, model_type=LLMType.OCR.value, extra=json.dumps({"max_tokens": 0}), ) return f"{model_name}@{instance_obj.instance_name}@{provider_name}"As per coding guidelines,
**/*.py: Add logging for new flows.🤖 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/joint_services/tenant_model_service.py` around lines 76 - 110, The _ensure_ocr_provider_from_env function performs DB inserts and lookups without any logs; add structured logging at key steps in _ensure_ocr_provider_from_env: log when config is missing, when a TenantModelProviderService lookup misses and you insert a provider (include tenant_id and provider_name), when creating a TenantModelInstance via TenantModelInstanceService.create_instance (include provider_id, model_name and a masked/partial api_key), when inserting a TenantModelService model (include provider_id, instance_id, model_name and model_type), and log any unexpected failures or exceptions around these calls; use the module logger (or logging.getLogger(__name__)) and avoid logging full secrets (mask api_key) to meet guidelines.Source: Coding guidelines
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/models_api_service.py`:
- Around line 305-307: The new OpenDataLoader provisioning call
ensure_opendataloader_from_env(tenant_id) lacks an informational log entry; add
a descriptive logger.info or logger.debug call before (or immediately after)
invoking ensure_opendataloader_from_env to mirror the existing provisioning logs
for ensure_mineru_from_env and ensure_paddleocr_from_env, including the
tenant_id and action name (e.g., "Provisioning OpenDataLoader for tenant:
{tenant_id}") so operators can trace this flow in production; ensure you use the
module/class logger used elsewhere in models_api_service.py for consistency.
🪄 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: a0c32cbe-e04c-4046-87ab-424bbf49153b
📒 Files selected for processing (1)
api/apps/services/models_api_service.py
| ensure_mineru_from_env(tenant_id) | ||
| ensure_paddleocr_from_env(tenant_id) | ||
| ensure_opendataloader_from_env(tenant_id) |
There was a problem hiding this comment.
Add logging for the new OpenDataLoader provisioning flow.
Line 307 introduces a new flow path (ensure_opendataloader_from_env) but does not emit a log, which makes provisioning/debugging harder in production triage.
Suggested patch
ensure_mineru_from_env(tenant_id)
ensure_paddleocr_from_env(tenant_id)
+ logging.debug("Ensuring OpenDataLoader OCR model from env for tenant_id=%s", tenant_id)
ensure_opendataloader_from_env(tenant_id)As per coding guidelines, **/*.py: Add logging for new flows.
📝 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.
| ensure_mineru_from_env(tenant_id) | |
| ensure_paddleocr_from_env(tenant_id) | |
| ensure_opendataloader_from_env(tenant_id) | |
| ensure_mineru_from_env(tenant_id) | |
| ensure_paddleocr_from_env(tenant_id) | |
| logging.debug("Ensuring OpenDataLoader OCR model from env for tenant_id=%s", tenant_id) | |
| ensure_opendataloader_from_env(tenant_id) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@api/apps/services/models_api_service.py` around lines 305 - 307, The new
OpenDataLoader provisioning call ensure_opendataloader_from_env(tenant_id) lacks
an informational log entry; add a descriptive logger.info or logger.debug call
before (or immediately after) invoking ensure_opendataloader_from_env to mirror
the existing provisioning logs for ensure_mineru_from_env and
ensure_paddleocr_from_env, including the tenant_id and action name (e.g.,
"Provisioning OpenDataLoader for tenant: {tenant_id}") so operators can trace
this flow in production; ensure you use the module/class logger used elsewhere
in models_api_service.py for consistency.
Source: Coding guidelines
What problem does this PR solve?
Remove tenant_llm call in rag.
Type of change