Repository navigation
feat: add Mistral OCR (/v1/ocr) as a document parser; fix "Can't find model" mis-tag (#5782, #7075) - #17057
Conversation
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…guard Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…alized bytes Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Remove unused `import os` and `_KNOWN_INTERNAL_TYPES` from mistral_parser.py; run `ruff format` (repo line-length=200) across the feature files. No behavior change; feature suite 41/41 green. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ighten annotations Final-review polish: crop() logged a stray [SoMark] prefix (copy-paste from the cloned method); MistralOcrModel now logs its resolved config (redacted) for parity with SoMarkOcrModel; parse_pdf return/filepath annotations tightened. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…actory mistral-ocr-latest is the /v1/ocr endpoint, not a vision (image2text) or chat model. The stock Mistral factory declared it as ["image2text","chat"], which is the root of infiniflow#5782/infiniflow#7075 ("Can't find model for .../image2text/mistral-ocr-latest"): selecting it as a layout recognizer resolved to CvModel["Mistral"], which does not exist. It is now correctly represented by the separate "Mistral OCR" factory (model_type ocr). Removing the redundant, non-functional entry completes the fix and de-duplicates it from the parser dropdown. Pixtral vision models are left as-is (a separate 'no Mistral CvModel' gap, out of scope here). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
RAGFlow's CvModel registry had no Mistral entry, so pixtral vision models advertised by the Mistral factory failed with 'Can't find model' when used as image2text. Mistral exposes an OpenAI-compatible endpoint, so MistralCV is a thin GptV4 subclass pointing at https://api.mistral.ai/v1 (default pixtral-12b-2409). This enables Mistral vision models for figure description and any image2text use. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…model Mistral OCR extracts figures (image blocks with bboxes). When the tenant has a vision model configured, by_mistral_ocr now passes it to the parser, which crops each figure from the locally rendered page and captions it via vision_llm_chunk (same helper MinerU/deepdoc use). The caption replaces the bare 'image N' label, so figures become searchable/embeddable content. Best-effort: any failure or a missing vision model silently degrades to the caption/seq label. Pairs with the new MistralCV so pixtral can serve as that vision model. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
_describe_image serialized the crop to PNG bytes and passed those to vision_llm_chunk, but that helper expects a PIL Image (it calls img.size and img.save). The bytes path silently returned '' so figures were never described. Pass the crop directly; add a regression test asserting a PIL Image reaches vision_llm_chunk. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
book/laws/manual/one/paper/presentation dispatch to naive's PARSERS but only forwarded mineru_llm_name (paper: only that), so selecting Mistral OCR as the layout recognizer on a doc using any of these chunking methods left mistral_ocr_llm_name=None -> by_mistral_ocr fell through to 'Mistral OCR not found' and crashed. Forward mistral_ocr_llm_name=parser_model_name like naive.py does. (SoMark has the same latent gap in paper.py; out of scope here.) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds Mistral OCR as a dedicated PDF parsing provider with environment configuration, OCR API integration, model registration, parser routing, page-range support, figure enrichment, and unit tests across configuration and ingestion paths. ChangesMistral OCR support
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant PDFChunker
participant ParserRouter
participant TenantModelService
participant MistralOcrModel
participant MistralOCRAPI
PDFChunker->>ParserRouter: select Mistral OCR and pass PDF
ParserRouter->>TenantModelService: resolve configured or environment-backed model
TenantModelService-->>ParserRouter: return OCR model configuration
ParserRouter->>MistralOcrModel: parse PDF with page bounds
MistralOcrModel->>MistralOCRAPI: submit inline PDF or uploaded file
MistralOCRAPI-->>MistralOcrModel: return OCR pages and blocks
MistralOcrModel-->>ParserRouter: return normalized sections
ParserRouter-->>PDFChunker: return standardized records
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
commented
Jul 17, 2026
|
Caution Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted. Error details |
left a comment
There was a problem hiding this comment.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
rag/app/book.py (1)
121-122: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winBypass further chunking for Mistral OCR's structured output.
Like MinerU, Docling, and PaddleOCR, Mistral OCR returns structured semantic sections that should not be blindly merged by the subsequent text chunker. While
"mistral ocr"was correctly added to thechunk_token_numbypass list innaive.py(Line 1076), it was omitted in the other chunking flows, meaning Mistral OCR blocks may be inappropriately concatenated here.
rag/app/book.py#L121-L122: add"mistral ocr"to thename in [...]list.rag/app/laws.py#L213-L214: add"mistral ocr"to thename in [...]list.rag/app/manual.py#L202-L203: add"mistral ocr"to thename in [...]list.rag/app/one.py#L117-L118: add"mistral ocr"to thename in [...]list.rag/app/presentation.py#L225-L226: add"mistral ocr"to thename in [...]list.🤖 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/book.py` around lines 121 - 122, Bypass subsequent chunking for Mistral OCR structured output by adding "mistral ocr" to each name list in rag/app/book.py lines 121-122, rag/app/laws.py lines 213-214, rag/app/manual.py lines 202-203, rag/app/one.py lines 117-118, and rag/app/presentation.py lines 225-226, alongside the existing parser names and preserving the chunk_token_num assignment.
🧹 Nitpick comments (2)
rag/flow/parser/parser.py (1)
338-360: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse the shared parser-name normalizer.
This duplicates
normalize_layout_recognizerand already differs from it, requiring every provider suffix to be maintained twice.Proposed refactor
- 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() - ... - elif lowered.endswith("`@mistral` ocr"): - parser_model_name = raw_parse_method - parse_method = "Mistral OCR" + parse_method, parser_model_name = normalize_layout_recognizer( + conf.get("parse_method", "") + ) + parse_method = parse_method or ""As per coding guidelines, “converge coexisting implementations to one path unless an external contract requires compatibility.”
🤖 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 - 360, Replace the local parser-selection and provider-suffix normalization logic in the configuration parsing flow with the shared normalize_layout_recognizer implementation. Reuse its returned parser method and model name so provider suffix handling has one source of truth, while preserving the existing downstream behavior for parse_method and parser_model_name.Source: Coding guidelines
rag/llm/cv_model.py (1)
331-337: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLog activation of the Mistral vision flow.
Emit a structured initialization log containing the model and resolved base URL, but never the API key.
As per coding guidelines, “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 `@rag/llm/cv_model.py` around lines 331 - 337, Add a structured initialization log in MistralCV.__init__ after resolving base_url and before or after the superclass call, including model_name and the resolved base URL. Ensure the log context identifies the Mistral vision flow and excludes key from both structured fields and message content.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 `@deepdoc/parser/mistral_parser.py`:
- Around line 58-75: Update the Mistral parser’s base URL handling and the
outbound request flow around the document upload and response-reading logic to
enforce the server’s existing outbound-request policy. Validate resolved
destinations, including every redirect target, before issuing requests, and
reject private, loopback, link-local, and metadata endpoints; apply the same
centralized validation to the request paths referenced near the later
upload/response handling block.
- Around line 462-473: Update the page-rendering flow around __images__ and
page_images so restricted from_page/to_page requests rasterize only that range
while preserving the absolute-to-local mapping required by _line_tag and crop
logic. Determine the available page count safely before building pages, avoid
fallback ranges based on MAXIMUM_PAGE_NUMBER, and return empty results cleanly
when rendering or page-count detection fails.
- Around line 435-440: Update the file cleanup in the finally block to validate
the response returned by requests.delete, treating 4xx/5xx statuses as cleanup
failures and logging them alongside transport exceptions. Keep cleanup errors
non-fatal so the original OCR error remains unmasked, and include the existing
file_id context in the warning.
In `@rag/llm/ocr_model.py`:
- Around line 337-358: Update the configuration normalization around _resolve so
flat dictionaries with a string api_key retain the full raw_config; only unwrap
raw_config["api_key"] when that value is a configuration dictionary. Preserve
lower-case api_key and mistral_ocr_base_url resolution, and add a regression
test covering this flat configuration.
In `@test/unit_test/common/test_parser_config_utils_mistral.py`:
- Around line 11-15: Update test_mistral_ocr_suffix_case_insensitive to use
model_name explicitly by asserting it retains the original model reference
returned by normalize_layout_recognizer. Do not leave the value unused;
alternatively, rename the binding to _model_name if preservation is not part of
the test’s intended behavior.
In `@test/unit_test/deepdoc/parser/test_mistral_parser.py`:
- Around line 263-271: Replace the try/except and `assert False` exception
checks in the affected tests, including `test_call_ocr_raises_on_http_error` and
the four additional sites, with `pytest.raises` context managers. Preserve each
test’s expected exception type and message/status assertion within the
corresponding context.
---
Outside diff comments:
In `@rag/app/book.py`:
- Around line 121-122: Bypass subsequent chunking for Mistral OCR structured
output by adding "mistral ocr" to each name list in rag/app/book.py lines
121-122, rag/app/laws.py lines 213-214, rag/app/manual.py lines 202-203,
rag/app/one.py lines 117-118, and rag/app/presentation.py lines 225-226,
alongside the existing parser names and preserving the chunk_token_num
assignment.
---
Nitpick comments:
In `@rag/flow/parser/parser.py`:
- Around line 338-360: Replace the local parser-selection and provider-suffix
normalization logic in the configuration parsing flow with the shared
normalize_layout_recognizer implementation. Reuse its returned parser method and
model name so provider suffix handling has one source of truth, while preserving
the existing downstream behavior for parse_method and parser_model_name.
In `@rag/llm/cv_model.py`:
- Around line 331-337: Add a structured initialization log in MistralCV.__init__
after resolving base_url and before or after the superclass call, including
model_name and the resolved base URL. Ensure the log context identifies the
Mistral vision flow and excludes key from both structured fields and message
content.
🪄 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: c33ba534-7d7d-4d6f-8932-e039642e815a
📒 Files selected for processing (22)
api/apps/services/provider_api_service.pyapi/db/joint_services/tenant_model_service.pycommon/constants.pycommon/parser_config_utils.pyconf/llm_factories.jsondeepdoc/parser/mistral_parser.pyrag/app/book.pyrag/app/laws.pyrag/app/manual.pyrag/app/naive.pyrag/app/one.pyrag/app/paper.pyrag/app/presentation.pyrag/flow/parser/parser.pyrag/llm/cv_model.pyrag/llm/ocr_model.pytest/unit_test/common/test_mistral_ocr_env.pytest/unit_test/common/test_mistral_ocr_factory.pytest/unit_test/common/test_parser_config_utils_mistral.pytest/unit_test/deepdoc/parser/test_mistral_ocr_model.pytest/unit_test/deepdoc/parser/test_mistral_parser.pytest/unit_test/llm/test_mistral_cv.py
| def __init__( | ||
| self, | ||
| base_url: str, | ||
| api_key: str = "", | ||
| *, | ||
| model: str = "mistral-ocr-latest", | ||
| table_format: str = "html", | ||
| keep_header_footer: bool = False, | ||
| timeout: int = 600, | ||
| inline_max_bytes: int = 20 * 1024 * 1024, | ||
| ): | ||
| self.base_url = (base_url or "https://api.mistral.ai/v1").strip().rstrip("/") | ||
| self.api_key = api_key | ||
| self.model = model | ||
| self.table_format = table_format.strip().lower() if table_format else "html" | ||
| self.keep_header_footer = bool(keep_header_footer) | ||
| self.timeout = int(timeout) | ||
| self.inline_max_bytes = int(inline_max_bytes) |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift
Validate base_url with the server’s outbound-request policy.
The configurable URL is used to upload document contents and read response bodies without restricting private, loopback, link-local, or metadata endpoints. A crafted provider URL therefore creates an SSRF path. Validate resolved destinations and redirects centrally before issuing these requests.
Also applies to: 419-445
🤖 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/mistral_parser.py` around lines 58 - 75, Update the Mistral
parser’s base URL handling and the outbound request flow around the document
upload and response-reading logic to enforce the server’s existing
outbound-request policy. Validate resolved destinations, including every
redirect target, before issuing requests, and reject private, loopback,
link-local, and metadata endpoints; apply the same centralized validation to the
request paths referenced near the later upload/response handling block.
Source: Linters/SAST tools
- MistralOcrModel: preserve a flat config whose api_key is a plain string (was discarded, leaving the parser with no key) + regression test. - _call_ocr cleanup: treat a non-2xx DELETE response as a cleanup failure (was silently accepted, potentially retaining uploaded PDFs). - parse_pdf page selector: bound by the real page count, never the MAXIMUM_PAGE_NUMBER sentinel, so a failed render can't build a ~100k list. - tests: replace assert-False exception checks with pytest.raises (Ruff B011), assert the preserved model ref in the case-insensitive suffix test (RUF059). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #17057 +/- ##
=======================================
Coverage 90.65% 90.65%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 650 650
Misses 39 39
Partials 28 28 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Address xhigh review findings on the Mistral OCR parser: - _resolve_internal_type: accept Optional[str] so a block with a missing/null "type" falls back to text instead of raising BeartypeCallHintParamViolation in production. - _normalize_pages: coerce a present-but-null "index" to 0 (dict.get's default only applies to an absent key), avoiding None + 1 TypeError in _line_tag. - _line_tag: clamp rescaled coords to >= 0 so a bbox bleeding past the page origin is not silently dropped by extract_positions' regex. - Remove dead code: the unused table_id block field and the permanently empty ALWAYS_DISCARDED set plus its guard. Add regression tests for the three hardening fixes. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
| "tags": "OCR", | ||
| "status": "1", | ||
| "rank": "930", | ||
| "llm": [] |
There was a problem hiding this comment.
It would be better to add a default model (like MinerU-model above), in case users are unable to add a model through the model provider page.
There was a problem hiding this comment.
Thanks — done in c644fa3b. I added a default model to the Mistral OCR factory, matching the MinerU-model / SoMark-model convention.
One deliberate difference: I used the real model id mistral-ocr-latest as the llm_name rather than a Mistral OCR-model placeholder.
The reason is that the other OCR providers and Mistral select the OCR engine differently. MinerU, SoMark and OpenDataLoader are dedicated OCR services — the engine is chosen by which endpoint the file is POSTed to (/file_parse, /submit, …), and no model id is sent in the request body, so their *-model llm_name is a purely internal label. Mistral, by contrast, is a multi-model API: api.mistral.ai/v1 serves chat, embeddings, vision and OCR behind one base URL, so the /v1/ocr call must carry a "model" field to say which model to run. The parser threads the selected name straight through as "model": self.model (deepdoc/parser/mistral_parser.py:398), so the llm_name is the API model id — a placeholder like Mistral OCR-model would come back as a model not found / 422 error.
Everything else (tags: OCR, max_tokens: 8192, model_type: ocr) follows the same shape as the other OCR factories.
Per maintainer review: like the other OCR factories (MinerU-model, SoMark-model, ...), the Mistral OCR factory must list a default model so it is usable without manually adding one through the model provider page. Use the real API id "mistral-ocr-latest" as the llm_name rather than a "Mistral OCR-model" placeholder: the parser POSTs self.model verbatim to Mistral's /v1/ocr endpoint, so a placeholder name would be rejected by the API. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The factory now ships a default mistral-ocr-latest model, so the assertion that its llm list is empty is stale. Assert the default model is present and correctly shaped (ocr type, OCR tag) instead. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
commented
Jul 23, 2026
|
CI red checks are environmental network flakes, not code issues — a re-run should clear them. The failing checks are all outbound-network failures on the runners, at test collection/setup time, in files unrelated to this PR:
None touch the files changed here. Where the network cooperated, everything this PR affects is green: on Could a maintainer re-run the failed jobs when convenient? I don't have re-run permissions on the repo. Thanks! |
What problem does this PR solve?
Adds first-class support for Mistral OCR (
POST /v1/ocr) as a document parser, and fixes the long-standing bug where selectingmistral-ocr-latestfails withCan't find model for <tenant>/image2text/mistral-ocr-latest.mistral-ocr-latestis Mistral's dedicated document-OCR endpoint, not a vision-chat (image2text) model, but the catalog tagged itimage2text— so it resolved to theCvModelregistry, which has noMistralentry, and there was noOcrModelentry either. This PR registers it correctly and wires it end to end.Closes #17056
Closes #5782
Closes #7075
What it does
MistralParser+MistralOcrModel(deepdoc/parser/mistral_parser.py,rag/llm/ocr_model.py) — a properOcrModelfactoryMistral OCR, mirroring the SoMark cloud-OCR template. Tables stay inline as HTML; the page range maps to Mistral's nativepagesselector (absolute page indices, billed per selected page, so multi-task documents do not re-OCR the whole file); documents over the inline limit go through the/v1/filessigned-URL flow with cleanup.image2textmis-tag formistral-ocr-latestfrom theMistralfactory inconf/llm_factories.json(it now lives only in theMistral OCRfactory, typedocr). This is what closes theCan't find modelpath.MistralCV(rag/llm/cv_model.py) — a thinGptV4subclass over Mistral's OpenAI-compatible endpoint, registering aMistralentry in theCvModelregistry so Mistral vision models (pixtral-*) become usable asimage2textat all.image2textmodel (any provider), matching MinerU/deepdoc behaviour.naive,paper,book,laws,manual,one,presentation) and therag/flowDAG path. This also fixes a related latent gap where those chunkers forwarded onlymineru_llm_name, so any model-based OCR provider selected on a non-naivemethod silently fell through.Notes on the API contract (verified against the live Mistral API):
pagesis a selector (returns absoluteindex, bills only the requested pages);include_blocks: truereturns per-block bounding boxes usable for chunk highlighting and figure cropping; large files usePOST /v1/files→ signed URL → OCR →DELETE.Testing: new unit tests cover the response→sections contract (both the 2-tuple
naivepath and the typed 3-tuple DAG path), the position-tag rescale, the HTTP client incl. upload failure/cleanup paths,parse_pdfpage-range threading, registry registration, env config, the suffix normalization, the factory catalog entry,MistralCVregistration, and figure-description injection. Verified end to end against the live Mistral API on real PDFs (table extraction, page-selector cost avoidance, figure captioning).Type of change