Skip to content

Feat: SoMark - #16482

Merged
wangq8 merged 27 commits into
infiniflow:mainfrom
Lynn-Inf:fix/somark-branch
Jul 1, 2026
Merged

wangq8 merged 27 commits into
infiniflow:mainfrom
Lynn-Inf:fix/somark-branch

Conversation

@Lynn-Inf

@Lynn-Inf Lynn-Inf commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Follow #15486

limuting233 and others added 19 commits June 8, 2026 17:55
新增SoMark的OCR模型配置项,完善模型配置列表
- Add SoMarkParser supporting both naive 2-tuple and rag/flow 3-tuple paths
- Add SoMarkOcrModel as auto-registered OCR factory
- Hook into naive.py PDF chunking and rag/flow Parser node (pipeline mode)
- Add SoMark configuration UI (provider modal, icon, env-based auto-provisioning)
- Aligned with MinerU integration pattern; PDF-only scope
…der ocr_config

- Remove _verify_provider_instance_model and _create_ocr_provider_instance
  from provider_api.py (controller-level OCR-specific functions)
- Route all create/verify through provider_api_service layer
- Nest OCR extra fields under ocr_config in add_model_to_instance
- Extract only ocr_config content in get_model_config_from_provider_instance
  to avoid ** expansion conflicts
…omark to new joint service

- Revert all SoMark changes in api/apps/llm_app.py (deprecated interface)
- Add ensure_somark_from_env to api/db/joint_services/tenant_model_service.py
  using the generic _ensure_ocr_provider_from_env helper (new tables)
- Update rag/flow/parser/parser.py and rag/app/naive.py to call the new
  joint service instead of deprecated TenantLLMService
- Build model_info from flat payload in create/verify route handlers for
  providers with empty static model lists (e.g. SoMark)
…ve flat-payload logic to service layer

- Remove _collect_somark_env_config and ensure_somark_from_env from
  TenantLLMService (deprecated table); callers already use the new
  joint-service version in tenant_model_service.py
- Remove SOMARK_DEFAULT_CONFIG/SOMARK_ENV_KEYS imports (only dead code used them)
- Add _normalize_model_info() helper in provider_api_service.py to
  synthesize model_info from flat request payload for providers with
  empty static model lists (generic, keyed by provider name prefix)
- Add flat_config param to create_provider_instance and verify_api_key
  so the service layer handles provider-specific payload normalization
- Remove duplicate model_info-from-flat-payload construction from
  both route handlers in provider_api.py; routes now just pass
  flat_config=data through to the service layer
…SoMark, revert tenant_llm_service

- Frontend sends standard model_info array instead of flat somark_* fields,
  removing the need for backend-specific _normalize_model_info helper
- Embed SoMark OCR config into instance api_key JSON so it reaches
  SoMarkOcrModel via the existing api_key_payload -> key path, avoiding
  changes in the deprecated LLMBundle (tenant_llm_service.py)
- Limit ocr_config wrapping in add_model_to_instance to SoMark only;
  other OCR models (MinerU, PaddleOCR) are unaffected
- Revert LLMBundle OCR path in tenant_llm_service.py to original;
  file is now identical to main
…correct merge

The GitHub web merge resolved conflicts by renaming provider_name to
provider_id_or_name in function signatures (from soulcode/main fork),
but function bodies still reference provider_name.  infiniflow/ragflow:main
(the PR target) uses provider_name throughout.  Revert the rename to
match upstream/main and fix the undefined name error.
…F821

- Merge upstream/main (infiniflow/ragflow) into feature branch
- Resolve svg-icon.tsx and llm.ts conflicts: keep both SoMark and NewAPI
- Fix provider_id_or_name -> provider_name in provider_api.py (2 F821 errors)
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 30, 2026
@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds SoMark as a new OCR provider: a standalone PDF parser adapter calling SoMark's async HTTP API, an SoMarkOcrModel wrapper, backend provider-instance handling for SoMark-specific config, pipeline integration in naive/parser flows, frontend settings modal, translations, constants, and unit tests. Numerous nearby formatting-only refactors are included.

Changes

SoMark OCR Provider Integration

Layer / File(s) Summary
Constants and factory registration
common/constants.py, conf/llm_factories.json, web/src/constants/llm.ts, web/src/components/svg-icon.tsx, web/src/locales/en.ts, web/src/locales/zh.ts, web/src/locales/zh-traditional.ts, web/src/pages/agents/agent-dropdown.tsx
Adds SoMark env keys/defaults, a new factory entry, LLMFactory.SoMark enum plus icon/API URL maps, SoMark translation strings, and unrelated import formatting.
SoMark parser adapter
deepdoc/parser/somark_parser.py
New SoMarkParser, SoMarkBlockType, and SoMarkAPIError implement reachability checks, async submit/poll against the SoMark API, bbox tagging/cropping, and section/table conversion for the parse pipeline.
Backend and pipeline wiring
api/apps/services/provider_api_service.py, api/db/joint_services/tenant_model_service.py, common/parser_config_utils.py, rag/app/naive.py, rag/flow/parser/parser.py, rag/llm/ocr_model.py
Adds SoMark-specific provider-instance config merging, OCR extra-field handling, ensure_somark_from_env, @somark layout-recognizer detection, by_somark chunking backend, SoMark parse branch in the pipeline, and SoMarkOcrModel; includes many formatting-only refactors in provider_api_service.py.
SoMark settings modal
web/src/pages/user-setting/setting-model/modal/somark-modal/index.tsx, .../hooks.tsx, .../index.tsx, .../modal/verify-button/index.tsx, .../payload-utils.ts, provider-modal hook/index formatting
Adds SoMarkModal, useSubmitSoMark hook, modal wiring in ModelProviders, VerifyButton label overrides, new MODEL_EXTRA_KEYS, plus formatting-only tweaks.
SoMark parser tests
test/unit_test/deepdoc/parser/test_somark_parser.py
New unit tests cover type mapping, internal type resolution, block text extraction, section conversion, header/footer handling, and line-tag formatting.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

A rabbit hops through code so deep,
🐇 SoMark's docs no longer sleep.
Async calls, and bboxes drawn,
Modals bloom before the dawn.
Hop, commit, and test with glee—
One more parser, wild and free! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description only references issue #15486 and lacks the required summary and context. Add a Summary section that briefly explains the PR goal, background, and the main SoMark changes.
Docstring Coverage ⚠️ Warning Docstring coverage is 50.63% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and matches the main change: adding SoMark support.
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.

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.

@Lynn-Inf Lynn-Inf mentioned this pull request Jun 30, 2026
1 task done
@Lynn-Inf Lynn-Inf added the ci Continue Integration label Jun 30, 2026
@Lynn-Inf
Lynn-Inf marked this pull request as draft June 30, 2026 06:12
@Lynn-Inf
Lynn-Inf marked this pull request as ready for review June 30, 2026 06:12

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

🧹 Nitpick comments (4)
api/apps/services/provider_api_service.py (1)

837-841: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Use the resolved provider name for the SoMark branch.

provider_id_or_name can be an ID or alias; comparing it directly to "SoMark" skips the ocr_config storage path for valid SoMark calls made by ID. Use provider_obj.provider_name after resolution.

♻️ Proposed fix
         if extra:
-            if provider_id_or_name == "SoMark" and LLMType.OCR.value in model_type:
+            if provider_obj.provider_name == "SoMark" and LLMType.OCR.value in model_type:
                 extra_fields["ocr_config"] = extra
             else:
                 extra_fields.update(extra)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/provider_api_service.py` around lines 837 - 841, The SoMark
OCR branch in the extra-handling logic is checking provider_id_or_name directly,
which can miss valid SoMark requests passed by ID or alias. Update the
conditional in the provider extra processing to use the resolved
provider_obj.provider_name when deciding whether to store extra under ocr_config
for LLMType.OCR.value, while keeping the existing extra_fields.update(extra)
fallback for other providers.
rag/flow/parser/parser.py (1)

520-541: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add logging around SoMark PDF parsing.

This new flow has no start/success logs, making parser selection and OCR output counts hard to diagnose. As per coding guidelines, **/*.py: Add logging for new flows.

🔍 Proposed logging
             ocr_model = LLMBundle(tenant_id, ocr_model_config)
             pdf_parser = ocr_model.mdl
 
+            logging.info("Starting SoMark PDF parse with model %s", parser_model_name)
             lines, _ = pdf_parser.parse_pdf(
                 filepath=name,
                 binary=blob,
                 callback=self.callback,
                 parse_method="pipeline",
             )
+            logging.info(
+                "Finished SoMark PDF parse with model %s: %d lines",
+                parser_model_name,
+                len(lines or []),
+            )
             bboxes = []
🤖 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 520 - 541, Add logging around the
SoMark PDF parsing flow in parser.py so parser selection and OCR results are
observable. In the branch that resolves parser_model_name, log when SoMark
parsing starts and which OCR/parser model is being used, then log after
pdf_parser.parse_pdf completes with the number of extracted lines or pages
processed. Keep the logs close to the existing ocr_model_config, LLMBundle, and
parse_pdf steps so the new flow can be traced easily.

Source: Coding guidelines

rag/app/naive.py (1)

327-346: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add success-path logging for the new SoMark flow.

The new parser flow only logs failures. Add start/finish logs without sensitive config values so production parsing can be traced. As per coding guidelines, **/*.py: Add logging for new flows.

🔍 Proposed logging
                 ocr_model = LLMBundle(tenant_id=tenant_id, model_config=ocr_model_config, lang=lang)
                 pdf_parser = ocr_model.mdl
+                logging.info("Starting SoMark PDF parse with model %s", somark_llm_name)
                 sections, tables = pdf_parser.parse_pdf(
                     filepath=filename,
                     binary=binary,
                     callback=callback,
                     parse_method=parse_method,
                     **kwargs,
                 )
+                logging.info(
+                    "Finished SoMark PDF parse with model %s: %d sections, %d tables",
+                    somark_llm_name,
+                    len(sections or []),
+                    len(tables or []),
+                )
                 return sections, tables, pdf_parser
🤖 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 327 - 346, The new SoMark OCR parsing path in
naive.py only logs on errors, so add non-sensitive success-path logging around
the somark_llm_name branch. Emit a start log before resolving the model and a
finish log after parse_pdf returns, using the existing context in the naive
parser flow without including model config details or other sensitive values.
Keep the logging localized to the success path near
get_model_config_from_provider_instance, LLMBundle, and pdf_parser.parse_pdf so
production tracing is possible.

Source: Coding guidelines

web/src/pages/user-setting/setting-model/modal/verify-button/index.tsx (1)

23-32: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use useTranslation here instead of the wrapper hook.

This component still uses useTranslate, while the new SoMark modal in the same flow already uses useTranslation. Keeping both paths makes the settings i18n behavior harder to reason about.
As per coding guidelines, "Prefer useTranslation from react-i18next over project-wrapped utilities like useTranslate for i18n in React components."

🤖 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 `@web/src/pages/user-setting/setting-model/modal/verify-button/index.tsx`
around lines 23 - 32, `VerifyButton` is still using the project wrapper hook for
i18n, which should be replaced with the standard React i18n hook to match the
new modal flow. Update the `VerifyButton` component to use `useTranslation` from
`react-i18next` instead of `useTranslate('setting')`, and keep the same
translation namespace usage when reading `t` and `i18n` so the settings modal
uses a consistent i18n path.

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/apps/services/provider_api_service.py`:
- Around line 349-370: The verification flow in provider_api_service.py is still
using the original api_key and unconditionally calling verify_api_key after the
SoMark payload merge, which bypasses the intended shaped config. Move the SoMark
JSON merge logic in the provider-specific branch before verification, then make
the verification step use the shaped api_key_str (or skip verification where the
earlier generic-provider guard already does so) via verify_api_key in the same
flow.

In `@deepdoc/parser/somark_parser.py`:
- Around line 459-463: Page-image rendering failures in somark_parser should
stop parsing instead of allowing later image section generation; update the
exception path in the page rendering logic to fail fast, or ensure
_transfer_to_sections() does not emit any "image" blocks when self.page_images
is None. Use the existing somark_parser flow around self.page_images,
self.total_page, and _transfer_to_sections() to either raise a parse error
immediately after logging or guard media emission so downstream parser.py and
the markdown writer never see missing image payloads.
- Around line 195-207: The current `check_installation` validation in
`SoMarkParser` is too permissive because it accepts any `http://` or `https://`
endpoint and only does a generic root health check, which can let an arbitrary
host pass and later receive sensitive upload data. Tighten the `base_url` checks
in `check_installation` to require HTTPS by default and replace the generic
`_is_http_endpoint_valid(self.base_url)` probe with a SoMark-specific endpoint
or allowlist-based verification. Keep the existing SaaS branch via
`_check_saas_usage()` and update the private-deployment path so the validated
host must match the expected SoMark service before any PDF submission or polling
occurs.

In `@rag/app/naive.py`:
- Around line 319-324: The SoMark lookup in the layout_recognize flow only falls
back to ensure_somark_from_env, so tenant-configured models can be missed.
Update the SoMark branch in naive.py to mirror the MinerU/PaddleOCR path by
checking the tenant provider model first (using the same tenant model service
flow as the other branches), and only then fall back to ensure_somark_from_env
if needed. Keep the logic localized around the SoMark resolution block so the
existing exception handling and downstream model selection still work.

In `@rag/flow/parser/parser.py`:
- Around line 702-706: The parser’s layout normalization in the block handling
for layout_type values "figure" and "image" is converting all images to figures
even when cropping did not produce an image payload, which later breaks markdown
rendering in the figure path. Update the logic in parser.py so blocks are only
retagged as "figure" when an image key is actually present, and otherwise leave
the layout_type as "image" (or skip the figure conversion) to keep the markdown
writer from indexing missing media.
- Around line 510-518: The resolve_somark_llm_name helper currently falls back
to ensure_somark_from_env too early and skips tenant-configured SoMark provider
models when parse_method is somark without an explicit model id. Update this
resolver to follow the same provider-first fallback pattern used by
MinerU/PaddleOCR: after parser_model_name and conf.get("somark_llm_name"), look
up the tenant’s SoMark model from Model Providers using the tenant_id before
calling ensure_somark_from_env, and only use the env provisioning path if no
provider model is found.

In `@web/src/locales/en.ts`:
- Around line 1856-1880: The new SoMark labels in the en locale are using title
case instead of sentence case. Update the string values in the somark section of
en.ts so they follow the existing en.ts convention (only the first word
capitalized, remaining words lowercase), and keep the corresponding keys like
sectionElementFormats, imageFormat, sectionFeatureConfig, and the enable* labels
consistent.

In `@web/src/pages/user-setting/setting-model/hooks.tsx`:
- Around line 239-243: The SoMark verification path in submitProviderInstance is
reading non-standard fields, which causes valid verify responses to be treated
as failures. Update the isVerify branch in hooks.tsx to use the standard
response shape from ret.code and ret.message, matching the rest of the
normalization logic in submitProviderInstance, so VerifyButton gets the correct
success state and backend logs are preserved.

In `@web/src/pages/user-setting/setting-model/index.tsx`:
- Around line 225-227: Existing SoMark instances are still being edited through
the generic ProviderModal path, which loses the saved somark_* options. Update
handleEditInstance and the SoMark-specific modal wiring so SoMark edits open
SoMarkModal instead of ProviderModal, or extend the generic edit/save flow to
preserve the full extra payload in addition to extra.is_tools. Make sure the
existing LLMFactory.SoMark branch and related edit/save handlers keep all SoMark
fields round-tripped.

In `@web/src/pages/user-setting/setting-model/modal/somark-modal/index.tsx`:
- Around line 129-159: Reset the SoMark form state whenever the modal is closed
so reopened sessions do not reuse the previous API key or toggle values. Update
the SoMarkModal flow around useForm and the Dialog/DialogContent visibility
handling so closing via hideModal or onOpenChange also clears the form back to
its defaultValues, preserving the current submit behavior in handleOk while
ensuring stale state is not retained between opens.
- Around line 129-147: The SoMark modal’s default form state is out of sync with
the backend for somark_enable_inline_image, causing new instances to save with
the wrong parser behavior. Update the useForm defaultValues in SoMark modal to
match the backend defaults used by common/constants.py and rag/llm/ocr_model.py,
keeping somark_enable_inline_image enabled by default and preserving the
existing behavior of the other SoMark flags.

---

Nitpick comments:
In `@api/apps/services/provider_api_service.py`:
- Around line 837-841: The SoMark OCR branch in the extra-handling logic is
checking provider_id_or_name directly, which can miss valid SoMark requests
passed by ID or alias. Update the conditional in the provider extra processing
to use the resolved provider_obj.provider_name when deciding whether to store
extra under ocr_config for LLMType.OCR.value, while keeping the existing
extra_fields.update(extra) fallback for other providers.

In `@rag/app/naive.py`:
- Around line 327-346: The new SoMark OCR parsing path in naive.py only logs on
errors, so add non-sensitive success-path logging around the somark_llm_name
branch. Emit a start log before resolving the model and a finish log after
parse_pdf returns, using the existing context in the naive parser flow without
including model config details or other sensitive values. Keep the logging
localized to the success path near get_model_config_from_provider_instance,
LLMBundle, and pdf_parser.parse_pdf so production tracing is possible.

In `@rag/flow/parser/parser.py`:
- Around line 520-541: Add logging around the SoMark PDF parsing flow in
parser.py so parser selection and OCR results are observable. In the branch that
resolves parser_model_name, log when SoMark parsing starts and which OCR/parser
model is being used, then log after pdf_parser.parse_pdf completes with the
number of extracted lines or pages processed. Keep the logs close to the
existing ocr_model_config, LLMBundle, and parse_pdf steps so the new flow can be
traced easily.

In `@web/src/pages/user-setting/setting-model/modal/verify-button/index.tsx`:
- Around line 23-32: `VerifyButton` is still using the project wrapper hook for
i18n, which should be replaced with the standard React i18n hook to match the
new modal flow. Update the `VerifyButton` component to use `useTranslation` from
`react-i18next` instead of `useTranslate('setting')`, and keep the same
translation namespace usage when reading `t` and `i18n` so the settings modal
uses a consistent i18n path.
🪄 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: cc3dc8c6-fcbb-4b62-8a7d-ea99171412a2

📥 Commits

Reviewing files that changed from the base of the PR and between 2018eec and 8493e56.

⛔ Files ignored due to path filters (1)
  • web/src/assets/svg/llm/somark.svg is excluded by !**/*.svg
📒 Files selected for processing (23)
  • api/apps/services/provider_api_service.py
  • api/db/joint_services/tenant_model_service.py
  • common/constants.py
  • common/parser_config_utils.py
  • conf/llm_factories.json
  • deepdoc/parser/somark_parser.py
  • rag/app/naive.py
  • rag/flow/parser/parser.py
  • rag/llm/ocr_model.py
  • test/unit_test/deepdoc/parser/test_somark_parser.py
  • web/src/components/svg-icon.tsx
  • web/src/constants/llm.ts
  • web/src/locales/en.ts
  • web/src/locales/zh-traditional.ts
  • web/src/locales/zh.ts
  • web/src/pages/agents/agent-dropdown.tsx
  • web/src/pages/user-setting/setting-model/hooks.tsx
  • web/src/pages/user-setting/setting-model/index.tsx
  • web/src/pages/user-setting/setting-model/modal/provider-modal/hooks/use-list-models-picker.ts
  • web/src/pages/user-setting/setting-model/modal/provider-modal/index.tsx
  • web/src/pages/user-setting/setting-model/modal/somark-modal/index.tsx
  • web/src/pages/user-setting/setting-model/modal/verify-button/index.tsx
  • web/src/pages/user-setting/setting-model/payload-utils.ts

Comment on lines +349 to +370
# For SoMark, embed OCR config from model_info into the api_key JSON so
# SoMarkOcrModel.__init__ can read it via the existing key → api_key_payload
# path. This avoids changing the deprecated LLMBundle in tenant_llm_service.py.
if provider_name == "SoMark" and model_info:
cfg = {}
if api_key_str:
try:
cfg = json.loads(api_key_str)
except Exception:
pass
if not isinstance(cfg, dict):
cfg = {}
for model in model_info:
if model.get("extra"):
cfg.update(model["extra"])
if base_url:
cfg["SOMARK_BASE_URL"] = base_url
api_key_str = json.dumps(cfg)

success, msg = await verify_api_key(provider_name, api_key, base_url, region, model_info)
if not success:
return False, msg

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Move SoMark payload shaping before verification and remove the unconditional verify.

Line 368 re-verifies every provider even when lines 341-344 intentionally skip empty generic providers, and it still passes the original api_key instead of the merged SoMark config from lines 352-366. Shape the SoMark payload before the existing conditional verify_api_key call and verify with that shaped value.

🐛 Proposed fix
+    api_key_for_verify = api_key
+
+    # For SoMark, embed OCR config from model_info into the api_key JSON so
+    # SoMarkOcrModel.__init__ can read it via the existing key → api_key_payload
+    # path. This avoids changing the deprecated LLMBundle in tenant_llm_service.py.
+    if provider_name == "SoMark" and model_info:
+        cfg = {}
+        if api_key_str:
+            try:
+                cfg = json.loads(api_key_str)
+            except Exception:
+                pass
+        if not isinstance(cfg, dict):
+            cfg = {}
+        for model in model_info:
+            if model.get("extra"):
+                cfg.update(model["extra"])
+        if base_url:
+            cfg["SOMARK_BASE_URL"] = base_url
+        api_key_str = json.dumps(cfg)
+        api_key_for_verify = cfg
+
     # Only verify when there are models to probe. Generic providers such as
     # "OpenAI-API-Compatible" may start empty and receive custom models later.
     factory_entry = next((f for f in FACTORY_LLM_INFOS if f["name"] == provider_name), None)
     if (factory_entry and factory_entry.get("llm")) or model_info:
-        success, msg = await verify_api_key(provider_name, api_key, base_url, region, model_info)
+        success, msg = await verify_api_key(provider_name, api_key_for_verify, base_url, region, model_info)
         if not success:
             return False, msg
-
-    # For SoMark, embed OCR config from model_info into the api_key JSON so
-    # SoMarkOcrModel.__init__ can read it via the existing key → api_key_payload
-    # path.  This avoids changing the deprecated LLMBundle in tenant_llm_service.py.
-    if provider_name == "SoMark" and model_info:
-        cfg = {}
-        if api_key_str:
-            try:
-                cfg = json.loads(api_key_str)
-            except Exception:
-                pass
-        if not isinstance(cfg, dict):
-            cfg = {}
-        for model in model_info:
-            if model.get("extra"):
-                cfg.update(model["extra"])
-        if base_url:
-            cfg["SOMARK_BASE_URL"] = base_url
-        api_key_str = json.dumps(cfg)
-
-    success, msg = await verify_api_key(provider_name, api_key, base_url, region, model_info)
-    if not success:
-        return False, msg
🧰 Tools
🪛 ast-grep (0.44.0)

[info] 365-365: use jsonify instead of json.dumps for JSON output
Context: json.dumps(cfg)
Note: [CWE-116] Improper Encoding or Escaping of Output.

(use-jsonify)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/provider_api_service.py` around lines 349 - 370, The
verification flow in provider_api_service.py is still using the original api_key
and unconditionally calling verify_api_key after the SoMark payload merge, which
bypasses the intended shaped config. Move the SoMark JSON merge logic in the
provider-specific branch before verification, then make the verification step
use the shaped api_key_str (or skip verification where the earlier
generic-provider guard already does so) via verify_api_key in the same flow.

Comment on lines +195 to +207
def check_installation(self) -> tuple[bool, str]:
if not self.base_url:
return False, "[SoMark] SOMARK_BASE_URL not configured."
if not self.base_url.startswith(("http://", "https://")):
return False, "[SoMark] SOMARK_BASE_URL must start with http:// or https://."

# SaaS deployment: hit /usage to verify API key validity and remaining quota.
if self.base_url == self.SAAS_BASE_URL:
return self._check_saas_usage()

# Private deployment: use a cheap HEAD health check.
if not self._is_http_endpoint_valid(self.base_url):
return False, f"[SoMark] server unreachable: {self.base_url}"

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Tighten base_url validation before uploading PDFs.

This accepts any http:///https:// URL whose root HEAD returns <500. Because base_url is resolved from provider config in rag/llm/ocr_model.py, a bad or malicious config can pass verification against an arbitrary internal host and then receive the API key plus raw PDF on submit/poll. Require HTTPS by default and probe a SoMark-specific endpoint/allowlist instead of a generic root HEAD.

🧰 Tools
🪛 ast-grep (0.44.0)

[warning] 197-197: Do not make http calls without encryption
Context: "http://"
Note: [CWE-319] Cleartext Transmission of Sensitive Information.

(requests-http)

🤖 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 `@deepdoc/parser/somark_parser.py` around lines 195 - 207, The current
`check_installation` validation in `SoMarkParser` is too permissive because it
accepts any `http://` or `https://` endpoint and only does a generic root health
check, which can let an arbitrary host pass and later receive sensitive upload
data. Tighten the `base_url` checks in `check_installation` to require HTTPS by
default and replace the generic `_is_http_endpoint_valid(self.base_url)` probe
with a SoMark-specific endpoint or allowlist-based verification. Keep the
existing SaaS branch via `_check_saas_usage()` and update the private-deployment
path so the validated host must match the expected SoMark service before any PDF
submission or polling occurs.

Source: Linters/SAST tools

Comment on lines +459 to +463
except Exception as exc:
self.page_images = None
self.total_page = 0
self.logger.exception(exc)

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Don't continue after page-image rendering fails.

If rendering fails here, self.page_images becomes None but _transfer_to_sections() still emits "image" blocks. Downstream rag/flow/parser/parser.py later normalizes those to figure and the markdown writer reads b["image"] unconditionally, so this turns into a late crash instead of a clean parse failure. Fail fast here or suppress media sections when page images are unavailable.

🤖 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 `@deepdoc/parser/somark_parser.py` around lines 459 - 463, Page-image rendering
failures in somark_parser should stop parsing instead of allowing later image
section generation; update the exception path in the page rendering logic to
fail fast, or ensure _transfer_to_sections() does not emit any "image" blocks
when self.page_images is None. Use the existing somark_parser flow around
self.page_images, self.total_page, and _transfer_to_sections() to either raise a
parse error immediately after logging or guard media emission so downstream
parser.py and the markdown writer never see missing image payloads.

Comment thread rag/app/naive.py
Comment on lines +319 to +324
if not somark_llm_name:
try:
from api.db.joint_services.tenant_model_service import ensure_somark_from_env

somark_llm_name = ensure_somark_from_env(tenant_id)
except Exception as e:

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Resolve tenant-configured SoMark models before env fallback.

When layout_recognize is just SoMark, this path only calls ensure_somark_from_env, so a SoMark model configured in Model Providers but not via env is reported as “not found.” Match the MinerU/PaddleOCR flow by checking the tenant provider model first.

🐛 Proposed fix
-                somark_llm_name = ensure_somark_from_env(tenant_id)
+                somark_llm_name = get_first_provider_model_name(tenant_id, "SoMark", LLMType.OCR) or ensure_somark_from_env(tenant_id)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if not somark_llm_name:
try:
from api.db.joint_services.tenant_model_service import ensure_somark_from_env
somark_llm_name = ensure_somark_from_env(tenant_id)
except Exception as e:
if not somark_llm_name:
try:
from api.db.joint_services.tenant_model_service import ensure_somark_from_env
somark_llm_name = (
get_first_provider_model_name(tenant_id, "SoMark", LLMType.OCR)
or ensure_somark_from_env(tenant_id)
)
except Exception as e:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@rag/app/naive.py` around lines 319 - 324, The SoMark lookup in the
layout_recognize flow only falls back to ensure_somark_from_env, so
tenant-configured models can be missed. Update the SoMark branch in naive.py to
mirror the MinerU/PaddleOCR path by checking the tenant provider model first
(using the same tenant model service flow as the other branches), and only then
fall back to ensure_somark_from_env if needed. Keep the logic localized around
the SoMark resolution block so the existing exception handling and downstream
model selection still work.

Comment thread rag/flow/parser/parser.py
Comment on lines +510 to +518
def resolve_somark_llm_name():
configured = parser_model_name or conf.get("somark_llm_name")
if configured:
return configured
tenant_id = self._canvas._tenant_id
if not tenant_id:
return None
from api.db.joint_services.tenant_model_service import ensure_somark_from_env
return ensure_somark_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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use tenant SoMark provider models before env fallback.

If the flow config is parse_method: somark without a specific model id, this resolver ignores SoMark models already configured in Model Providers and only checks env provisioning. Use the same provider-first fallback pattern as MinerU/PaddleOCR.

🐛 Proposed fix
                 tenant_id = self._canvas._tenant_id
                 if not tenant_id:
                     return None
                 from api.db.joint_services.tenant_model_service import ensure_somark_from_env
-                return ensure_somark_from_env(tenant_id)
+                return get_first_provider_model_name(tenant_id, "SoMark", LLMType.OCR) or ensure_somark_from_env(tenant_id)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def resolve_somark_llm_name():
configured = parser_model_name or conf.get("somark_llm_name")
if configured:
return configured
tenant_id = self._canvas._tenant_id
if not tenant_id:
return None
from api.db.joint_services.tenant_model_service import ensure_somark_from_env
return ensure_somark_from_env(tenant_id)
def resolve_somark_llm_name():
configured = parser_model_name or conf.get("somark_llm_name")
if configured:
return configured
tenant_id = self._canvas._tenant_id
if not tenant_id:
return None
from api.db.joint_services.tenant_model_service import ensure_somark_from_env
return get_first_provider_model_name(tenant_id, "SoMark", LLMType.OCR) or ensure_somark_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 `@rag/flow/parser/parser.py` around lines 510 - 518, The
resolve_somark_llm_name helper currently falls back to ensure_somark_from_env
too early and skips tenant-configured SoMark provider models when parse_method
is somark without an explicit model id. Update this resolver to follow the same
provider-first fallback pattern used by MinerU/PaddleOCR: after
parser_model_name and conf.get("somark_llm_name"), look up the tenant’s SoMark
model from Model Providers using the tenant_id before calling
ensure_somark_from_env, and only use the env provisioning path if no provider
model is found.

Comment thread web/src/locales/en.ts
Comment on lines +1856 to +1880
somark: {
modelNameMessage: 'Please input your model name',
baseUrl: 'Base URL',
baseUrlMessage: 'Please input the Base URL',
baseUrlPlaceholder:
'For SoMark API, fill in https://somark.tech/api/v1; for self-hosted deployment, fill in your local Base URL',
apiKey: 'API Key',
apiKeyPlaceholder:
'Required for SoMark API; leave blank for self-hosted deployment',
verifyPassed: 'Verified',
verifyFailed: 'Verification failed',
sectionElementFormats: 'Element Formats',
imageFormat: 'Image Format',
formulaFormat: 'Formula Format',
tableFormat: 'Table Format',
csFormat: 'Chemical Structural Formula Format',
sectionFeatureConfig: 'Feature Config',
enableInlineImage: 'Enable Inline Image',
enableTableImage: 'Enable Table Image',
enableImageUnderstanding: 'Enable Image Understanding',
enableTitleLevelRecognition: 'Enable Title Level Recognition',
enableTextCrossPage: 'Enable Text Cross Page',
enableTableCrossPage: 'Enable Table Cross Page',
keepHeaderFooter: 'Keep Header Footer',
},

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Keep the new en.ts strings in sentence case.

Several new labels are still title case (Element Formats, Image Format, Feature Config, etc.), which makes the SoMark section inconsistent with the rest of en.ts. As per coding guidelines, web/src/locales/{en,zh}.ts: “Use sentence case for en.ts: first word capitalized, rest lowercase.”

🤖 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 `@web/src/locales/en.ts` around lines 1856 - 1880, The new SoMark labels in the
en locale are using title case instead of sentence case. Update the string
values in the somark section of en.ts so they follow the existing en.ts
convention (only the first word capitalized, remaining words lowercase), and
keep the corresponding keys like sectionElementFormats, imageFormat,
sectionFeatureConfig, and the enable* labels consistent.

Source: Coding guidelines

Comment on lines +239 to +243
if (isVerify) {
return {
isValid: !!ret.data?.success,
logs: ret.data?.message,
} as VerifyResult;

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use the standard response fields for SoMark verification.

submitProviderInstance(..., true) is normalized everywhere else via ret.code / ret.message. Reading ret.data?.success here will turn a normal successful verify response into a failed VerifyButton state and drop the backend logs.

Suggested fix
         if (isVerify) {
           return {
-            isValid: !!ret.data?.success,
-            logs: ret.data?.message,
+            isValid: ret.code === 0,
+            logs: ret.message ?? '',
           } as VerifyResult;
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (isVerify) {
return {
isValid: !!ret.data?.success,
logs: ret.data?.message,
} as VerifyResult;
if (isVerify) {
return {
isValid: ret.code === 0,
logs: ret.message ?? '',
} as VerifyResult;
🤖 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 `@web/src/pages/user-setting/setting-model/hooks.tsx` around lines 239 - 243,
The SoMark verification path in submitProviderInstance is reading non-standard
fields, which causes valid verify responses to be treated as failures. Update
the isVerify branch in hooks.tsx to use the standard response shape from
ret.code and ret.message, matching the rest of the normalization logic in
submitProviderInstance, so VerifyButton gets the correct success state and
backend logs are preserved.

Comment on lines +225 to +227
[LLMFactory.SoMark]: showSoMarkModal,
}),
[showBedrockAddingModal],
[showBedrockAddingModal, showSoMarkModal],

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Existing SoMark instances still fall back to the generic edit modal.

This only wires SoMark into the add flow. handleEditInstance() still opens ProviderModal, and that save path only round-trips extra.is_tools, so editing an existing SoMark instance will drop the saved somark_* options. Either route SoMark edits back through SoMarkModal or teach the generic edit path to preserve the full extra payload.

🤖 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 `@web/src/pages/user-setting/setting-model/index.tsx` around lines 225 - 227,
Existing SoMark instances are still being edited through the generic
ProviderModal path, which loses the saved somark_* options. Update
handleEditInstance and the SoMark-specific modal wiring so SoMark edits open
SoMarkModal instead of ProviderModal, or extend the generic edit/save flow to
preserve the full extra payload in addition to extra.is_tools. Make sure the
existing LLMFactory.SoMark branch and related edit/save handlers keep all SoMark
fields round-tripped.

Comment on lines +129 to +147
const form = useForm<SoMarkFormValues>({
resolver: zodResolver(FormSchema),
defaultValues: {
instance_name: '',
llm_name: '',
somark_base_url: '',
somark_api_key: '',
somark_image_format: 'url',
somark_formula_format: 'latex',
somark_table_format: 'html',
somark_cs_format: 'image',
somark_enable_text_cross_page: false,
somark_enable_table_cross_page: false,
somark_enable_title_level_recognition: false,
somark_enable_inline_image: false,
somark_enable_table_image: true,
somark_enable_image_understanding: true,
somark_keep_header_footer: false,
},

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

somark_enable_inline_image is flipped from the backend default.

common/constants.py and rag/llm/ocr_model.py both default this flag to true, but the modal initializes it to false at Line 143. Saving a new SoMark instance through this UI therefore silently changes the parser behavior and disables inline-image output unless the user notices the toggle.

Proposed fix
-      somark_enable_inline_image: false,
+      somark_enable_inline_image: true,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const form = useForm<SoMarkFormValues>({
resolver: zodResolver(FormSchema),
defaultValues: {
instance_name: '',
llm_name: '',
somark_base_url: '',
somark_api_key: '',
somark_image_format: 'url',
somark_formula_format: 'latex',
somark_table_format: 'html',
somark_cs_format: 'image',
somark_enable_text_cross_page: false,
somark_enable_table_cross_page: false,
somark_enable_title_level_recognition: false,
somark_enable_inline_image: false,
somark_enable_table_image: true,
somark_enable_image_understanding: true,
somark_keep_header_footer: false,
},
const form = useForm<SoMarkFormValues>({
resolver: zodResolver(FormSchema),
defaultValues: {
instance_name: '',
llm_name: '',
somark_base_url: '',
somark_api_key: '',
somark_image_format: 'url',
somark_formula_format: 'latex',
somark_table_format: 'html',
somark_cs_format: 'image',
somark_enable_text_cross_page: false,
somark_enable_table_cross_page: false,
somark_enable_title_level_recognition: false,
somark_enable_inline_image: true,
somark_enable_table_image: true,
somark_enable_image_understanding: true,
somark_keep_header_footer: false,
},
🤖 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 `@web/src/pages/user-setting/setting-model/modal/somark-modal/index.tsx` around
lines 129 - 147, The SoMark modal’s default form state is out of sync with the
backend for somark_enable_inline_image, causing new instances to save with the
wrong parser behavior. Update the useForm defaultValues in SoMark modal to match
the backend defaults used by common/constants.py and rag/llm/ocr_model.py,
keeping somark_enable_inline_image enabled by default and preserving the
existing behavior of the other SoMark flags.

Comment on lines +129 to +159
const form = useForm<SoMarkFormValues>({
resolver: zodResolver(FormSchema),
defaultValues: {
instance_name: '',
llm_name: '',
somark_base_url: '',
somark_api_key: '',
somark_image_format: 'url',
somark_formula_format: 'latex',
somark_table_format: 'html',
somark_cs_format: 'image',
somark_enable_text_cross_page: false,
somark_enable_table_cross_page: false,
somark_enable_title_level_recognition: false,
somark_enable_inline_image: false,
somark_enable_table_image: true,
somark_enable_image_understanding: true,
somark_keep_header_footer: false,
},
});

const handleOk = async (values: SoMarkFormValues) => {
const ret = await onOk?.(values as any);
if (ret) {
hideModal?.();
}
};

return (
<Dialog open={visible} onOpenChange={hideModal}>
<DialogContent className="max-h-[80vh] overflow-y-auto">

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.

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Reset the form when the modal closes.

ModelProviders keeps SoMarkModal mounted and only toggles visible, so the last API key and toggle state will still be there on the next open. That makes stale submissions easy and keeps secret material in client state longer than necessary.

🤖 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 `@web/src/pages/user-setting/setting-model/modal/somark-modal/index.tsx` around
lines 129 - 159, Reset the SoMark form state whenever the modal is closed so
reopened sessions do not reuse the previous API key or toggle values. Update the
SoMarkModal flow around useForm and the Dialog/DialogContent visibility handling
so closing via hideModal or onOpenChange also clears the form back to its
defaultValues, preserving the current submit behavior in handleOk while ensuring
stale state is not retained between opens.

@codecov

codecov Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (828c578) to head (f6d99c5).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16482   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

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

@wangq8
wangq8 marked this pull request as draft June 30, 2026 07:36
@wangq8
wangq8 marked this pull request as ready for review June 30, 2026 07:36
Lynn-Inf and others added 4 commits June 30, 2026 15:56
The web-prettier and web-eslint lefthook hooks fail on the CI runner
because web/node_modules is not populated before lefthook runs. Without
it, `npx --prefix web ...` fetches the latest packages from the
registry, which breaks for two reasons:

  * prettier 3.9.4 is fetched but its declared plugins
    (prettier-plugin-organize-imports, prettier-plugin-packagejson)
    are not auto-resolved by npx — they have to be installed
    locally.
  * The latest eslint is 10.x, which requires the flat-config
    eslint.config.js format. The project still uses .eslintrc.cjs
    and pins eslint^$8.56.0.

Fix: ensure web/node_modules exists inside each hook by running
`npm ci --prefix web` when missing, then `cd web` before invoking
the tool so its plugin resolution finds web/node_modules. Also strip
the repo-root `web/` prefix from staged file paths before passing
them to prettier/eslint.

Also re-runs `ruff format` over the PR's changed Python files, which
the preflight job previously accepted because ruff was passing — the
PR files just weren't normalized to the project's ruff format.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
api/apps/services/provider_api_service.py (2)

800-803: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Use the resolved provider name for SoMark OCR extras.

provider_id_or_name may be an ID, so Line 800 can skip the SoMark branch and flatten OCR config incorrectly. Use provider_obj.provider_name and the current loop type.

Proposed fix
-            if provider_id_or_name == "SoMark" and LLMType.OCR.value in model_type:
+            if provider_obj.provider_name == "SoMark" and _type == LLMType.OCR.value:
                 extra_fields["ocr_config"] = extra
             else:
                 extra_fields.update(extra)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/provider_api_service.py` around lines 800 - 803, The SoMark
OCR extras check is using provider_id_or_name, which can be an ID and cause the
OCR-specific branch to be skipped. Update the conditional in
provider_api_service’s provider extras handling to use
provider_obj.provider_name together with the current model_type/loop type so
SoMark OCR extras stay nested under ocr_config instead of being flattened into
extra_fields.

319-333: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Preserve plain SoMark API keys during config merge.

If api_key is a plain hosted SoMark key, Line 323 fails JSON parsing and Lines 326-333 persist only extras/base URL, dropping the key that later parsing needs.

Proposed fix
     if provider_name == "SoMark" and model_info:
         cfg = {}
+        raw_key_as_secret = api_key if isinstance(api_key, str) and api_key and not api_key.lstrip().startswith("{") else ""
         if api_key_str:
             try:
                 cfg = json.loads(api_key_str)
             except Exception:
                 pass
         if not isinstance(cfg, dict):
             cfg = {}
+        if raw_key_as_secret and "SOMARK_API_KEY" not in cfg and "somark_api_key" not in cfg:
+            cfg["SOMARK_API_KEY"] = raw_key_as_secret
         for model in model_info:
             if model.get("extra"):
                 cfg.update(model["extra"])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/provider_api_service.py` around lines 319 - 333, The SoMark
merge logic in provider_api_service.py is overwriting plain api_key values when
json.loads fails, so the original hosted key is lost. Update the provider_name
== "SoMark" handling to preserve non-JSON api_key_str values while still merging
model_info extras and base_url, likely by keeping the original string separate
from the JSON config and only serializing a merged dict when the key is already
structured. Make the change in the SoMark config merge block so later parsing
can still recover the plain API key.
🧹 Nitpick comments (1)
api/apps/services/provider_api_service.py (1)

258-258: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use explicit None unions on these defaults. RUF013 also applies to api_key/base_url in list_provider_models and the base_url/region/model_info/extra params in create_provider_instance, verify_api_key, and add_model_to_instance; update the annotations to T | None in api/apps/services/provider_api_service.py:182, 258, 390, 769.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/provider_api_service.py` at line 258, Update the affected
function signatures in provider_api_service.py to use explicit None unions for
parameters with None defaults, since the current annotations are missing None
and trigger RUF013. Focus on list_provider_models, create_provider_instance,
verify_api_key, and add_model_to_instance, and change the relevant params such
as api_key, base_url, region, model_info, and extra to use T | None while
keeping the existing defaults and behavior unchanged.

Sources: Coding guidelines, Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@api/apps/services/provider_api_service.py`:
- Line 681: The provider API response currently returns a set for model_type in
the custom-model branch inside provider_api_service's model handling, which can
break JSON serialization. Update the logic around the
model_info_dict/model_unsupported_type_map expression so model_type is always
converted to a JSON-serializable list (matching the factory-model path) before
returning the response. Use the existing model_type assembly in the
provider_api_service flow to keep the shape consistent across branches.

In `@lefthook.yml`:
- Around line 40-65: The web hook bootstrap is duplicated in both web-prettier
and web-eslint, so they can race when web/node_modules is missing. Update
lefthook.yml so the npm ci --prefix web install happens only once in a shared
bootstrap step or a single combined web job, and have both prettier/eslint reuse
that prepared workspace without re-running the install check.
- Around line 28-34: Update the Ruff hook globs in lefthook config so the ruff
and ruff-format entries match both root-level and nested Python files, not just
top-level ones. Keep the existing hook names and commands, but change the glob
pattern used by these hooks so Lefthook will still include files like
check_comment_ascii.py, run_tests.py, and test.py while also covering all nested
.py files.

---

Outside diff comments:
In `@api/apps/services/provider_api_service.py`:
- Around line 800-803: The SoMark OCR extras check is using provider_id_or_name,
which can be an ID and cause the OCR-specific branch to be skipped. Update the
conditional in provider_api_service’s provider extras handling to use
provider_obj.provider_name together with the current model_type/loop type so
SoMark OCR extras stay nested under ocr_config instead of being flattened into
extra_fields.
- Around line 319-333: The SoMark merge logic in provider_api_service.py is
overwriting plain api_key values when json.loads fails, so the original hosted
key is lost. Update the provider_name == "SoMark" handling to preserve non-JSON
api_key_str values while still merging model_info extras and base_url, likely by
keeping the original string separate from the JSON config and only serializing a
merged dict when the key is already structured. Make the change in the SoMark
config merge block so later parsing can still recover the plain API key.

---

Nitpick comments:
In `@api/apps/services/provider_api_service.py`:
- Line 258: Update the affected function signatures in provider_api_service.py
to use explicit None unions for parameters with None defaults, since the current
annotations are missing None and trigger RUF013. Focus on list_provider_models,
create_provider_instance, verify_api_key, and add_model_to_instance, and change
the relevant params such as api_key, base_url, region, model_info, and extra to
use T | None while keeping the existing defaults and behavior unchanged.
🪄 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: 47ecff14-2673-49ec-8fe1-5fb36a9e9b33

📥 Commits

Reviewing files that changed from the base of the PR and between 8493e56 and ef12746.

📒 Files selected for processing (8)
  • api/apps/services/provider_api_service.py
  • api/db/joint_services/tenant_model_service.py
  • deepdoc/parser/somark_parser.py
  • lefthook.yml
  • rag/app/naive.py
  • rag/flow/parser/parser.py
  • rag/llm/ocr_model.py
  • test/unit_test/deepdoc/parser/test_somark_parser.py
🚧 Files skipped from review as they are similar to previous changes (5)
  • rag/app/naive.py
  • rag/flow/parser/parser.py
  • test/unit_test/deepdoc/parser/test_somark_parser.py
  • rag/llm/ocr_model.py
  • api/db/joint_services/tenant_model_service.py

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

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 (2)
api/apps/services/provider_api_service.py (2)

800-803: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Use the resolved provider name for SoMark OCR extras.

provider_id_or_name may be an ID, so Line 800 can skip the SoMark branch and flatten OCR config incorrectly. Use provider_obj.provider_name and the current loop type.

Proposed fix
-            if provider_id_or_name == "SoMark" and LLMType.OCR.value in model_type:
+            if provider_obj.provider_name == "SoMark" and _type == LLMType.OCR.value:
                 extra_fields["ocr_config"] = extra
             else:
                 extra_fields.update(extra)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/provider_api_service.py` around lines 800 - 803, The SoMark
OCR extras check is using provider_id_or_name, which can be an ID and cause the
OCR-specific branch to be skipped. Update the conditional in
provider_api_service’s provider extras handling to use
provider_obj.provider_name together with the current model_type/loop type so
SoMark OCR extras stay nested under ocr_config instead of being flattened into
extra_fields.

319-333: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Preserve plain SoMark API keys during config merge.

If api_key is a plain hosted SoMark key, Line 323 fails JSON parsing and Lines 326-333 persist only extras/base URL, dropping the key that later parsing needs.

Proposed fix
     if provider_name == "SoMark" and model_info:
         cfg = {}
+        raw_key_as_secret = api_key if isinstance(api_key, str) and api_key and not api_key.lstrip().startswith("{") else ""
         if api_key_str:
             try:
                 cfg = json.loads(api_key_str)
             except Exception:
                 pass
         if not isinstance(cfg, dict):
             cfg = {}
+        if raw_key_as_secret and "SOMARK_API_KEY" not in cfg and "somark_api_key" not in cfg:
+            cfg["SOMARK_API_KEY"] = raw_key_as_secret
         for model in model_info:
             if model.get("extra"):
                 cfg.update(model["extra"])
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/provider_api_service.py` around lines 319 - 333, The SoMark
merge logic in provider_api_service.py is overwriting plain api_key values when
json.loads fails, so the original hosted key is lost. Update the provider_name
== "SoMark" handling to preserve non-JSON api_key_str values while still merging
model_info extras and base_url, likely by keeping the original string separate
from the JSON config and only serializing a merged dict when the key is already
structured. Make the change in the SoMark config merge block so later parsing
can still recover the plain API key.
🧹 Nitpick comments (1)
api/apps/services/provider_api_service.py (1)

258-258: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use explicit None unions on these defaults. RUF013 also applies to api_key/base_url in list_provider_models and the base_url/region/model_info/extra params in create_provider_instance, verify_api_key, and add_model_to_instance; update the annotations to T | None in api/apps/services/provider_api_service.py:182, 258, 390, 769.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/provider_api_service.py` at line 258, Update the affected
function signatures in provider_api_service.py to use explicit None unions for
parameters with None defaults, since the current annotations are missing None
and trigger RUF013. Focus on list_provider_models, create_provider_instance,
verify_api_key, and add_model_to_instance, and change the relevant params such
as api_key, base_url, region, model_info, and extra to use T | None while
keeping the existing defaults and behavior unchanged.

Sources: Coding guidelines, Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@api/apps/services/provider_api_service.py`:
- Line 681: The provider API response currently returns a set for model_type in
the custom-model branch inside provider_api_service's model handling, which can
break JSON serialization. Update the logic around the
model_info_dict/model_unsupported_type_map expression so model_type is always
converted to a JSON-serializable list (matching the factory-model path) before
returning the response. Use the existing model_type assembly in the
provider_api_service flow to keep the shape consistent across branches.

In `@lefthook.yml`:
- Around line 40-65: The web hook bootstrap is duplicated in both web-prettier
and web-eslint, so they can race when web/node_modules is missing. Update
lefthook.yml so the npm ci --prefix web install happens only once in a shared
bootstrap step or a single combined web job, and have both prettier/eslint reuse
that prepared workspace without re-running the install check.
- Around line 28-34: Update the Ruff hook globs in lefthook config so the ruff
and ruff-format entries match both root-level and nested Python files, not just
top-level ones. Keep the existing hook names and commands, but change the glob
pattern used by these hooks so Lefthook will still include files like
check_comment_ascii.py, run_tests.py, and test.py while also covering all nested
.py files.

---

Outside diff comments:
In `@api/apps/services/provider_api_service.py`:
- Around line 800-803: The SoMark OCR extras check is using provider_id_or_name,
which can be an ID and cause the OCR-specific branch to be skipped. Update the
conditional in provider_api_service’s provider extras handling to use
provider_obj.provider_name together with the current model_type/loop type so
SoMark OCR extras stay nested under ocr_config instead of being flattened into
extra_fields.
- Around line 319-333: The SoMark merge logic in provider_api_service.py is
overwriting plain api_key values when json.loads fails, so the original hosted
key is lost. Update the provider_name == "SoMark" handling to preserve non-JSON
api_key_str values while still merging model_info extras and base_url, likely by
keeping the original string separate from the JSON config and only serializing a
merged dict when the key is already structured. Make the change in the SoMark
config merge block so later parsing can still recover the plain API key.

---

Nitpick comments:
In `@api/apps/services/provider_api_service.py`:
- Line 258: Update the affected function signatures in provider_api_service.py
to use explicit None unions for parameters with None defaults, since the current
annotations are missing None and trigger RUF013. Focus on list_provider_models,
create_provider_instance, verify_api_key, and add_model_to_instance, and change
the relevant params such as api_key, base_url, region, model_info, and extra to
use T | None while keeping the existing defaults and behavior unchanged.
🪄 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: 47ecff14-2673-49ec-8fe1-5fb36a9e9b33

📥 Commits

Reviewing files that changed from the base of the PR and between 8493e56 and ef12746.

📒 Files selected for processing (8)
  • api/apps/services/provider_api_service.py
  • api/db/joint_services/tenant_model_service.py
  • deepdoc/parser/somark_parser.py
  • lefthook.yml
  • rag/app/naive.py
  • rag/flow/parser/parser.py
  • rag/llm/ocr_model.py
  • test/unit_test/deepdoc/parser/test_somark_parser.py
🚧 Files skipped from review as they are similar to previous changes (5)
  • rag/app/naive.py
  • rag/flow/parser/parser.py
  • test/unit_test/deepdoc/parser/test_somark_parser.py
  • rag/llm/ocr_model.py
  • api/db/joint_services/tenant_model_service.py
🛑 Comments failed to post (3)
api/apps/services/provider_api_service.py (1)

681-681: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Return a JSON-serializable model_type.

Line 681 returns a set for custom models, unlike the list returned for factory models; API serialization can fail on this response.

Proposed fix
-                    "model_type": set(model_info_dict["model_type"]) - set(model_unsupported_type_map.get(model_name, [])),
+                    "model_type": sorted(set(model_info_dict["model_type"]) - set(model_unsupported_type_map.get(model_name, []))),
📝 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.

                    "model_type": sorted(set(model_info_dict["model_type"]) - set(model_unsupported_type_map.get(model_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 `@api/apps/services/provider_api_service.py` at line 681, The provider API
response currently returns a set for model_type in the custom-model branch
inside provider_api_service's model handling, which can break JSON
serialization. Update the logic around the
model_info_dict/model_unsupported_type_map expression so model_type is always
converted to a JSON-serializable list (matching the factory-model path) before
returning the response. Use the existing model_type assembly in the
provider_api_service flow to keep the shape consistent across branches.
lefthook.yml (2)

28-34: 📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

In Lefthook glob patterns, does "*.py" match nested paths like "api/apps/services/provider_api_service.py", or is "**/*.py" required to cover all Python files?

