Skip to content

Fix paddle ocr cannot add - #15858

Merged
wangq8 merged 11 commits into
infiniflow:mainfrom
wangq8:bugfix/fix-paddle-ocr-cannot-add
Jun 10, 2026
Merged

wangq8 merged 11 commits into
infiniflow:mainfrom
wangq8:bugfix/fix-paddle-ocr-cannot-add

Conversation

@wangq8

@wangq8 wangq8 commented Jun 9, 2026

Copy link
Copy Markdown
Collaborator

Fix paddle ocr cannot add

@coderabbitai

coderabbitai Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

Tenant model resolution and OCR wiring

Layer / File(s) Summary
Tenant model resolver implementation
api/db/joint_services/tenant_model_service.py
Adds helpers for decoding API-key configs, selecting the first active provider model by tenant/type, and env-driven OCR provider/model bootstrapping (ensure_mineru_from_env, ensure_paddleocr_from_env).
Service/API callsite wiring
api/apps/services/models_api_service.py
Imports and invokes env-driven OCR bootstrapping helpers before assembling tenant-added models in list_tenant_added_models.
Parser & naive app OCR lookup changes
rag/flow/parser/parser.py, rag/app/naive.py
Preserves full parser/model identifiers for provider-suffixed parse methods and resolves OCR provider model names via get_first_provider_model_name(..., Provider, LLMType.OCR) with env-based fallback helpers.
Parser config normalization
common/parser_config_utils.py
For provider-suffixed recognizer strings, parser_model_name is kept as the full raw value while normalized layout_recognizer maps to MinerU/PaddleOCR/OpenDataLoader as before.

PaddleOCR Web Form Model Type Specification & Parser Cleanup

Layer / File(s) Summary
PaddleOCR model_type override in form transforms
web/src/pages/user-setting/setting-model/modal/provider-modal/field-config/provider-config-map.ts
verifyTransform and submitTransform now call buildModelInfoFromValues({ ...values, model_type: ['ocr'] }) to ensure produced model info is explicitly tagged as OCR.
PaddleOCRParser.init local initialization
deepdoc/parser/paddleocr_parser.py
Removes super().__init__() from PaddleOCRParser.__init__, relying on local attribute initialization instead.

Agent template credential cleanup

Layer / File(s) Summary
TavilySearch API key removal from template
agent/templates/stock_market_research_assistant.json
Replaces embedded TavilySearch api_key values with empty strings in both the component DSL and the corresponding graph node configuration.

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

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#15830: Modifies PaddleOCR provider configuration transforms in the same file to change how modelInfo is built from submitted values.

Suggested labels

🐞 bug

🐰 I hop and clear the hidden keys away,
I keep the parser names intact today,
I tag OCR models with a sure little cheer,
Constructors trimmed and bootstraps appear.
A tiny rabbit dance through code, hooray!

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is missing critical sections and is largely incomplete, with no explanation of the problem, rationale, change type, or implementation details. Fill in the description template with problem statement, change type selection, and detailed explanation of how the PaddleOCR issues are resolved and why this approach was chosen.
Docstring Coverage ⚠️ Warning Docstring coverage is 13.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is vague and incomplete, using generic phrasing that doesn't clearly convey the actual changes made throughout the codebase. Provide a more specific title that describes the main change, such as 'Refactor OCR provider model name resolution and environment setup' or 'Fix PaddleOCR initialization and model configuration'.
✅ Passed checks (2 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@wangq8
wangq8 requested a review from Lynn-Inf June 9, 2026 11:43
@wangq8 wangq8 added the ci Continue Integration label Jun 9, 2026
@wangq8
wangq8 marked this pull request as ready for review June 9, 2026 11:44
@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Jun 9, 2026
@codecov

codecov Bot commented Jun 9, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (64b860f) to head (ba64383).
⚠️ Report is 10 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Lynn-Inf Lynn-Inf left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 8de63a9 and 054675e.

📒 Files selected for processing (2)
  • common/parser_config_utils.py
  • rag/flow/parser/parser.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • common/parser_config_utils.py

Comment thread rag/flow/parser/parser.py Resolved
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels Jun 10, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
api/db/joint_services/tenant_model_service.py (1)

36-78: ⚡ Quick win

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between 054675e and 3a2dfda.

📒 Files selected for processing (5)
  • api/db/joint_services/tenant_model_service.py
  • common/parser_config_utils.py
  • deepdoc/parser/paddleocr_parser.py
  • rag/app/naive.py
  • rag/flow/parser/parser.py
💤 Files with no reviewable changes (1)
  • deepdoc/parser/paddleocr_parser.py

Comment on lines +101 to +104
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Comment thread rag/flow/parser/parser.py
Comment on lines 336 to 343
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"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

♻️ Duplicate comments (1)
rag/flow/parser/parser.py (1)

338-349: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add normalization for @opendataloader suffix.

The MinerU and PaddleOCR branches preserve provider-suffixed model names (lines 344-349), but @opendataloader is not normalized here. A value like foo@opendataloader will miss the OCR branch (line 440) and might fall through to the vision parser path, resolving as IMAGE2TEXT instead of OCR.

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

Align OpenDataLoader resolution with MinerU/PaddleOCR pattern.

The OpenDataLoader model resolution still uses TenantLLMService.ensure_opendataloader_from_env and TenantLLMService.query (lines 224-228), while MinerU (line 146) and PaddleOCR (line 283) have been updated to use get_first_provider_model_name(...) or ensure_*_from_env(...) helpers.

♻️ Suggested refactor to align patterns

If an ensure_opendataloader_from_env helper exists in api.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_env is available in tenant_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

📥 Commits

Reviewing files that changed from the base of the PR and between 3a2dfda and ba64383.

📒 Files selected for processing (4)
  • api/apps/services/models_api_service.py
  • api/db/joint_services/tenant_model_service.py
  • rag/app/naive.py
  • rag/flow/parser/parser.py

Comment on lines +305 to +306
ensure_mineru_from_env(tenant_id)
ensure_paddleocr_from_env(tenant_id)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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

Comment on lines +49 to +62
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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 None

As 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

Comment on lines +75 to +110
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}"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants