Repository navigation
Fix paddle ocr cannot add - #15858
Conversation
📝 WalkthroughWalkthroughRemoves embedded TavilySearch API keys from a template, adds tenant/provider OCR model resolution and env-based bootstrapping, updates parser/app callsites to use full model identifiers, forces PaddleOCR form model_type=['ocr'], and removes a superclass init call in PaddleOCRParser. ChangesTenant model resolution and OCR wiring
PaddleOCR Web Form Model Type Specification & Parser Cleanup
Agent template credential cleanup
Sequence Diagram(s)sequenceDiagram
participant Parser as Parser._pdf
participant TenantModelSvc as tenant_model_service.get_first_provider_model_name
participant Env as ensure_mineru_from_env/ensure_paddleocr_from_env
Parser->>TenantModelSvc: request model name (tenant_id, Provider, LLMType.OCR)
TenantModelSvc->>Env: fallback: ensure provider/model from env (tenant_id)
Env-->>TenantModelSvc: constructed model_name@instance@provider or None
TenantModelSvc-->>Parser: resolved model name (or None)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (2 warnings, 1 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 |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15858 +/- ##
=======================================
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:
|
…ragflow into bugfix/fix-paddle-ocr-cannot-add
…ragflow into bugfix/fix-paddle-ocr-cannot-add
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 `@rag/flow/parser/parser.py`:
- Line 339: The code currently strips the provider suffix with
raw_parse_method.rsplit("@")[0], which removes everything after the first '@'
and breaks names with internal '@'; change the logic to only remove the trailing
suffix by splitting on the last '@' (e.g., use rsplit with a maxsplit of 1) when
computing parser_model_name (and the similar occurrence at the other instance),
so that names like "foo@bar@paddleocr" become "foo@bar" while still stripping
the provider suffix.
🪄 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: 73d77ff1-077f-406c-aa81-45b17e8ad312
📒 Files selected for processing (2)
common/parser_config_utils.pyrag/flow/parser/parser.py
🚧 Files skipped from review as they are similar to previous changes (1)
- common/parser_config_utils.py
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
api/db/joint_services/tenant_model_service.py (1)
36-78: ⚡ Quick winAdd breadcrumbs for the new fallback matrix.
Lines 36-78 add several silent resolution branches (TEI builtin, CHAT↔IMAGE2TEXT, name/provider retry). When OCR config resolution lands on a fallback path, there is no log explaining why, which will make tenant-specific misroutes hard to diagnose. A debug/info log for the selected branch would make this new flow observable. 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 36 - 78, The new fallback matrix in TenantLLMService (inside the branch handling missing model_config) silently picks several alternative resolution paths (is_tei_builtin_embedding, CHAT→IMAGE2TEXT fallback, IMAGE2TEXT←CHAT tag-based reuse, and the generic provider retry) — add debug/info logging at each decision point (use the same logger used elsewhere in this module) stating the tenant_id, model_name/pure_model_name, model_type_val and which branch was taken (e.g., "using TEI builtin embedding", "falling back to CHAT creds for IMAGE2TEXT", "reusing CHAT config because LLMService tags include IMAGE2TEXT", "no tenant config found, raising LookupError") so operators can trace why a fallback was chosen; place logs near the checks that compute is_tei_builtin_embedding, after retrieving model_config from TenantLLMService.get_api_key, and after LLMService.query where tags are inspected.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 101-104: In get_model_config_by_name, don't treat every 3-part
model_name as provider-instance; instead call
get_model_config_by_type_and_name(tenant_id, model_type, model_name) first and
return it if found, and only if that lookup returns no result (falsy/None) then
check for a 3-part split and call
get_model_config_from_provider_instance(tenant_id, model_type, model_name) as a
fallback; preserve the full-name lookup behavior for OCR models by avoiding the
unconditional len(model_name.split("@")) >= 3 branch.
- Around line 95-97: The fallback that sets config_dict["is_tools"] uses
LLMService.query(llm_name=config_dict["llm_name"]) which can return a model from
the wrong provider; update the lookup to scope by factory as well (e.g. pass
llm_factory=config_dict.get("llm_factory") into LLMService.query) so the
retrieved llm matches both llm_name and llm_factory before using
llm[0].is_tools; ensure this mirrors the CHAT→IMAGE2TEXT check logic and only
sets config_dict["is_tools"] when the factory-scoped query returns a valid
result.
In `@rag/flow/parser/parser.py`:
- Around line 336-343: The _pdf() branch in parser.py only handles "`@mineru`" and
"`@paddleocr`" so inputs like "foo@opendataloader" fall through to the vision
path; update the raw_parse_method handling in _pdf() to reuse
common/parser_config_utils.normalize_layout_recognizer() (or apply the same
normalization logic) so that parser_model_name and parse_method are set
correctly for "`@opendataloader`" (mapping to the OCR branch) instead of resolving
as IMAGE2TEXT; locate the code around the raw_parse_method check in the _pdf()
function and replace/extend the lowered.endswith checks with a call to
normalize_layout_recognizer() or equivalent normalization and then assign
parser_model_name and parse_method accordingly.
---
Nitpick comments:
In `@api/db/joint_services/tenant_model_service.py`:
- Around line 36-78: The new fallback matrix in TenantLLMService (inside the
branch handling missing model_config) silently picks several alternative
resolution paths (is_tei_builtin_embedding, CHAT→IMAGE2TEXT fallback,
IMAGE2TEXT←CHAT tag-based reuse, and the generic provider retry) — add
debug/info logging at each decision point (use the same logger used elsewhere in
this module) stating the tenant_id, model_name/pure_model_name, model_type_val
and which branch was taken (e.g., "using TEI builtin embedding", "falling back
to CHAT creds for IMAGE2TEXT", "reusing CHAT config because LLMService tags
include IMAGE2TEXT", "no tenant config found, raising LookupError") so operators
can trace why a fallback was chosen; place logs near the checks that compute
is_tei_builtin_embedding, after retrieving model_config from
TenantLLMService.get_api_key, and after LLMService.query where tags are
inspected.
🪄 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: 1ab1561b-0b4e-4cb1-9a0c-74c1c2c69b2d
📒 Files selected for processing (5)
api/db/joint_services/tenant_model_service.pycommon/parser_config_utils.pydeepdoc/parser/paddleocr_parser.pyrag/app/naive.pyrag/flow/parser/parser.py
💤 Files with no reviewable changes (1)
- deepdoc/parser/paddleocr_parser.py
| def get_model_config_by_name(tenant_id: str, model_type: str | enum.Enum, model_name: str): | ||
| if len(model_name.split("@")) >= 3: | ||
| return get_model_config_from_provider_instance(tenant_id, model_type, model_name) | ||
| return get_model_config_by_type_and_name(tenant_id, model_type, model_name) |
There was a problem hiding this comment.
Don't treat every 3-part name as model@instance@provider.
Line 102 undoes the full-name preservation this PR introduces for OCR models. A value like foo@bar@paddleocr can legitimately mean model name foo@bar plus provider suffix @paddleocr, but this branch forces it through get_model_config_from_provider_instance(), which re-parses it as model=foo, instance=bar, provider=paddleocr. Try the name-based resolver first and only fall back to provider-instance parsing if that lookup misses.
Suggested fix
def get_model_config_by_name(tenant_id: str, model_type: str | enum.Enum, model_name: str):
- if len(model_name.split("@")) >= 3:
- return get_model_config_from_provider_instance(tenant_id, model_type, model_name)
- return get_model_config_by_type_and_name(tenant_id, model_type, model_name)
+ try:
+ return get_model_config_by_type_and_name(tenant_id, model_type, model_name)
+ except LookupError:
+ if len(model_name.split("@")) >= 3:
+ return get_model_config_from_provider_instance(tenant_id, model_type, model_name)
+ raise🤖 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 101 - 104, In
get_model_config_by_name, don't treat every 3-part model_name as
provider-instance; instead call get_model_config_by_type_and_name(tenant_id,
model_type, model_name) first and return it if found, and only if that lookup
returns no result (falsy/None) then check for a 3-part split and call
get_model_config_from_provider_instance(tenant_id, model_type, model_name) as a
fallback; preserve the full-name lookup behavior for OCR models by avoiding the
unconditional len(model_name.split("@")) >= 3 branch.
| if isinstance(raw_parse_method, str): | ||
| lowered = raw_parse_method.lower() | ||
| if lowered.endswith("@mineru"): | ||
| parser_model_name = raw_parse_method.rsplit("@", 1)[0] | ||
| parser_model_name = raw_parse_method | ||
| parse_method = "MinerU" | ||
| elif lowered.endswith("@paddleocr"): | ||
| parser_model_name = raw_parse_method.rsplit("@", 1)[0] | ||
| parser_model_name = raw_parse_method | ||
| parse_method = "PaddleOCR" |
There was a problem hiding this comment.
Normalize @opendataloader in _pdf() as well.
Lines 338-343 only rewrite @mineru and @paddleocr. If parse_method is something like foo@opendataloader, _pdf() misses the OCR branch entirely and falls through to the vision-parser path, where it gets resolved as IMAGE2TEXT instead of OCR. Reusing common/parser_config_utils.normalize_layout_recognizer() here would keep this logic in sync.
Suggested fix
+from common.parser_config_utils import normalize_layout_recognizer
...
- raw_parse_method = conf.get("parse_method", "")
- parser_model_name = None
- parse_method = raw_parse_method
- parse_method = parse_method or ""
- if isinstance(raw_parse_method, str):
- lowered = raw_parse_method.lower()
- if lowered.endswith("`@mineru`"):
- parser_model_name = raw_parse_method
- parse_method = "MinerU"
- elif lowered.endswith("`@paddleocr`"):
- parser_model_name = raw_parse_method
- parse_method = "PaddleOCR"
+ raw_parse_method = conf.get("parse_method", "")
+ parse_method, parser_model_name = normalize_layout_recognizer(raw_parse_method)
+ parse_method = parse_method or ""🤖 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/flow/parser/parser.py` around lines 336 - 343, The _pdf() branch in
parser.py only handles "`@mineru`" and "`@paddleocr`" so inputs like
"foo@opendataloader" fall through to the vision path; update the
raw_parse_method handling in _pdf() to reuse
common/parser_config_utils.normalize_layout_recognizer() (or apply the same
normalization logic) so that parser_model_name and parse_method are set
correctly for "`@opendataloader`" (mapping to the OCR branch) instead of resolving
as IMAGE2TEXT; locate the code around the raw_parse_method check in the _pdf()
function and replace/extend the lowered.endswith checks with a call to
normalize_layout_recognizer() or equivalent normalization and then assign
parser_model_name and parse_method accordingly.
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (1)
rag/flow/parser/parser.py (1)
338-349:⚠️ Potential issue | 🟠 Major | ⚡ Quick winAdd normalization for
@opendataloadersuffix.The MinerU and PaddleOCR branches preserve provider-suffixed model names (lines 344-349), but
@opendataloaderis not normalized here. A value likefoo@opendataloaderwill miss the OCR branch (line 440) and might fall through to the vision parser path, resolving asIMAGE2TEXTinstead ofOCR.🔧 Suggested normalization for OpenDataLoader
if isinstance(raw_parse_method, str): lowered = raw_parse_method.lower() if lowered.endswith("`@mineru`"): parser_model_name = raw_parse_method parse_method = "MinerU" elif lowered.endswith("`@paddleocr`"): parser_model_name = raw_parse_method parse_method = "PaddleOCR" + elif lowered.endswith("`@opendataloader`"): + parser_model_name = raw_parse_method + parse_method = "OpenDataLoader"This ensures
@opendataloader-suffixed names route to the correct OCR branch and preserve the full model identifier for downstream resolution.🤖 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/flow/parser/parser.py` around lines 338 - 349, The code normalizes MinerU and PaddleOCR provider suffixes but misses the "`@opendataloader`" suffix, so add a branch in the raw_parse_method string handling to detect lowered.endswith("`@opendataloader`"), set parser_model_name = raw_parse_method and set parse_method = "OpenDataLoader" (or the project convention for the opendataloader OCR parser) so that models like "foo@opendataloader" are preserved in parser_model_name and routed to the OCR parsing branch instead of falling through to vision/image2text handling; update the same block that currently checks for "`@mineru`" and "`@paddleocr`" (variables raw_parse_method, parser_model_name, parse_method) to include this new branch.
🧹 Nitpick comments (1)
rag/app/naive.py (1)
219-232: ⚡ Quick winAlign OpenDataLoader resolution with MinerU/PaddleOCR pattern.
The OpenDataLoader model resolution still uses
TenantLLMService.ensure_opendataloader_from_envandTenantLLMService.query(lines 224-228), while MinerU (line 146) and PaddleOCR (line 283) have been updated to useget_first_provider_model_name(...) or ensure_*_from_env(...)helpers.♻️ Suggested refactor to align patterns
If an
ensure_opendataloader_from_envhelper exists inapi.db.joint_services.tenant_model_service, update the resolution logic:try: - from api.db.services.tenant_llm_service import TenantLLMService - - env_name = TenantLLMService.ensure_opendataloader_from_env(tenant_id) - candidates = TenantLLMService.query(tenant_id=tenant_id, llm_factory="OpenDataLoader", model_type=LLMType.OCR) - if candidates: - opendataloader_llm_name = candidates[0].llm_name - elif env_name: - opendataloader_llm_name = env_name + opendataloader_llm_name = get_first_provider_model_name(tenant_id, "OpenDataLoader", LLMType.OCR) or ensure_opendataloader_from_env(tenant_id) except Exception as e: logging.warning(f"fallback to env opendataloader: {e}")Note: This assumes
ensure_opendataloader_from_envis available intenant_model_service. If not, consider adding it to match the MinerU/PaddleOCR 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 `@rag/app/naive.py` around lines 219 - 232, The OpenDataLoader resolution block uses TenantLLMService.ensure_opendataloader_from_env and TenantLLMService.query directly, causing inconsistency with MinerU/PaddleOCR; update this logic to call the shared helper pattern get_first_provider_model_name(...) first and fall back to ensure_opendataloader_from_env(...) from the tenant_model_service (or add a matching ensure_opendataloader_from_env in api.db.joint_services.tenant_model_service if missing), replacing the current use of TenantLLMService.query and TenantLLMService.ensure_opendataloader_from_env so resolution follows the same get_first_provider_model_name(...) or ensure_*_from_env(...) pattern used by MinerU and PaddleOCR.
🤖 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-306: The calls to ensure_mineru_from_env and
ensure_paddleocr_from_env introduce side-effecting bootstrapping that currently
can abort the list operation without any logs; wrap each call in a try/except
that catches exceptions from ensure_mineru_from_env and
ensure_paddleocr_from_env, log the exception with context (e.g., "failed to
bootstrap mineru for tenant {tenant_id}" and "failed to bootstrap paddleocr for
tenant {tenant_id}") using the module logger at error or warning level, and
allow the list flow to continue (do not re-raise) so transient bootstrap errors
don’t fail the listing; ensure the logged messages reference tenant_id and the
exception details and apply this change where the two calls appear in the list
operation.
In `@api/db/joint_services/tenant_model_service.py`:
- Around line 75-110: The _ensure_ocr_provider_from_env flow currently mutates
DB without logs—add concise logging at key steps: log when config is missing and
returning, log before/after creating a provider
(TenantModelProviderService.insert) including tenant_id and provider_name, log
before/after creating an instance (TenantModelInstanceService.create_instance)
including instance id/name and a masked api_key, and log before/after creating
the model (TenantModelService.insert) including model_name, model_type,
provider_id and instance_id; also catch and log exceptions around each
insert/create call (with tenant_id, provider_name, model_name) using the module
logger (e.g., logging.getLogger(__name__) or existing logger) and re-raise or
handle as appropriate so failures are recorded.
- Around line 49-62: Add logging to get_first_provider_model_name to record key
decision points: log a warning/info when
TenantModelProviderService.get_by_tenant_id_and_provider_name(tenant_id,
provider_name) returns None, log when each instance from
TenantModelInstanceService.get_all_by_provider_id(provider_obj.id) is skipped
due to non-active status, and log when a matching model is found (include
model_name, instance_name, provider_name and model_type_val) before returning;
also log a debug/info when the function finishes without finding any active
model. Use the module logger (or processLogger if existing) and include
tenant_id/provider_name for context.
---
Duplicate comments:
In `@rag/flow/parser/parser.py`:
- Around line 338-349: The code normalizes MinerU and PaddleOCR provider
suffixes but misses the "`@opendataloader`" suffix, so add a branch in the
raw_parse_method string handling to detect lowered.endswith("`@opendataloader`"),
set parser_model_name = raw_parse_method and set parse_method = "OpenDataLoader"
(or the project convention for the opendataloader OCR parser) so that models
like "foo@opendataloader" are preserved in parser_model_name and routed to the
OCR parsing branch instead of falling through to vision/image2text handling;
update the same block that currently checks for "`@mineru`" and "`@paddleocr`"
(variables raw_parse_method, parser_model_name, parse_method) to include this
new branch.
---
Nitpick comments:
In `@rag/app/naive.py`:
- Around line 219-232: The OpenDataLoader resolution block uses
TenantLLMService.ensure_opendataloader_from_env and TenantLLMService.query
directly, causing inconsistency with MinerU/PaddleOCR; update this logic to call
the shared helper pattern get_first_provider_model_name(...) first and fall back
to ensure_opendataloader_from_env(...) from the tenant_model_service (or add a
matching ensure_opendataloader_from_env in
api.db.joint_services.tenant_model_service if missing), replacing the current
use of TenantLLMService.query and
TenantLLMService.ensure_opendataloader_from_env so resolution follows the same
get_first_provider_model_name(...) or ensure_*_from_env(...) pattern used by
MinerU and PaddleOCR.
🪄 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: 43789781-947d-4b45-a090-161fec78943f
📒 Files selected for processing (4)
api/apps/services/models_api_service.pyapi/db/joint_services/tenant_model_service.pyrag/app/naive.pyrag/flow/parser/parser.py
| ensure_mineru_from_env(tenant_id) | ||
| ensure_paddleocr_from_env(tenant_id) |
There was a problem hiding this comment.
Add error handling and logging for OCR bootstrapping side effects.
Calling ensure_mineru_from_env and ensure_paddleocr_from_env at the start of a list operation introduces unlogged side effects (provider/instance/model creation). If these calls fail, the list operation fails without indication of why. Per coding guidelines, new flows require logging.
🛡️ Suggested error handling and logging
+ try:
+ ensure_mineru_from_env(tenant_id)
+ except Exception as e:
+ logging.warning(f"Failed to bootstrap MinerU from env for tenant {tenant_id}: {e}")
+
+ try:
+ ensure_paddleocr_from_env(tenant_id)
+ except Exception as e:
+ logging.warning(f"Failed to bootstrap PaddleOCR from env for tenant {tenant_id}: {e}")
- ensure_mineru_from_env(tenant_id)
- ensure_paddleocr_from_env(tenant_id)
-As per coding guidelines, add logging for new flows and handle exceptions gracefully to prevent list operations from failing due to bootstrapping errors.
🤖 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 - 306, The calls to
ensure_mineru_from_env and ensure_paddleocr_from_env introduce side-effecting
bootstrapping that currently can abort the list operation without any logs; wrap
each call in a try/except that catches exceptions from ensure_mineru_from_env
and ensure_paddleocr_from_env, log the exception with context (e.g., "failed to
bootstrap mineru for tenant {tenant_id}" and "failed to bootstrap paddleocr for
tenant {tenant_id}") using the module logger at error or warning level, and
allow the list flow to continue (do not re-raise) so transient bootstrap errors
don’t fail the listing; ensure the logged messages reference tenant_id and the
exception details and apply this change where the two calls appear in the list
operation.
Source: Coding guidelines
| 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: | ||
| 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: | ||
| return f"{model_obj.model_name}@{instance_obj.instance_name}@{provider_name}" | ||
| return None | ||
|
|
There was a problem hiding this comment.
Add logging for model lookup flow.
This function silently returns None when the provider is not found or when no active models match. Per coding guidelines, new flows should include logging to aid debugging.
📊 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.debug(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"Found {model_type_val} model: {model_obj.model_name}@{instance_obj.instance_name}@{provider_name}")
return f"{model_obj.model_name}@{instance_obj.instance_name}@{provider_name}"
+ logger.debug(f"No active {model_type_val} models found for provider {provider_name}")
return NoneAs per coding guidelines, add logging for new flows to improve observability and debugging.
🤖 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 49 - 62, Add
logging to get_first_provider_model_name to record key decision points: log a
warning/info when
TenantModelProviderService.get_by_tenant_id_and_provider_name(tenant_id,
provider_name) returns None, log when each instance from
TenantModelInstanceService.get_all_by_provider_id(provider_obj.id) is skipped
due to non-active status, and log when a matching model is found (include
model_name, instance_name, provider_name and model_type_val) before returning;
also log a debug/info when the function finishes without finding any active
model. Use the module logger (or processLogger if existing) and include
tenant_id/provider_name for context.
Source: Coding guidelines
| 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: | ||
| 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: | ||
| 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: | ||
| 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}" | ||
|
|
There was a problem hiding this comment.
Add logging for OCR provider bootstrapping.
This function creates provider, instance, and model records from environment configuration without any logging. Per coding guidelines, new flows require logging—especially critical bootstrapping operations that modify database state.
📊 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:
+ logger.debug(f"No env config for {provider_name}")
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 {provider_name} provider (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}),
)
+ logger.debug(f"Ensured {provider_name} OCR model: {model_name}@{instance_obj.instance_name}@{provider_name}")
return f"{model_name}@{instance_obj.instance_name}@{provider_name}"As per coding guidelines, add logging for new flows—especially for database record creation during environment-driven bootstrapping.
🤖 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 75 - 110, The
_ensure_ocr_provider_from_env flow currently mutates DB without logs—add concise
logging at key steps: log when config is missing and returning, log before/after
creating a provider (TenantModelProviderService.insert) including tenant_id and
provider_name, log before/after creating an instance
(TenantModelInstanceService.create_instance) including instance id/name and a
masked api_key, and log before/after creating the model
(TenantModelService.insert) including model_name, model_type, provider_id and
instance_id; also catch and log exceptions around each insert/create call (with
tenant_id, provider_name, model_name) using the module logger (e.g.,
logging.getLogger(__name__) or existing logger) and re-raise or handle as
appropriate so failures are recorded.
Source: Coding guidelines
Fix paddle ocr cannot add