💡 Result:

In Lefthook, the pattern ".py" does not match nested files like "api/apps/services/provider_api_service.py" by default [1][2]. Lefthook uses a specific glob matching library (gobwas/glob) by default, which has distinct behaviors compared to many other tools [1][3][2]. Specifically: 1. The "" pattern matches files only within the current directory level [1][2]. 2. The "" pattern in the default configuration ("gobwas") matches one or more directories deep, but does not match files at the current (root) level [1][3][2]. To match all Python files regardless of their depth, you have two primary options: - Use the "glob_matcher: doublestar" configuration: By setting glob_matcher to "doublestar" in your lefthook.yml, you enable standard shell-style glob behavior where "/.py" will match files at any depth, including the root [3]. - Use multiple patterns: If you choose to keep the default matcher, you must explicitly include patterns for both the top-level and nested files (e.g., [".py", "/.py"]) if you need to capture everything [1][2]. To opt-in to standard behavior, configure your lefthook.yml as follows: glob_matcher: doublestar pre-commit: jobs: - name: lint run: your_command {staged_files} glob: "/.py"

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the Lefthook config and nearby context.
git ls-files lefthook.yml
echo "----"
cat -n lefthook.yml | sed -n '1,120p'
echo "----"
rg -n "glob_matcher|ruff|pre-commit|glob:" lefthook.yml

Repository: infiniflow/ragflow

Length of output: 3605


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== glob_matcher references =="
rg -n "glob_matcher" -S .

echo "== root-level Python files =="
git ls-files '*.py' | sed -n '1,120p'

echo "== Python files under top-level directories =="
find api rag deepdoc -type f -name '*.py' 2>/dev/null | sed -n '1,120p'

Repository: infiniflow/ragflow

Length of output: 186


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== root-level Python files =="
git ls-files | awk -F/ 'NF==1 && $0 ~ /\.py$/'

echo "== nested Python files =="
git ls-files | awk -F/ 'NF>1 && $0 ~ /\.py$/'

echo "== any lefthook glob matcher setting =="
rg -n "glob_matcher" lefthook.yml .github . 2>/dev/null || true

Repository: infiniflow/ragflow

Length of output: 43036


Expand the Ruff hook glob to cover both root-level and nested Python files. *.py only hits repo-root files here, and **/*.py by itself would skip check_comment_ascii.py, run_tests.py, and test.py under Lefthook’s default matcher.

🤖 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 `@lefthook.yml` around lines 28 - 34, Update the Ruff hook globs in lefthook
config so the ruff and ruff-format entries match both root-level and nested
Python files, not just top-level ones. Keep the existing hook names and
commands, but change the glob pattern used by these hooks so Lefthook will still
include files like check_comment_ascii.py, run_tests.py, and test.py while also
covering all nested .py files.

Source: Coding guidelines


40-65: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Bootstrap web/node_modules only once.

Because pre-commit runs in parallel, web-prettier and web-eslint can both enter the npm ci --prefix web branch at the same time when web/node_modules is absent. That races on the same workspace and makes the hook flaky. Please move the install into a single shared step or combine these two web jobs behind one bootstrap.

🤖 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 `@lefthook.yml` around lines 40 - 65, The web hook bootstrap is duplicated in
both web-prettier and web-eslint, so they can race when web/node_modules is
missing. Update lefthook.yml so the npm ci --prefix web install happens only
once in a shared bootstrap step or a single combined web job, and have both
prettier/eslint reuse that prepared workspace without re-running the install
check.

@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

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

261-265: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

New OCR flows lack logging.

The new SoMark branch in get_model_config_from_provider_instance and ensure_somark_from_env introduce a new flow but add no logging (e.g. on provider creation, config resolution fallback to whole model_extra). As per coding guidelines, "Add logging for new flows" for **/*.py.

Also applies to: 356-362

🤖 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 261 - 265, Add
logging for the new SoMark OCR flow in get_model_config_from_provider_instance
and ensure_somark_from_env. Log when the SoMark provider branch is entered, when
provider creation/config resolution happens, and when the code falls back from
model_extra["ocr_config"] to the full model_extra payload. Use the existing
function names to place the logs near the SoMark-specific path so the new flow
is observable without changing behavior.

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`:
- Line 259: The max_tokens defaulting in tenant_model_service is treating an
explicit 0 as missing, so OCR models created via _ensure_ocr_provider_from_env
and ensure_somark_from_env get silently changed to 8192. Update the max_tokens
handling in the affected model creation paths to fall back only when the key is
absent or None, preserving an explicit 0 value from model_extra. Apply the same
fix at both referenced max_tokens assignments so all OCR provider creation paths
keep the intended token limit.

---

Nitpick comments:
In `@api/db/joint_services/tenant_model_service.py`:
- Around line 261-265: Add logging for the new SoMark OCR flow in
get_model_config_from_provider_instance and ensure_somark_from_env. Log when the
SoMark provider branch is entered, when provider creation/config resolution
happens, and when the code falls back from model_extra["ocr_config"] to the full
model_extra payload. Use the existing function names to place the logs near the
SoMark-specific path so the new flow is observable without changing 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: 3777ba8a-4f21-4713-955b-64154f729f82

📥 Commits

Reviewing files that changed from the base of the PR and between ef12746 and c32fd0e.

📒 Files selected for processing (2)
  • api/db/joint_services/tenant_model_service.py
  • conf/llm_factories.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • conf/llm_factories.json

@@ -247,6 +258,11 @@ def get_model_config_from_provider_instance(tenant_id, model_type: str | enum.En
"is_tools": model_extra.get("is_tools", is_tool),
"max_tokens": model_extra.get("max_tokens") or 8192,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

or 8192 fallback silently overrides explicit max_tokens: 0.

_ensure_ocr_provider_from_env (used by ensure_somark_from_env and other OCR providers) creates models with extra=json.dumps({"max_tokens": 0}) — an intentional 0 value. With model_extra.get("max_tokens") or 8192, that explicit 0 is now treated as falsy and silently replaced by 8192 for every OCR model created this way, changing token-limit behavior for OCR calls that previously relied on max_tokens=0.

🐛 Proposed fix
-            "max_tokens": model_extra.get("max_tokens") or 8192,
+            "max_tokens": model_extra.get("max_tokens", 8192) if model_extra.get("max_tokens") is None else model_extra.get("max_tokens"),

Or more simply, only fall back when the key is absent/None:

-            "max_tokens": model_extra.get("max_tokens") or 8192,
+            "max_tokens": model_extra["max_tokens"] if model_extra.get("max_tokens") is not None else 8192,

Also applies to: 292-292

🤖 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 259, The max_tokens
defaulting in tenant_model_service is treating an explicit 0 as missing, so OCR
models created via _ensure_ocr_provider_from_env and ensure_somark_from_env get
silently changed to 8192. Update the max_tokens handling in the affected model
creation paths to fall back only when the key is absent or None, preserving an
explicit 0 value from model_extra. Apply the same fix at both referenced
max_tokens assignments so all OCR provider creation paths keep the intended
token limit.

@wangq8
wangq8 merged commit 400476f into infiniflow:main Jul 1, 2026
1 of 3 checks passed
Harsh23Kashyap added a commit to Harsh23Kashyap/ragflow that referenced this pull request Aug 20, 2026
Pre-fix, all 5 OCR provider classes in `rag/llm/ocr_model.py`
(`MinerUOcrModel`, `PaddleOCROcrModel`, `OpenDataLoaderOcrModel`,
`SoMarkOcrModel`, `MistralOcrModel`) parsed their `key` with the
same `try: json.loads(key) except Exception: raw_config = {}`
silent-fallback pattern. When a user pasted a plain key (e.g. a
provider's API key like `"sk-abc123"`), the JSON parse failed, the
exception was silently swallowed, and the provider fell back to host
env vars -- the user's pasted key was dropped on the floor.

The fix unifies all 5 through a single `_resolve_ocr_credentials`
helper in `rag/llm/key_utils.py` that follows the same pattern as
the other 6 helpers in the JSON-decode family (Bedrock, BaiduYiyan,
VolcEngine, OpenRouter, GoogleCV, Azure):

  1. Accept a dict (returned verbatim) or a JSON-string-encoded dict.
  2. On non-JSON input, raise a clear `ModelException(retryable=False)`
     naming the expected schema and pointing at
     `conf/llm_factories.json`, instead of letting `json.loads` bubble
     up as `JSONDecodeError` from inside the provider init.
  3. On a JSON top-level type that is not a dict (list, string,
     number, bool, null), raise the same clear `ModelException`
     instead of calling `.get(...)` on the value and getting
     `AttributeError`.
  4. On a falsy key (`None` or empty string), return `{}` -- matches
     the existing `if key:` short-circuit in every class.

Returns a dict (possibly empty) on success.

`MinerUOcrModel`, `PaddleOCROcrModel`, `OpenDataLoaderOcrModel` do
NOT support a raw secret key -- a plain key now raises a clear
`ModelException` (the bug fix).

`SoMarkOcrModel` and `MistralOcrModel` DO support a raw secret key
as a documented fallback for the api_key (added in infiniflow#16482 and infiniflow#17057
respectively). The fix preserves that behavior by pre-checking
whether the key is a non-JSON plain string via a new local helper
`_is_raw_secret_key(key) -> bool` that uses `json.loads` validation
(instead of the old `not key.lstrip().startswith("{")` heuristic,
which misclassified JSON arrays and strings as raw keys). The raw
key is captured as `key_as_secret` and used as the api_key
fallback, matching the pre-fix behavior.

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

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants