From b826463a7daf4fb442004a9951447c6e578b9ed2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 16:01:23 +0000 Subject: [PATCH 1/2] feat(text): per-page output with pages=true; 503/502/500 for OCR failures Closes #21. /text gains an optional `pages` form field. With pages=true the response also carries `pages: [{"page": n, "text": ...}]`, taken from the 1-based metadata["page"] the PDF, image and multi-page TIFF loaders already set. Each page is cleaned exactly as the joined `text` is, and `text` itself is unchanged. Blank pages are kept with empty text so numbering has no gaps. Formats without pages (any load where a Document lacks an integer page) give []. Without the field the response shape is unchanged. OCR service failures no longer answer 400: - 503 for transient ones: Mistral 429/408/5xx left after the SDK's own retries, no response, or httpx transport errors and timeouts. Mistral's Retry-After is forwarded when present. - 502 when Mistral rejects our credentials (401/403). - 500 when OCR is not configured (new OCRNotConfiguredError, still a RuntimeError). Other Mistral 4xx (400/422, the document itself) and non-OCR failures stay 400. The detail message is the same as before in every case, so callers matching on it keep working. /embed is not changed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01URp9mLt2aeYaLwVPocNnyH --- README.md | 10 ++ app/routes/document_routes.py | 63 +++++++-- app/utils/document_loader.py | 72 +++++++++- tests/test_text_pages.py | 240 ++++++++++++++++++++++++++++++++++ 4 files changed, 372 insertions(+), 13 deletions(-) create mode 100644 tests/test_text_pages.py diff --git a/README.md b/README.md index f4990af6..70d5412a 100644 --- a/README.md +++ b/README.md @@ -260,6 +260,16 @@ The following environment variables are required to run the application: Make sure to set these environment variables before running the application. You can set them in a `.env` file or as system environment variables. +### `/text` endpoint + +`POST /text` (multipart form: `file_id`, `file`, optional `entity_id`) extracts a file's text without embedding it and answers `{"text", "file_id", "filename", "known_type"}`. + +- **Per-page output:** send `pages=true` to also get `"pages": [{"page": 1, "text": "…"}, …]`, so callers can cite by page. Pages are 1-based and come from the loaders that have them: PDFs, standalone images, and multi-page TIFFs (one entry per frame). Each page's text is cleaned the same way as `text`, which is unchanged by the flag. Blank pages are **kept** with empty text, so the numbering has no gaps. For formats without pages (`.docx`, `.eml`, `.msg`, `.rtf`, `.xlsx`, `.pptx`, text files…), `pages` is `[]`; use `text`. Without the field the response has no `pages` key. +- **Status codes:** `400` means a problem with the file itself (unsupported, encrypted, corrupt, or rejected by Mistral as unreadable). Failures of the OCR service get their own codes, with the same `detail` message as before: + - `503`: transient, retry later. Mistral rate limits (429), timeouts (408) and server errors (5xx) left after the SDK's own retries, or Mistral unreachable or timing out. Mistral's `Retry-After` header is forwarded when it sends one. + - `502`: Mistral rejected this server's API key (401/403). + - `500`: OCR is not configured on this server (`MISTRAL_API_KEY` unset). + ### Embedding Batch Processing For large files, you can enable batched embedding processing to reduce memory consumption. This is particularly useful in memory-constrained environments like Kubernetes pods with memory limits. diff --git a/app/routes/document_routes.py b/app/routes/document_routes.py index c3cdb2ee..6d49133b 100644 --- a/app/routes/document_routes.py +++ b/app/routes/document_routes.py @@ -95,6 +95,7 @@ def _apply_distance_threshold(documents): from app.utils.document_loader import ( get_loader, clean_text, + classify_ocr_failure, process_documents, cleanup_temp_encoding_file, ) @@ -362,22 +363,46 @@ async def load_file_content( cleanup_temp_encoding_file(loader) +def _document_text(doc: Document, file_ext: str) -> str: + """A loaded document's text as ``/text`` returns it (cleaned for PDFs).""" + return clean_text(doc.page_content) if file_ext == "pdf" else doc.page_content + + def extract_text_from_documents(documents: List[Document], file_ext: str) -> str: """Extract text content from loaded documents.""" text_content = "" if documents: for doc in documents: if hasattr(doc, "page_content"): - # Clean text if it's a PDF - if file_ext == "pdf": - text_content += clean_text(doc.page_content) + "\n" - else: - text_content += doc.page_content + "\n" + text_content += _document_text(doc, file_ext) + "\n" # Remove trailing newline return text_content.rstrip("\n") +def _page_number(doc: Document) -> Optional[int]: + page = getattr(doc, "metadata", {}).get("page") + return page if isinstance(page, int) and not isinstance(page, bool) else None + + +def extract_pages_from_documents(documents: List[Document], file_ext: str) -> List[dict]: + """Per-page text for ``/text?pages=true``: ``[{"page": n, "text": ...}]`` in loader order. + + Pages come from the loaders that produce them (PDF, standalone images and + multi-page TIFF), which set a 1-based ``metadata["page"]`` on every + Document. Formats without pages, i.e. any load where some Document lacks + an integer page, give ``[]``. Blank pages are kept with empty text, so the + numbering has no gaps. Each page's text is cleaned exactly as the joined + ``text`` is. + """ + if not documents or any(_page_number(doc) is None for doc in documents): + return [] + return [ + {"page": _page_number(doc), "text": _document_text(doc, file_ext)} + for doc in documents + ] + + async def cleanup_temp_file_async(file_path: str) -> None: """Clean up temporary file asynchronously.""" try: @@ -1523,10 +1548,19 @@ async def extract_text_from_file( file_id: str = Form(...), file: UploadFile = File(...), entity_id: str = Form(None), + pages: bool = Form(False), ): """ Extract text content from an uploaded file without creating embeddings. Returns the raw text content for text parsing purposes. + + With ``pages=true`` the response also carries ``pages``, the text of each + page (see :func:`extract_pages_from_documents`); without it the response + is unchanged. + + A failure of the OCR service answers 503 (try again later), 502 (it + rejected our credentials) or 500 (OCR not configured) instead of 400, + which stays for problems with the file itself. """ user_id = get_user_id(request, entity_id) validated_temp_file_path = _make_unique_temp_path(user_id, file.filename) @@ -1552,12 +1586,15 @@ async def extract_text_from_file( # Extract text content from loaded documents text_content = extract_text_from_documents(data, file_ext) - return { + response = { "text": text_content, "file_id": file_id, "filename": file.filename, "known_type": known_type, } + if pages: + response["pages"] = extract_pages_from_documents(data, file_ext) + return response except HTTPException as http_exc: logger.error( @@ -1578,10 +1615,14 @@ async def extract_text_from_file( status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.PANDOC_NOT_INSTALLED, ) - else: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Error during text extraction: {str(e)}", - ) + # The detail stays the same whatever the status, so callers that match + # on it keep working. + ocr_failure = classify_ocr_failure(e) + status_code, retry_after = ocr_failure or (status.HTTP_400_BAD_REQUEST, None) + raise HTTPException( + status_code=status_code, + detail=f"Error during text extraction: {str(e)}", + headers={"Retry-After": retry_after} if retry_after else None, + ) finally: await cleanup_temp_file_async(validated_temp_file_path) diff --git a/app/utils/document_loader.py b/app/utils/document_loader.py index de80a48f..e2bcf893 100644 --- a/app/utils/document_loader.py +++ b/app/utils/document_loader.py @@ -311,6 +311,74 @@ def process_documents(documents: List[Document]) -> str: return processed_text.strip() +class OCRNotConfiguredError(RuntimeError): + """OCR can't run on this server (``mistralai`` missing or ``MISTRAL_API_KEY`` unset). + + A server misconfiguration, not a problem with the uploaded file and not + something a retry fixes. + """ + + +# Upstream statuses worth retrying later: timeout, rate limit, and server errors (>= 500). +_TRANSIENT_UPSTREAM_STATUSES = frozenset({408, 429}) + + +def _exception_chain(exc: BaseException) -> Iterator[BaseException]: + """``exc`` and the exceptions it was raised from or during, outermost first.""" + seen = set() + while exc is not None and id(exc) not in seen: + seen.add(id(exc)) + yield exc + exc = exc.__cause__ or exc.__context__ + + +def _is_mistral_error(exc: BaseException) -> bool: + # By module rather than isinstance, so this works without importing the SDK. + return type(exc).__module__.startswith("mistralai") + + +def classify_ocr_failure(exc: BaseException) -> Optional[tuple]: + """Map an extraction failure caused by the OCR service to ``(http_status, retry_after)``. + + Returns None when the failure isn't the OCR service's (an unsupported, + encrypted or corrupt file, or any non-OCR error), so the caller keeps its + own status for it. Otherwise: + + - 503 for transient failures, worth retrying later: Mistral rate limits + (429), timeouts (408) and server errors (5xx) left after the SDK's own + retries, no response, and network errors or timeouts reaching it. + ``retry_after`` is Mistral's ``Retry-After`` header when it sent one. + - 502 when Mistral rejects this server's credentials (401/403). + - 500 when OCR isn't configured on this server (:class:`OCRNotConfiguredError`). + + Other Mistral 4xx responses (e.g. 400/422 for a document it can't read) + return None: they are about the file. + """ + try: + import httpx + except Exception: # pragma: no cover - httpx ships with mistralai + httpx = None + + for error in _exception_chain(exc): + if isinstance(error, OCRNotConfiguredError): + return 500, None + if httpx is not None and isinstance(error, httpx.TransportError): + return 503, None # includes timeouts and connection errors + if not _is_mistral_error(error): + continue + status_code = getattr(error, "status_code", None) + if status_code is None: + return 503, None # NoResponseError: nothing came back + if status_code in _TRANSIENT_UPSTREAM_STATUSES or status_code >= 500: + headers = getattr(error, "headers", None) + retry_after = headers.get("retry-after") if headers is not None else None + return 503, retry_after + if status_code in (401, 403): + return 502, None + return None + return None + + def _mistral_ocr_client(): """Import mistralai, validate the API key, and return a configured client. @@ -321,12 +389,12 @@ def _mistral_ocr_client(): try: from mistralai.client import Mistral except Exception as e: - raise RuntimeError( + raise OCRNotConfiguredError( "mistralai package is required for OCR. Please install 'mistralai>=2.0.0' and set MISTRAL_API_KEY." ) from e if not MISTRAL_API_KEY: - raise RuntimeError( + raise OCRNotConfiguredError( "MISTRAL_API_KEY is not set. Please configure it in environment variables." ) diff --git a/tests/test_text_pages.py b/tests/test_text_pages.py new file mode 100644 index 00000000..6a0012d6 --- /dev/null +++ b/tests/test_text_pages.py @@ -0,0 +1,240 @@ +"""/text: per-page output (``pages=true``) and status codes for OCR service failures. + +The Mistral client is faked, but the loaders, the route and the SDK's own +exception types are real. +""" + +import datetime +import os +from concurrent.futures import ThreadPoolExecutor +from types import SimpleNamespace +from unittest.mock import MagicMock + +import httpx +import jwt +import pytest +from fastapi.testclient import TestClient +from mistralai.client.errors import NoResponseError, SDKError + +from app.utils import document_loader +from main import app + +client = TestClient(app) + + +@pytest.fixture(autouse=True) +def thread_pool(): + # The app creates its pool on startup, which TestClient without a context manager skips. + if getattr(app.state, "thread_pool", None) is None: + app.state.thread_pool = ThreadPoolExecutor(max_workers=2) + + +@pytest.fixture +def auth_headers(): + os.environ["JWT_SECRET"] = "testsecret" + payload = { + "id": "testuser", + "exp": datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1), + } + return {"Authorization": f"Bearer {jwt.encode(payload, 'testsecret', algorithm='HS256')}"} + + +def _ocr_response(*markdowns): + return SimpleNamespace( + pages=[SimpleNamespace(markdown=md, images=[]) for md in markdowns] + ) + + +@pytest.fixture +def ocr(monkeypatch): + """A fake Mistral client; set ``ocr.ocr.process.side_effect`` / ``return_value``.""" + fake = MagicMock() + monkeypatch.setattr(document_loader, "_mistral_ocr_client", lambda: fake) + monkeypatch.setattr(document_loader, "MISTRAL_OCR_EMBEDDED_IMAGES", False) + return fake + + +def _post_text(path, filename, content_type, headers, **form): + with open(path, "rb") as f: + return client.post( + "/text", + data={"file_id": "f1", **form}, + files={"file": (filename, f, content_type)}, + headers=headers, + ) + + +@pytest.fixture +def pdf_file(tmp_path): + path = tmp_path / "contract.pdf" + path.write_bytes(b"%PDF-1.4 not parsed locally; OCR is faked") + return path + + +def _upstream_error(status_code, headers=None): + response = httpx.Response( + status_code, headers=headers, request=httpx.Request("POST", "https://api.mistral.ai/v1/ocr") + ) + return SDKError("API error occurred", response, "upstream said no") + + +# --- pages=true ------------------------------------------------------------- + + +def test_pdf_pages_numbered_and_text_unchanged(ocr, pdf_file, auth_headers): + ocr.ocr.process.return_value = _ocr_response("first\x00 page", "second page", "third page") + + plain = _post_text(pdf_file, "contract.pdf", "application/pdf", auth_headers) + paged = _post_text(pdf_file, "contract.pdf", "application/pdf", auth_headers, pages="true") + + assert plain.status_code == 200 and paged.status_code == 200, paged.text + assert "pages" not in plain.json() + body = paged.json() + assert body["pages"] == [ + {"page": 1, "text": "first page"}, # cleaned like the joined text (NUL removed) + {"page": 2, "text": "second page"}, + {"page": 3, "text": "third page"}, + ] + assert {k: v for k, v in body.items() if k != "pages"} == plain.json() + assert body["text"] == "first page\nsecond page\nthird page" + + +def test_blank_pages_are_kept_with_empty_text(ocr, pdf_file, auth_headers): + ocr.ocr.process.return_value = _ocr_response("cover", "", "body") + + response = _post_text(pdf_file, "contract.pdf", "application/pdf", auth_headers, pages="true") + + assert [p["page"] for p in response.json()["pages"]] == [1, 2, 3] + assert response.json()["pages"][1]["text"] == "" + + +def test_multipage_tiff_returns_one_entry_per_frame(ocr, tmp_path, auth_headers): + from PIL import Image + + path = tmp_path / "scan.tiff" + frames = [Image.new("RGB", (8, 8), color) for color in ("white", "black", "gray")] + frames[0].save(path, format="TIFF", save_all=True, append_images=frames[1:]) + ocr.ocr.process.side_effect = [_ocr_response(f"frame {n}") for n in (1, 2, 3)] + + response = _post_text(path, "scan.tiff", "image/tiff", auth_headers, pages="true") + + assert response.status_code == 200, response.text + assert response.json()["pages"] == [ + {"page": 1, "text": "frame 1"}, + {"page": 2, "text": "frame 2"}, + {"page": 3, "text": "frame 3"}, + ] + + +def test_format_without_pages_returns_empty_list(tmp_path, auth_headers): + pytest.importorskip("pypandoc") + from docx import Document as DocxDocument + + path = tmp_path / "memo.docx" + doc = DocxDocument() + doc.add_paragraph("Smlouva o dílo") + doc.save(path) + docx_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" + + plain = _post_text(path, "memo.docx", docx_type, auth_headers) + paged = _post_text(path, "memo.docx", docx_type, auth_headers, pages="true") + + assert paged.status_code == 200, paged.text + assert paged.json()["pages"] == [] + assert paged.json()["text"] == plain.json()["text"] + assert "Smlouva o dílo" in paged.json()["text"] + + +def test_pages_false_keeps_current_shape(tmp_path, auth_headers): + path = tmp_path / "note.txt" + path.write_text("hello") + + response = _post_text(path, "note.txt", "text/plain", auth_headers, pages="false") + + assert set(response.json()) == {"text", "file_id", "filename", "known_type"} + + +# --- OCR service failures ----------------------------------------------------- + + +@pytest.mark.parametrize("status_code", [429, 408, 500, 502, 503]) +def test_transient_upstream_failure_answers_503(ocr, pdf_file, auth_headers, status_code): + ocr.ocr.process.side_effect = _upstream_error(status_code) + + response = _post_text(pdf_file, "contract.pdf", "application/pdf", auth_headers) + + assert response.status_code == 503 + # Same detail as before, so callers matching on it keep working. + assert response.json()["detail"].startswith("Error during text extraction: ") + + +def test_rate_limit_forwards_retry_after(ocr, pdf_file, auth_headers): + ocr.ocr.process.side_effect = _upstream_error(429, headers={"Retry-After": "7"}) + + response = _post_text(pdf_file, "contract.pdf", "application/pdf", auth_headers) + + assert response.status_code == 503 + assert response.headers["retry-after"] == "7" + + +@pytest.mark.parametrize( + "error", + [ + httpx.ReadTimeout("timed out"), + httpx.ConnectError("connection refused"), + NoResponseError(), + ], +) +def test_timeout_or_unreachable_answers_503(ocr, pdf_file, auth_headers, error): + ocr.ocr.process.side_effect = error + + response = _post_text(pdf_file, "contract.pdf", "application/pdf", auth_headers) + + assert response.status_code == 503 + assert "retry-after" not in response.headers + + +@pytest.mark.parametrize("status_code", [401, 403]) +def test_rejected_credentials_answer_502(ocr, pdf_file, auth_headers, status_code): + ocr.ocr.process.side_effect = _upstream_error(status_code) + + response = _post_text(pdf_file, "contract.pdf", "application/pdf", auth_headers) + + assert response.status_code == 502 + + +def test_ocr_not_configured_answers_500(monkeypatch, pdf_file, auth_headers): + monkeypatch.setattr(document_loader, "MISTRAL_API_KEY", "") + + response = _post_text(pdf_file, "contract.pdf", "application/pdf", auth_headers) + + assert response.status_code == 500 + assert "MISTRAL_API_KEY" in response.json()["detail"] + + +@pytest.mark.parametrize("status_code", [400, 422]) +def test_mistral_rejecting_the_document_stays_400(ocr, pdf_file, auth_headers, status_code): + ocr.ocr.process.side_effect = _upstream_error(status_code) + + response = _post_text(pdf_file, "contract.pdf", "application/pdf", auth_headers) + + assert response.status_code == 400 + + +def test_non_ocr_failure_stays_400(ocr, pdf_file, auth_headers): + ocr.ocr.process.side_effect = ValueError("file is corrupt") + + response = _post_text(pdf_file, "contract.pdf", "application/pdf", auth_headers) + + assert response.status_code == 400 + assert response.json()["detail"] == "Error during text extraction: file is corrupt" + + +def test_failure_wrapped_by_another_exception_is_still_classified(): + try: + try: + raise _upstream_error(429) + except SDKError as inner: + raise RuntimeError("load failed") from inner + except RuntimeError as outer: + assert document_loader.classify_ocr_failure(outer) == (503, None) From cdaee75d93efbb99a0e1d01e5aa00a33fe308cb9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 16:24:04 +0000 Subject: [PATCH 2/2] fix(text): tighten OCR failure classification after review - Follow the exception chain as Python prints it: stop at a context hidden with `raise ... from None`, so a deliberate file error raised while handling a Mistral error is not reported as an OCR outage. - A Mistral error with a non-error status (e.g. ResponseValidationError on a 200 the SDK can't parse) is upstream's fault: 502, not 400. - Only NoResponseError counts as a transient Mistral error without a status; other errors from mistralai modules that carry no HTTP status are no longer 503. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01URp9mLt2aeYaLwVPocNnyH --- README.md | 978 +++++++++++++++++------------------ app/utils/document_loader.py | 28 +- tests/test_text_pages.py | 33 +- 3 files changed, 542 insertions(+), 497 deletions(-) diff --git a/README.md b/README.md index 70d5412a..9ddda5c7 100644 --- a/README.md +++ b/README.md @@ -1,489 +1,489 @@ -# ID-based RAG FastAPI - -> ## About this fork -> -> This is a fork of [danny-avila/rag_api](https://github.com/danny-avila/rag_api), tailored for legal-office document workflows. It keeps full upstream compatibility (same API, same LibreChat integration) while changing how several document types are loaded and adding new ones. **Key differences from upstream:** -> -> - **Remote OCR via Mistral** — PDFs and standalone images (`.png`, `.jpg`, `.jpeg`, `.gif`, `.bmp`, `.tif`/`.tiff`, `.webp`) are OCR'd through the [Mistral OCR API](https://docs.mistral.ai/) instead of a bundled local OCR engine. Set `MISTRAL_API_KEY` to enable. Because OCR is remote, the local OCR/computer-vision stack (`rapidocr-onnxruntime`, `opencv`, `onnxruntime`) has been **removed**, which also makes the image considerably smaller. -> - **Richer DOCX text extraction** — `.docx` files routed to `/text` are converted with [pandoc](https://pandoc.org/), preserving tracked changes, comments, and (optionally) headers/footers. Tables are written as compact pipe tables and the Markdown is cleaned of extraction noise, so a bilingual contract laid out as one long table no longer extracts at several times its content size. Configurable via `DOCX_TEXT_USE_PANDOC`, `DOCX_TEXT_TRACK_CHANGES`, `DOCX_TEXT_INCLUDE_HEADERS_FOOTERS`, `DOCX_TEXT_TABLE_STYLE`, `DOCX_TEXT_CLEANUP`, `DOCX_TEXT_STRIP_HEADING_ANCHORS` and `DOCX_TEXT_DROP_TOC`. -> - **Email support** — `.eml` and `.msg` (Outlook) files are parsed, with sender/recipient/subject/date headers optionally prepended (`EMAIL_INCLUDE_HEADERS`). Bcc is never exposed. -> - **`.rtf` support** added. -> - **Legacy `.doc` is rejected** with a clear error asking the user to convert to `.docx` (the old binary format could not be loaded reliably). -> -> **Prebuilt image:** [`georgx22/rag_api_lite`](https://hub.docker.com/r/georgx22/rag_api_lite) on Docker Hub — the lite build (no local embedding stack; uses remote embeddings + remote Mistral OCR). - -## Overview -This project integrates Langchain with FastAPI in an Asynchronous, Scalable manner, providing a framework for document indexing and retrieval, using PostgreSQL/pgvector. - -Files are organized into embeddings by `file_id`. The primary use case is for integration with [LibreChat](https://librechat.ai), but this simple API can be used for any ID-based use case. - -The main reason to use the ID approach is to work with embeddings on a file-level. This makes for targeted queries when combined with file metadata stored in a database, such as is done by LibreChat. - -The API will evolve over time to employ different querying/re-ranking methods, embedding models, and vector stores. - -## Features -- **Document Management**: Methods for adding, retrieving, and deleting documents. -- **Vector Store**: Utilizes Langchain's vector store for efficient document retrieval. -- **Asynchronous Support**: Offers async operations for enhanced performance. - -## Retrieval scope - -Chunks are owned. Every route that reads or removes stored content resolves the -caller's owner set from the verified token and puts it into the store query -*before* ranking, so a chunk outside that set is never read into the process. -The owner set is built in one place — `app/scope.py` — rather than re-derived per -route. - -Before this release these routes addressed the store by caller-supplied -`file_id` alone, or authorized a whole result set from the first hit returned: - -- `GET /ids` listed every file id in the deployment. -- `POST /query_multiple` performed no authorization at all, so pairing it with - `GET /ids` disclosed the content of every file to any authenticated caller. -- `POST /query` authorized the whole result set from `documents[0]`, so any hit - behind the first was never checked. A `file_id` is chosen by whoever uploads, - so an attacker's own row ranking first authorized the rows behind it. -- `GET /documents`, `GET /documents/{id}/context` and `DELETE /documents` read or - deleted the chunks of any file id the caller could name. -- A chunk with no recorded `user_id` read as "belongs to everyone". -- On the synchronous store path, a failed ingestion rolled back by `file_id` - alone, so an upload under someone else's file id destroyed their chunks. The - async pgvector pipeline already scopes its rollback to the ingestion attempt. - -**What changes for callers.** A caller reads and deletes only what it owns. A -file id outside the caller's scope answers "not found" rather than "found but -refused", so none of these routes is an existence oracle. Chunks with no -`user_id` are owned by nobody and are no longer readable — if a deployment holds -such rows and still needs them, stamp an owner on them before upgrading: - -```sql -UPDATE langchain_pg_embedding -SET cmetadata = jsonb_set(cmetadata, '{user_id}', '""') -WHERE cmetadata->>'user_id' IS NULL; -``` - -**If this deployment ever ran without `JWT_SECRET`, check for `public` too.** With -no signing key configured there is no caller identity to record, so every chunk -written in that period is owned by the literal string `public`. Once a signing -key is set, callers arrive with their own ids and none of them owns `public`, so -that content stops being readable. Routes other than `/query` returned it to -everybody before this release, which is exactly the hole being closed — but if -the content is still wanted, give it a real owner first: - -```sql --- inspect before rewriting: this is content nobody was ever identified as owning -SELECT count(*) FROM langchain_pg_embedding WHERE cmetadata->>'user_id' = 'public'; -``` - -Deployments that never set `JWT_SECRET` are unaffected: with no key configured -the read scope is `public` as well, so what was written is what is read. - -`atlas-mongo` deployments must add `user_id` to the vector search index first; -see [Use Atlas MongoDB as Vector Database](#use-atlas-mongodb-as-vector-database). - -**Deleting entity-owned files requires `entity_id`.** Chunks embedded under an -`entity_id` — an agent knowledge base, for instance — are owned by that entity -rather than by the uploading user, so `DELETE /documents` needs the same -`entity_id` that the upload used, as a query parameter alongside the JSON body of -file ids. A delete that omits it resolves to the caller's own scope, matches -nothing, and answers 404 with the chunks left in place. Because a 404 is -indistinguishable from "already deleted", a caller that treats it as success will -orphan those chunks silently. - -**Upgrade the client first.** Deploy order matters, in one direction only: - -- A client that sends `entity_id` against an *older* build is inert — the - parameter is simply undeclared there, so the request behaves exactly as before. -- An *older* client against this build orphans every agent knowledge-base file it - tries to delete. - -So upgrade the client first, or both together — never this service first. -LibreChat carries the matching change: it records the owner each embed was made -under and sends it on delete, with `npm run migrate:embed-owners` to backfill -files embedded before that. - -**`entity_id` is unchanged and still caller-asserted.** Agent knowledge bases are -owned by an agent id rather than a user id, so a caller reading one names it via -`entity_id`. That id now *widens* the owner set rather than replacing the -caller's identity — the caller's own scope always remains — but nothing in a -token minted today proves the caller may act for the entity it names. A caller -that knows another owner's id can still name it — on read, to reach that owner's -chunks, and on the ingestion routes, where `entity_id` is what gets stamped as the -owner, to write into that owner's namespace. Deployments exposing this API to -untrusted callers must continue to authorize entity access upstream. Closing this -requires the token to carry the entity authorization, which is a coordinated -change with the callers that mint those tokens and is tracked separately from -this release. - -## Setup - -### Getting Started - -- **Configure `.env` file based on [section below](#environment-variables)** -- **Setup pgvector database:** - - Run an existing PSQL/PGVector setup, or, - - Docker: `docker compose up` (also starts RAG API) - - or, use docker just for DB: `docker compose -f ./db-compose.yaml up` -- **Run API**: - - Docker: `docker compose up` (also starts PSQL/pgvector) - - or, use docker just for RAG API: `docker compose -f ./api-compose.yaml up` - - Local: - - Make sure to setup `DB_HOST` to the correct database hostname - - Run the following commands (preferably in a [virtual environment](https://realpython.com/python-virtual-environments-a-primer/)) -```bash -pip install -r requirements.txt -uvicorn main:app -``` - -### Clean Install (Local Development) - -To do a clean reinstall of all dependencies (e.g., after updating `requirements.txt`): - -```bash -# Remove existing virtual environment and recreate it -rm -rf venv -python3 -m venv venv -source venv/bin/activate -pip install -r requirements.txt -``` - -For the lite version (without sentence_transformers/huggingface): - -```bash -rm -rf venv -python3 -m venv venv -source venv/bin/activate -pip install -r requirements.lite.txt -``` - -For Docker, rebuild without cache: - -```bash -docker compose build --no-cache -``` - -### Environment Variables - -The following environment variables are required to run the application: - -- `RAG_OPENAI_API_KEY`: The API key for OpenAI API Embeddings (if using default settings). - - Note: `OPENAI_API_KEY` will work but `RAG_OPENAI_API_KEY` will override it in order to not conflict with LibreChat setting. -- `RAG_OPENAI_BASEURL`: (Optional) The base URL for your OpenAI API Embeddings -- `RAG_OPENAI_PROXY`: (Optional) Proxy for OpenAI API Embeddings - - Note: When using with LibreChat, you can also set `HTTP_PROXY` and `HTTPS_PROXY` environment variables in the `docker-compose.override.yml` file (see [Proxy Configuration](#proxy-configuration) section below) -- `VECTOR_DB_TYPE`: (Optional) select vector database type, default to `pgvector`. -- `POSTGRES_USE_UNIX_SOCKET`: (Optional) Set to "True" when connecting to the PostgreSQL database server with Unix Socket. -- `POSTGRES_DB`: (Optional) The name of the PostgreSQL database, used when `VECTOR_DB_TYPE=pgvector`. -- `POSTGRES_USER`: (Optional) The username for connecting to the PostgreSQL database. -- `POSTGRES_PASSWORD`: (Optional) The password for connecting to the PostgreSQL database. -- `DB_HOST`: (Optional) The hostname or IP address of the PostgreSQL database server. -- `DB_PORT`: (Optional) The port number of the PostgreSQL database server. -- `PGVECTOR_CREATE_EXTENSION`: (Optional) Set to "False" to skip the `CREATE EXTENSION IF NOT EXISTS vector` call on startup. Default is "True". Use this when the `vector` extension is already installed on a managed Postgres (e.g. RDS, Azure Database for PostgreSQL) and the application user is not a superuser. -- `PG_POOL_PRE_PING`: (Optional) Set to "False" to disable SQLAlchemy's pre-ping check. Default is "True". When enabled, the connection pool issues a lightweight `SELECT 1` before handing out a pooled connection, so stale connections dropped by a remote server or middlebox idle timeout are transparently replaced instead of surfacing as query errors. Recommended for any deployment that connects to a remote PostgreSQL instance (managed Postgres, connections that traverse a load balancer, etc.). -- `PG_POOL_RECYCLE`: (Optional) Maximum age in seconds of a pooled connection before it is recycled. Default is "-1" (disabled). Set to a positive value when the server enforces a hard idle or max-lifetime limit (e.g. "1800" for a 30-minute cap). -- `POSTGRES_SCHEMA`: (Optional) Prepend this schema to the Postgres `search_path` so langchain's pgvector tables live in (and are read from) it. Unset by default (uses the user's default schema, typically `public`). Useful when sharing a database with other services — create the schema out-of-band first (`CREATE SCHEMA IF NOT EXISTS ; GRANT USAGE, CREATE ON SCHEMA TO ;`); the RAG API will not create it for you and fails fast at startup if the schema is missing. `public` is always appended to the resulting search path so the `vector` data type stays resolvable when the extension was installed there (the common case). Multiple schemas may be supplied as a comma-separated list (e.g. `myapp,extensions`) when the `vector` extension lives in a non-`public` schema. -- `PGVECTOR_CREATE_LEGACY_INDEXES`: (Optional) Set to "True" to create the legacy `custom_id` and `cmetadata->>'file_id'` indexes on startup. Default is "False". -- `PGVECTOR_MIGRATE_CMETADATA_JSONB`: (Optional) Set to "True" to migrate `langchain_pg_embedding.cmetadata` from JSON to JSONB on startup. Default is "False". -- `PGVECTOR_CREATE_CMETADATA_GIN_INDEX`: (Optional) Set to "True" to create the `cmetadata` JSONB GIN index on startup. Default is "False". The index is created only when `cmetadata` is already JSONB; for a legacy JSON column, also enable `PGVECTOR_MIGRATE_CMETADATA_JSONB` or the index step is skipped. -- `RAG_HOST`: (Optional) The hostname or IP address where the API server will run. Defaults to "0.0.0.0" -- `RAG_PORT`: (Optional) The port number where the API server will run. Defaults to port 8000. -- `JWT_SECRET`: (Optional) The secret key used for verifying JWT tokens for requests. - - The secret is only used for verification. This basic approach assumes a signed JWT from elsewhere. - - Omit to run API without requiring authentication - -- `COLLECTION_NAME`: (Optional) The name of the collection in the vector store. Default value is "testcollection". -- `CHUNK_SIZE`: (Optional) The size of the chunks for text processing. Default value is "1500". -- `CHUNK_OVERLAP`: (Optional) The overlap between chunks during text processing. Default value is "100". -- `EMBEDDING_BATCH_SIZE`: (Optional) Number of document chunks to process per batch. Defaults to `500`; set to `0` to disable batching. Recommended value is `750` for `text-embedding-3-small`. -- `EMBEDDING_MAX_QUEUE_SIZE`: (Optional) Maximum number of batches to buffer in memory during async processing. Default value is "3". -- `PARALLEL_EXECUTION`: (Optional) Maximum number of async embedding/database insertion consumers to run per file when batching is enabled. Default value is "2". -- `RAG_DISTANCE_THRESHOLD`: (Optional, `VECTOR_DB_TYPE=pgvector` only) Drop results whose vector distance is greater than this value, after the top-`k` search. Unset by default (no filtering). Lower distance = more similar, so e.g. `0.5` keeps only hits with distance ≤ 0.5 and discards weaker matches. Useful for reducing downstream LLM token cost when the top-`k` call returns loosely-related chunks. Appropriate values depend on the embedding model and distance strategy — inspect your actual scores before choosing one. Ignored (with a startup warning) under `VECTOR_DB_TYPE=atlas-mongo`, because Atlas returns a similarity score (higher = better) with inverted semantics. -- `RAG_UPLOAD_DIR`: (Optional) The directory where uploaded files are stored. Default value is "./uploads/". -- `DOCX_TEXT_USE_PANDOC`: (Optional) Boolean. When "True" (default), `.docx` files sent to the `/text` endpoint are converted via **pandoc** so tracked changes and comments are preserved (output is Markdown). The embedding path always uses `Docx2txtLoader`. Pandoc only reads OOXML `.docx`; legacy binary `.doc` files are rejected with an error asking you to convert to `.docx`. Requires the `pandoc` binary (already installed in the provided Docker images). -- `DOCX_TEXT_TRACK_CHANGES`: (Optional) pandoc `--track-changes` mode for the `.docx` `/text` path: `all` (default; keep insertions/deletions, record each edit's author/date, and emit comments), `accept` (final text), or `reject` (original text). -- `DOCX_TEXT_INCLUDE_HEADERS_FOOTERS`: (Optional) Boolean. When "True" (default), `.docx` headers/footers (matter numbers, "PRIVILEGED & CONFIDENTIAL", "DRAFT", etc.) — which pandoc drops — are extracted via python-docx and prepended to the `/text` output. Headers/footers holding nothing but a page number ("4", "Page 4 of 10") are skipped. -- `DOCX_TEXT_TABLE_STYLE`: (Optional) `compact` (default) or `grid`. Pandoc's own Markdown writer pads every cell of every row out to the width of the longest line in its column; with `--wrap=none` a single long clause can therefore inflate a whole contract table many times over, most of the output being spaces and `+---+` rules. `compact` disables grid/multiline/simple tables, so pandoc writes unpadded pipe tables and falls back to an HTML `` only for cells holding block content. On bilingual contract tables this cuts the extracted text by 55-82% with no loss of content, tracked changes included. Set `grid` to restore pandoc's default table output; pair it with `DOCX_TEXT_CLEANUP=False`, since grid tables encode their columns as character positions and a cleanup that shortens a row shifts its `|` delimiters off the `+---+` rule (the service warns at startup if you set one without the other); reproducing the pre-fix output byte for byte also needs `DOCX_TEXT_CLEANUP=False` and `DOCX_TEXT_STRIP_HEADING_ANCHORS=False`, which are independent settings. -- `DOCX_TEXT_CLEANUP`: (Optional) Boolean. When "True" (default), the extracted Markdown is stripped of noise that carries no content: table columns that are empty in every row, empty tracked-change spans (a deleted space still costs ~70 bytes of author/date metadata), runs of blank lines from Word spacer paragraphs, and invisible characters (NBSP, soft hyphen, zero-width). Tracked changes that carry text keep their author and date untouched, and comments are preserved. -- `DOCX_TEXT_STRIP_HEADING_ANCHORS`: (Optional) Boolean. When "True" (default), the anchors pandoc derives from Word bookmarks (`# Heading {#_Toc123456789}`) are omitted — they are Word-internal TOC/cross-reference ids, not document content. -- `DOCX_TEXT_DROP_TOC`: (Optional) Boolean. When "True", a Word-generated table of contents (the block of links to `#_Toc` bookmarks) is dropped from the extracted text. Defaults to "False", since in some documents the TOC is the only outline of the agreement. - -> **Upgrading:** these defaults change what `/text` returns for `.docx` files — tables come back as pipe tables (or an HTML `
` for cells holding block content) instead of padded grid tables, and the cleanup pass runs. Anything downstream that depends on the previous Markdown shape byte for byte — a prompt template keyed on grid tables, or a stored extraction being compared against a fresh one — sees different text. Set `DOCX_TEXT_TABLE_STYLE=grid`, `DOCX_TEXT_CLEANUP=False` and `DOCX_TEXT_STRIP_HEADING_ANCHORS=False` to keep the old output. -- `EMAIL_INCLUDE_HEADERS`: (Optional) Boolean. When "True" (default), the From/To/Cc/Subject/Date headers are prepended to extracted email text for `.eml` and `.msg` files. Set "False" to extract the body only. -- `MISTRAL_API_KEY`: (Optional) API key for Mistral OCR, used for PDFs and standalone images. OCR is unavailable without it. -- `MISTRAL_OCR_MODEL`: (Optional) Mistral OCR model. Default value is `mistral-ocr-latest`. -- `MISTRAL_SERVER_URL`: (Optional) Base URL of the Mistral API. Leave unset for the SDK default (`https://api.mistral.ai`); set `https://api.eu.mistral.ai` to keep OCR traffic on Mistral's [EU regional endpoint](https://docs.mistral.ai/inference/regional-inference). Regional endpoints don't offer the Files API, which is fine here: documents and images are sent inline as base64. Confirm with Mistral that your OCR model is served on the regional endpoint before relying on it. - - Note: LibreChat's own `mistral_ocr` strategy uploads through the Files API, so on an EU-only deployment route PDFs and images to this service's `/text` endpoint instead. - - For EU embeddings as well, point `RAG_OPENAI_BASEURL` at an EU OpenAI-compatible endpoint (e.g. `https://eu.openrouter.ai/api/v1`) with a non-OpenAI model such as `mistralai/mistral-embed-2312` (1024 dimensions), and set `RAG_CHECK_EMBEDDING_CTX_LENGTH=False`: with the check on, inputs are sent as OpenAI tiktoken token IDs, which non-OpenAI models don't accept. Switching embedding models requires re-indexing existing files (see `EMBEDDINGS_DIMENSIONS`). -- Standalone image uploads (`.png`, `.jpg/.jpeg`, `.gif`, `.bmp`, `.tif/.tiff`, `.webp`) — including multi-page TIFF — are run through **Mistral OCR**, yielding one result per page. Requires `MISTRAL_API_KEY` (same key used for PDF OCR). This is separate from PDF handling; images embedded inside PDFs are covered by `MISTRAL_OCR_EMBEDDED_IMAGES` below. -- `IMAGE_OCR_MAX_PAGES`: (Optional) Max number of frames/pages of a single image upload (e.g. animated GIF or large multi-page TIFF) sent to OCR; frames beyond the cap are skipped with a warning. Default value is `100`. -- `MISTRAL_OCR_EMBEDDED_IMAGES`: (Optional) Boolean. Mistral OCR returns only a placeholder (`![img-0.jpeg](img-0.jpeg)`) for a raster image embedded in a PDF page, such as a photo or scan of a page, and does not read the text inside it. When "True" (default), those images are extracted, OCR'd in a second Mistral call each, and the recognized text replaces the placeholder. **Each embedded image is billed as an extra OCR page**; set "False" to OCR only the PDF itself. If an image's OCR call fails, its placeholder is kept and the document still loads. -- `MISTRAL_OCR_IMAGE_MIN_SIZE`: (Optional) Minimum image size in pixels for an embedded image to be extracted, so logos and icons are skipped. Default value is `100`. -- `MISTRAL_OCR_MAX_EXTRACTED_IMAGES`: (Optional) Max number of embedded images Mistral extracts per document (minimum `1`), before any filtering; this bounds the size of the OCR response. A warning is logged when the document has more, and the later images are not extracted. Default value is `200`. -- `MISTRAL_OCR_MAX_EMBEDDED_IMAGES`: (Optional) Max number of distinct embedded images OCR'd per document (minimum `1`), i.e. the number of extra billed OCR calls. It is applied after the page-fraction filter and the removal of identical images, in page order; a warning is logged when the document has more, and the extra images are left as placeholders. Default value is `50`. -- `MISTRAL_OCR_IMAGE_MIN_PAGE_FRACTION`: (Optional) Embedded images covering less than this fraction of their page (`0` to `1`) are not OCR'd and keep their placeholder, so letterheads and logos repeated on every page cost nothing. Set to `0` to OCR every extracted image. Skipped images are logged at debug level. Identical images are always OCR'd only once per document. Default value is `0.1`. -- `MISTRAL_OCR_IMAGE_CONCURRENCY`: (Optional) Max number of embedded-image OCR calls in flight at once across all documents and requests (minimum `1`); it is also the parallelism within a single document. Default value is `4`. -- `DEBUG_RAG_API`: (Optional) Set to "True" to show more verbose logging output in the server console, and to enable postgresql database routes -- `DEBUG_PGVECTOR_QUERIES`: (Optional) Set to "True" to enable detailed PostgreSQL query logging for pgvector operations. Useful for debugging performance issues with vector database queries. -- `CONSOLE_JSON`: (Optional) Set to "True" to log as json for Cloud Logging aggregations -- `EMBEDDINGS_PROVIDER`: (Optional) either "openai", "bedrock", "azure", "huggingface", "huggingfacetei", "google_genai", "vertexai", or "ollama", where "huggingface" uses sentence_transformers; defaults to "openai" -- `EMBEDDINGS_MODEL`: (Optional) Set a valid embeddings model to use from the configured provider. - - **Defaults** - - openai: "text-embedding-3-small" - - azure: "text-embedding-3-small" (will be used as your Azure Deployment) - - huggingface: "sentence-transformers/all-MiniLM-L6-v2" - - huggingfacetei: "http://huggingfacetei:3000". Hugging Face TEI uses model defined on TEI service launch. - - vertexai: "gemini-embedding-001" - - ollama: "nomic-embed-text" - - bedrock: "amazon.titan-embed-text-v1" - - google_genai: "gemini-embedding-001" -- `EMBEDDINGS_CHUNK_SIZE`: (Optional) The chunk size used by the OpenAI and Azure embeddings clients to limit the number of inputs per request. Default value is `200`. -- `EMBEDDINGS_DIMENSIONS`: (Optional) Output vector size to request from the embedding model. Only honored by the `openai` and `azure` providers, and only supported by `text-embedding-3-*` models. Leave unset to use the model's native dimensionality (1536 for `text-embedding-3-small`, 3072 for `text-embedding-3-large`). Setting a smaller value (e.g. `512`, `1024`) trades some retrieval quality for lower storage cost and faster similarity search. Note: do not change this on an existing collection — all vectors in a `pgvector` column must share the same dimensionality. -- `RAG_AZURE_OPENAI_API_VERSION`: (Optional) Default is `2023-05-15`. The version of the Azure OpenAI API. -- `RAG_AZURE_OPENAI_API_KEY`: (Optional) The API key for Azure OpenAI service. - - Note: `AZURE_OPENAI_API_KEY` will work but `RAG_AZURE_OPENAI_API_KEY` will override it in order to not conflict with LibreChat setting. -- `RAG_AZURE_OPENAI_ENDPOINT`: (Optional) The endpoint URL for Azure OpenAI service, including the resource. - - Example: `https://YOUR_RESOURCE_NAME.openai.azure.com`. - - Note: `AZURE_OPENAI_ENDPOINT` will work but `RAG_AZURE_OPENAI_ENDPOINT` will override it in order to not conflict with LibreChat setting. -- `HF_TOKEN`: (Optional) if needed for `huggingface` option. -- `OLLAMA_BASE_URL`: (Optional) defaults to `http://ollama:11434`. -- `ATLAS_SEARCH_INDEX`: (Optional) the name of the vector search index if using Atlas MongoDB, defaults to `vector_index` -- `MONGO_VECTOR_COLLECTION`: Deprecated for MongoDB, please use `ATLAS_SEARCH_INDEX` and `COLLECTION_NAME` -- `AWS_DEFAULT_REGION`: (Optional) defaults to `us-east-1` -- `AWS_ACCESS_KEY_ID`: (Optional) needed for bedrock embeddings -- `AWS_SECRET_ACCESS_KEY`: (Optional) needed for bedrock embeddings -- `GOOGLE_API_KEY`, `GOOGLE_KEY`, `RAG_GOOGLE_API_KEY`: (Optional) Google API key for Google GenAI embeddings. Priority order: RAG_GOOGLE_API_KEY > GOOGLE_KEY > GOOGLE_API_KEY -- `AWS_SESSION_TOKEN`: (Optional) may be needed for bedrock embeddings -- `GOOGLE_APPLICATION_CREDENTIALS`: (Optional) needed for Google VertexAI embeddings. This should be a path to a service account credential file in JSON format. -- `GOOGLE_CLOUD_PROJECT`: (Optional) Google Cloud project ID, needed for VertexAI embeddings. -- `GOOGLE_CLOUD_LOCATION`: (Optional) Google Cloud region for VertexAI embeddings. Defaults to `us-central1`. -- `RAG_CHECK_EMBEDDING_CTX_LENGTH` (Optional) Default is true, disabling this will send raw input to the embedder, use this for custom embedding models. - -Make sure to set these environment variables before running the application. You can set them in a `.env` file or as system environment variables. - -### `/text` endpoint - -`POST /text` (multipart form: `file_id`, `file`, optional `entity_id`) extracts a file's text without embedding it and answers `{"text", "file_id", "filename", "known_type"}`. - -- **Per-page output:** send `pages=true` to also get `"pages": [{"page": 1, "text": "…"}, …]`, so callers can cite by page. Pages are 1-based and come from the loaders that have them: PDFs, standalone images, and multi-page TIFFs (one entry per frame). Each page's text is cleaned the same way as `text`, which is unchanged by the flag. Blank pages are **kept** with empty text, so the numbering has no gaps. For formats without pages (`.docx`, `.eml`, `.msg`, `.rtf`, `.xlsx`, `.pptx`, text files…), `pages` is `[]`; use `text`. Without the field the response has no `pages` key. -- **Status codes:** `400` means a problem with the file itself (unsupported, encrypted, corrupt, or rejected by Mistral as unreadable). Failures of the OCR service get their own codes, with the same `detail` message as before: - - `503`: transient, retry later. Mistral rate limits (429), timeouts (408) and server errors (5xx) left after the SDK's own retries, or Mistral unreachable or timing out. Mistral's `Retry-After` header is forwarded when it sends one. - - `502`: Mistral rejected this server's API key (401/403). - - `500`: OCR is not configured on this server (`MISTRAL_API_KEY` unset). - -### Embedding Batch Processing - -For large files, you can enable batched embedding processing to reduce memory consumption. This is particularly useful in memory-constrained environments like Kubernetes pods with memory limits. - -#### Configuration - -| Variable | Default | Description | -|----------|---------|-------------| -| `EMBEDDING_BATCH_SIZE` | `500` | Number of document chunks to process per batch. `0` disables batching (original behavior). | -| `EMBEDDING_MAX_QUEUE_SIZE` | `3` | Maximum number of batches to buffer in memory during async processing. | -| `PARALLEL_EXECUTION` | `2` | Maximum number of async embedding/database insertion consumers per file when batching is enabled. | - -#### Recommended Settings - -For `text-embedding-3-small` model: -- `EMBEDDING_BATCH_SIZE=750` - Good balance of throughput and memory - -For memory-constrained environments (< 2GB RAM): -- `EMBEDDING_BATCH_SIZE=100-250` - -For high-throughput environments: -- `EMBEDDING_BATCH_SIZE=1000-2000` -- `EMBEDDING_MAX_QUEUE_SIZE=5` -- Increase `PARALLEL_EXECUTION` cautiously; it applies per active file upload. - -#### Behavior - -When `EMBEDDING_BATCH_SIZE > 0`: -- Documents are processed in batches of the specified size -- Up to `PARALLEL_EXECUTION` batches for the same file can be embedded and inserted concurrently -- `PARALLEL_EXECUTION` is per request/file. Total process concurrency can be roughly `active uploads * PARALLEL_EXECUTION`, bounded indirectly by `RAG_THREAD_POOL_SIZE` and downstream provider/database limits -- On failure, remaining batch work is stopped and successfully inserted documents are rolled back -- Memory usage is bounded by queued plus active batches, roughly `EMBEDDING_BATCH_SIZE * (EMBEDDING_MAX_QUEUE_SIZE + PARALLEL_EXECUTION)` -- Ingestion lifecycle logs include route, user, file, chunk count, file size, elapsed time, and selected process memory context. Per-batch queue/insert progress is logged at debug level - -When `EMBEDDING_BATCH_SIZE <= 0`: -- All documents are processed at once (original behavior) -- Better for small files or memory-rich environments - -### Use Atlas MongoDB as Vector Database - -Instead of using the default pgvector, we could use [Atlas MongoDB](https://www.mongodb.com/products/platform/atlas-vector-search) as the vector database. To do so, set the following environment variables - -```env -VECTOR_DB_TYPE=atlas-mongo -ATLAS_MONGO_DB_URI= -COLLECTION_NAME= -ATLAS_SEARCH_INDEX= -``` - -The `ATLAS_MONGO_DB_URI` could be the same or different from what is used by LibreChat. Even if it is the same, the `$COLLECTION_NAME` collection needs to be a completely new one, separate from all collections used by LibreChat. In addition, create a vector search index for collection above (remember to assign `$ATLAS_SEARCH_INDEX`) with the following json: - -```json -{ - "fields": [ - { - "numDimensions": 1536, - "path": "embedding", - "similarity": "cosine", - "type": "vector" - }, - { - "path": "file_id", - "type": "filter" - }, - { - "path": "user_id", - "type": "filter" - } - ] -} -``` - -Follow one of the [four documented methods](https://www.mongodb.com/docs/atlas/atlas-vector-search/create-index/#procedure) to create the vector index. - -> **Upgrading an existing Atlas deployment:** `user_id` is a required filter field -> as of the release described under [Retrieval scope](#retrieval-scope). Retrieval -> now filters on it, and Atlas Vector Search rejects a `$vectorSearch` pre-filter on -> a path the index does not declare — so add it to the index definition **before** -> deploying, or `/query` and `/query_multiple` will start returning errors. - -#### Create a `file_id` Index (recommended) - -We recommend creating a standard MongoDB index on `file_id` to keep lookups fast. After creating the collection, run the following once (via Atlas UI, Compass, or `mongosh`): - -```javascript -db.getCollection("").createIndex({ file_id: 1 }) -``` - -Replace `` with the same collection used by the RAG API. This ensures lookups remain fast even as the number of embedded documents grows. - - -### Proxy Configuration - -When using the RAG API with LibreChat and you need to configure proxy settings, you can set the `HTTP_PROXY` and `HTTPS_PROXY` environment variables in the [`docker-compose.override.yml`](https://www.librechat.ai/docs/configuration/docker_override) file (from the LibreChat repository): - -```yaml -rag_api: - environment: - - HTTP_PROXY= - - HTTPS_PROXY= -``` - -This configuration will ensure that all HTTP/HTTPS requests from the RAG API container are routed through your specified proxy server. - - -### Cloud Installation Settings: - -#### AWS: -Make sure your RDS Postgres instance adheres to this requirement: - -`The pgvector extension version 0.5.0 is available on database instances in Amazon RDS running PostgreSQL 15.4-R2 and higher, 14.9-R2 and higher, 13.12-R2 and higher, and 12.16-R2 and higher in all applicable AWS Regions, including the AWS GovCloud (US) Regions.` - -In order to setup RDS Postgres with RAG API, you can follow these steps: - -* Create a RDS Instance/Cluster using the provided [AWS Documentation](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CreateDBInstance.html). -* Login to the RDS Cluster using the Endpoint connection string from the RDS Console or from your IaC Solution output. -* The login is via the *Master User*. -* Create a dedicated database for rag_api: -``` create database rag_api;```. -* Create a dedicated user\role for that database: -``` create role rag;``` - -* Switch to the database you just created: ```\c rag_api``` -* Enable the Vector extension: ```create extension vector;``` -* Use the documentation provided above to set up the connection string to the RDS Postgres Instance\Cluster. - -Notes: - * Even though you're logging with a Master user, it doesn't have all the super user privileges, that's why we cannot use the command: ```create role x with superuser;``` - * If you do not enable the extension, rag_api service will throw an error that it cannot create the extension due to the note above. - -### Dev notes: - -#### Running Tests - -##### Prerequisites - -Install test dependencies: - -```bash -pip install -r test_requirements.txt -``` - -##### Running All Tests - -```bash -# Run all tests -pytest - -# Run with verbose output -pytest -v - -# Run with coverage (if pytest-cov is installed) -pytest --cov=app -``` - -##### Running Specific Test Files - -```bash -# Run batch processing unit tests -pytest tests/test_batch_processing.py -v - -# Run batch processing integration tests (memory optimization tests) -pytest tests/test_batch_processing_integration.py -v - -# Run main API tests -pytest tests/test_main.py -v -``` - -##### Running Tests by Category - -```bash -# Run only integration tests (marked with @pytest.mark.integration) -pytest -m integration -v - -# Skip integration tests -pytest -m "not integration" -v - -# Run only async tests -pytest -k "async" -v -``` - -##### Test Categories - -| Test File | Description | -|-----------|-------------| -| `test_batch_processing.py` | Unit tests for batch processing functions | -| `test_batch_processing_integration.py` | Memory optimization and integration tests | -| `test_main.py` | API endpoint tests | -| `test_config.py` | Configuration tests | -| `test_middleware.py` | Middleware tests | -| `test_models.py` | Model tests | - -##### Memory Optimization Tests - -The `test_batch_processing_integration.py` file includes tests that verify the memory optimization behavior: - -- **`test_memory_bounded_by_batch_size`**: Verifies that the number of documents in memory at any time is bounded by `EMBEDDING_BATCH_SIZE` -- **`test_memory_tracking_with_tracemalloc`**: Uses Python's `tracemalloc` to monitor memory usage during batch processing -- **`test_sync_memory_bounded_by_batch_size`**: Same verification for the synchronous code path - -Run memory tests specifically: - -```bash -pytest tests/test_batch_processing_integration.py::TestMemoryOptimization -v -pytest tests/test_batch_processing_integration.py::TestSyncBatchedMemory -v -``` - -#### Installing pre-commit formatter - -Run the following commands to install pre-commit formatter, which uses [black](https://github.com/psf/black) code formatter: - -```bash -pip install pre-commit -pre-commit install -``` - +# ID-based RAG FastAPI + +> ## About this fork +> +> This is a fork of [danny-avila/rag_api](https://github.com/danny-avila/rag_api), tailored for legal-office document workflows. It keeps full upstream compatibility (same API, same LibreChat integration) while changing how several document types are loaded and adding new ones. **Key differences from upstream:** +> +> - **Remote OCR via Mistral** — PDFs and standalone images (`.png`, `.jpg`, `.jpeg`, `.gif`, `.bmp`, `.tif`/`.tiff`, `.webp`) are OCR'd through the [Mistral OCR API](https://docs.mistral.ai/) instead of a bundled local OCR engine. Set `MISTRAL_API_KEY` to enable. Because OCR is remote, the local OCR/computer-vision stack (`rapidocr-onnxruntime`, `opencv`, `onnxruntime`) has been **removed**, which also makes the image considerably smaller. +> - **Richer DOCX text extraction** — `.docx` files routed to `/text` are converted with [pandoc](https://pandoc.org/), preserving tracked changes, comments, and (optionally) headers/footers. Tables are written as compact pipe tables and the Markdown is cleaned of extraction noise, so a bilingual contract laid out as one long table no longer extracts at several times its content size. Configurable via `DOCX_TEXT_USE_PANDOC`, `DOCX_TEXT_TRACK_CHANGES`, `DOCX_TEXT_INCLUDE_HEADERS_FOOTERS`, `DOCX_TEXT_TABLE_STYLE`, `DOCX_TEXT_CLEANUP`, `DOCX_TEXT_STRIP_HEADING_ANCHORS` and `DOCX_TEXT_DROP_TOC`. +> - **Email support** — `.eml` and `.msg` (Outlook) files are parsed, with sender/recipient/subject/date headers optionally prepended (`EMAIL_INCLUDE_HEADERS`). Bcc is never exposed. +> - **`.rtf` support** added. +> - **Legacy `.doc` is rejected** with a clear error asking the user to convert to `.docx` (the old binary format could not be loaded reliably). +> +> **Prebuilt image:** [`georgx22/rag_api_lite`](https://hub.docker.com/r/georgx22/rag_api_lite) on Docker Hub — the lite build (no local embedding stack; uses remote embeddings + remote Mistral OCR). + +## Overview +This project integrates Langchain with FastAPI in an Asynchronous, Scalable manner, providing a framework for document indexing and retrieval, using PostgreSQL/pgvector. + +Files are organized into embeddings by `file_id`. The primary use case is for integration with [LibreChat](https://librechat.ai), but this simple API can be used for any ID-based use case. + +The main reason to use the ID approach is to work with embeddings on a file-level. This makes for targeted queries when combined with file metadata stored in a database, such as is done by LibreChat. + +The API will evolve over time to employ different querying/re-ranking methods, embedding models, and vector stores. + +## Features +- **Document Management**: Methods for adding, retrieving, and deleting documents. +- **Vector Store**: Utilizes Langchain's vector store for efficient document retrieval. +- **Asynchronous Support**: Offers async operations for enhanced performance. + +## Retrieval scope + +Chunks are owned. Every route that reads or removes stored content resolves the +caller's owner set from the verified token and puts it into the store query +*before* ranking, so a chunk outside that set is never read into the process. +The owner set is built in one place — `app/scope.py` — rather than re-derived per +route. + +Before this release these routes addressed the store by caller-supplied +`file_id` alone, or authorized a whole result set from the first hit returned: + +- `GET /ids` listed every file id in the deployment. +- `POST /query_multiple` performed no authorization at all, so pairing it with + `GET /ids` disclosed the content of every file to any authenticated caller. +- `POST /query` authorized the whole result set from `documents[0]`, so any hit + behind the first was never checked. A `file_id` is chosen by whoever uploads, + so an attacker's own row ranking first authorized the rows behind it. +- `GET /documents`, `GET /documents/{id}/context` and `DELETE /documents` read or + deleted the chunks of any file id the caller could name. +- A chunk with no recorded `user_id` read as "belongs to everyone". +- On the synchronous store path, a failed ingestion rolled back by `file_id` + alone, so an upload under someone else's file id destroyed their chunks. The + async pgvector pipeline already scopes its rollback to the ingestion attempt. + +**What changes for callers.** A caller reads and deletes only what it owns. A +file id outside the caller's scope answers "not found" rather than "found but +refused", so none of these routes is an existence oracle. Chunks with no +`user_id` are owned by nobody and are no longer readable — if a deployment holds +such rows and still needs them, stamp an owner on them before upgrading: + +```sql +UPDATE langchain_pg_embedding +SET cmetadata = jsonb_set(cmetadata, '{user_id}', '""') +WHERE cmetadata->>'user_id' IS NULL; +``` + +**If this deployment ever ran without `JWT_SECRET`, check for `public` too.** With +no signing key configured there is no caller identity to record, so every chunk +written in that period is owned by the literal string `public`. Once a signing +key is set, callers arrive with their own ids and none of them owns `public`, so +that content stops being readable. Routes other than `/query` returned it to +everybody before this release, which is exactly the hole being closed — but if +the content is still wanted, give it a real owner first: + +```sql +-- inspect before rewriting: this is content nobody was ever identified as owning +SELECT count(*) FROM langchain_pg_embedding WHERE cmetadata->>'user_id' = 'public'; +``` + +Deployments that never set `JWT_SECRET` are unaffected: with no key configured +the read scope is `public` as well, so what was written is what is read. + +`atlas-mongo` deployments must add `user_id` to the vector search index first; +see [Use Atlas MongoDB as Vector Database](#use-atlas-mongodb-as-vector-database). + +**Deleting entity-owned files requires `entity_id`.** Chunks embedded under an +`entity_id` — an agent knowledge base, for instance — are owned by that entity +rather than by the uploading user, so `DELETE /documents` needs the same +`entity_id` that the upload used, as a query parameter alongside the JSON body of +file ids. A delete that omits it resolves to the caller's own scope, matches +nothing, and answers 404 with the chunks left in place. Because a 404 is +indistinguishable from "already deleted", a caller that treats it as success will +orphan those chunks silently. + +**Upgrade the client first.** Deploy order matters, in one direction only: + +- A client that sends `entity_id` against an *older* build is inert — the + parameter is simply undeclared there, so the request behaves exactly as before. +- An *older* client against this build orphans every agent knowledge-base file it + tries to delete. + +So upgrade the client first, or both together — never this service first. +LibreChat carries the matching change: it records the owner each embed was made +under and sends it on delete, with `npm run migrate:embed-owners` to backfill +files embedded before that. + +**`entity_id` is unchanged and still caller-asserted.** Agent knowledge bases are +owned by an agent id rather than a user id, so a caller reading one names it via +`entity_id`. That id now *widens* the owner set rather than replacing the +caller's identity — the caller's own scope always remains — but nothing in a +token minted today proves the caller may act for the entity it names. A caller +that knows another owner's id can still name it — on read, to reach that owner's +chunks, and on the ingestion routes, where `entity_id` is what gets stamped as the +owner, to write into that owner's namespace. Deployments exposing this API to +untrusted callers must continue to authorize entity access upstream. Closing this +requires the token to carry the entity authorization, which is a coordinated +change with the callers that mint those tokens and is tracked separately from +this release. + +## Setup + +### Getting Started + +- **Configure `.env` file based on [section below](#environment-variables)** +- **Setup pgvector database:** + - Run an existing PSQL/PGVector setup, or, + - Docker: `docker compose up` (also starts RAG API) + - or, use docker just for DB: `docker compose -f ./db-compose.yaml up` +- **Run API**: + - Docker: `docker compose up` (also starts PSQL/pgvector) + - or, use docker just for RAG API: `docker compose -f ./api-compose.yaml up` + - Local: + - Make sure to setup `DB_HOST` to the correct database hostname + - Run the following commands (preferably in a [virtual environment](https://realpython.com/python-virtual-environments-a-primer/)) +```bash +pip install -r requirements.txt +uvicorn main:app +``` + +### Clean Install (Local Development) + +To do a clean reinstall of all dependencies (e.g., after updating `requirements.txt`): + +```bash +# Remove existing virtual environment and recreate it +rm -rf venv +python3 -m venv venv +source venv/bin/activate +pip install -r requirements.txt +``` + +For the lite version (without sentence_transformers/huggingface): + +```bash +rm -rf venv +python3 -m venv venv +source venv/bin/activate +pip install -r requirements.lite.txt +``` + +For Docker, rebuild without cache: + +```bash +docker compose build --no-cache +``` + +### Environment Variables + +The following environment variables are required to run the application: + +- `RAG_OPENAI_API_KEY`: The API key for OpenAI API Embeddings (if using default settings). + - Note: `OPENAI_API_KEY` will work but `RAG_OPENAI_API_KEY` will override it in order to not conflict with LibreChat setting. +- `RAG_OPENAI_BASEURL`: (Optional) The base URL for your OpenAI API Embeddings +- `RAG_OPENAI_PROXY`: (Optional) Proxy for OpenAI API Embeddings + - Note: When using with LibreChat, you can also set `HTTP_PROXY` and `HTTPS_PROXY` environment variables in the `docker-compose.override.yml` file (see [Proxy Configuration](#proxy-configuration) section below) +- `VECTOR_DB_TYPE`: (Optional) select vector database type, default to `pgvector`. +- `POSTGRES_USE_UNIX_SOCKET`: (Optional) Set to "True" when connecting to the PostgreSQL database server with Unix Socket. +- `POSTGRES_DB`: (Optional) The name of the PostgreSQL database, used when `VECTOR_DB_TYPE=pgvector`. +- `POSTGRES_USER`: (Optional) The username for connecting to the PostgreSQL database. +- `POSTGRES_PASSWORD`: (Optional) The password for connecting to the PostgreSQL database. +- `DB_HOST`: (Optional) The hostname or IP address of the PostgreSQL database server. +- `DB_PORT`: (Optional) The port number of the PostgreSQL database server. +- `PGVECTOR_CREATE_EXTENSION`: (Optional) Set to "False" to skip the `CREATE EXTENSION IF NOT EXISTS vector` call on startup. Default is "True". Use this when the `vector` extension is already installed on a managed Postgres (e.g. RDS, Azure Database for PostgreSQL) and the application user is not a superuser. +- `PG_POOL_PRE_PING`: (Optional) Set to "False" to disable SQLAlchemy's pre-ping check. Default is "True". When enabled, the connection pool issues a lightweight `SELECT 1` before handing out a pooled connection, so stale connections dropped by a remote server or middlebox idle timeout are transparently replaced instead of surfacing as query errors. Recommended for any deployment that connects to a remote PostgreSQL instance (managed Postgres, connections that traverse a load balancer, etc.). +- `PG_POOL_RECYCLE`: (Optional) Maximum age in seconds of a pooled connection before it is recycled. Default is "-1" (disabled). Set to a positive value when the server enforces a hard idle or max-lifetime limit (e.g. "1800" for a 30-minute cap). +- `POSTGRES_SCHEMA`: (Optional) Prepend this schema to the Postgres `search_path` so langchain's pgvector tables live in (and are read from) it. Unset by default (uses the user's default schema, typically `public`). Useful when sharing a database with other services — create the schema out-of-band first (`CREATE SCHEMA IF NOT EXISTS ; GRANT USAGE, CREATE ON SCHEMA TO ;`); the RAG API will not create it for you and fails fast at startup if the schema is missing. `public` is always appended to the resulting search path so the `vector` data type stays resolvable when the extension was installed there (the common case). Multiple schemas may be supplied as a comma-separated list (e.g. `myapp,extensions`) when the `vector` extension lives in a non-`public` schema. +- `PGVECTOR_CREATE_LEGACY_INDEXES`: (Optional) Set to "True" to create the legacy `custom_id` and `cmetadata->>'file_id'` indexes on startup. Default is "False". +- `PGVECTOR_MIGRATE_CMETADATA_JSONB`: (Optional) Set to "True" to migrate `langchain_pg_embedding.cmetadata` from JSON to JSONB on startup. Default is "False". +- `PGVECTOR_CREATE_CMETADATA_GIN_INDEX`: (Optional) Set to "True" to create the `cmetadata` JSONB GIN index on startup. Default is "False". The index is created only when `cmetadata` is already JSONB; for a legacy JSON column, also enable `PGVECTOR_MIGRATE_CMETADATA_JSONB` or the index step is skipped. +- `RAG_HOST`: (Optional) The hostname or IP address where the API server will run. Defaults to "0.0.0.0" +- `RAG_PORT`: (Optional) The port number where the API server will run. Defaults to port 8000. +- `JWT_SECRET`: (Optional) The secret key used for verifying JWT tokens for requests. + - The secret is only used for verification. This basic approach assumes a signed JWT from elsewhere. + - Omit to run API without requiring authentication + +- `COLLECTION_NAME`: (Optional) The name of the collection in the vector store. Default value is "testcollection". +- `CHUNK_SIZE`: (Optional) The size of the chunks for text processing. Default value is "1500". +- `CHUNK_OVERLAP`: (Optional) The overlap between chunks during text processing. Default value is "100". +- `EMBEDDING_BATCH_SIZE`: (Optional) Number of document chunks to process per batch. Defaults to `500`; set to `0` to disable batching. Recommended value is `750` for `text-embedding-3-small`. +- `EMBEDDING_MAX_QUEUE_SIZE`: (Optional) Maximum number of batches to buffer in memory during async processing. Default value is "3". +- `PARALLEL_EXECUTION`: (Optional) Maximum number of async embedding/database insertion consumers to run per file when batching is enabled. Default value is "2". +- `RAG_DISTANCE_THRESHOLD`: (Optional, `VECTOR_DB_TYPE=pgvector` only) Drop results whose vector distance is greater than this value, after the top-`k` search. Unset by default (no filtering). Lower distance = more similar, so e.g. `0.5` keeps only hits with distance ≤ 0.5 and discards weaker matches. Useful for reducing downstream LLM token cost when the top-`k` call returns loosely-related chunks. Appropriate values depend on the embedding model and distance strategy — inspect your actual scores before choosing one. Ignored (with a startup warning) under `VECTOR_DB_TYPE=atlas-mongo`, because Atlas returns a similarity score (higher = better) with inverted semantics. +- `RAG_UPLOAD_DIR`: (Optional) The directory where uploaded files are stored. Default value is "./uploads/". +- `DOCX_TEXT_USE_PANDOC`: (Optional) Boolean. When "True" (default), `.docx` files sent to the `/text` endpoint are converted via **pandoc** so tracked changes and comments are preserved (output is Markdown). The embedding path always uses `Docx2txtLoader`. Pandoc only reads OOXML `.docx`; legacy binary `.doc` files are rejected with an error asking you to convert to `.docx`. Requires the `pandoc` binary (already installed in the provided Docker images). +- `DOCX_TEXT_TRACK_CHANGES`: (Optional) pandoc `--track-changes` mode for the `.docx` `/text` path: `all` (default; keep insertions/deletions, record each edit's author/date, and emit comments), `accept` (final text), or `reject` (original text). +- `DOCX_TEXT_INCLUDE_HEADERS_FOOTERS`: (Optional) Boolean. When "True" (default), `.docx` headers/footers (matter numbers, "PRIVILEGED & CONFIDENTIAL", "DRAFT", etc.) — which pandoc drops — are extracted via python-docx and prepended to the `/text` output. Headers/footers holding nothing but a page number ("4", "Page 4 of 10") are skipped. +- `DOCX_TEXT_TABLE_STYLE`: (Optional) `compact` (default) or `grid`. Pandoc's own Markdown writer pads every cell of every row out to the width of the longest line in its column; with `--wrap=none` a single long clause can therefore inflate a whole contract table many times over, most of the output being spaces and `+---+` rules. `compact` disables grid/multiline/simple tables, so pandoc writes unpadded pipe tables and falls back to an HTML `
` only for cells holding block content. On bilingual contract tables this cuts the extracted text by 55-82% with no loss of content, tracked changes included. Set `grid` to restore pandoc's default table output; pair it with `DOCX_TEXT_CLEANUP=False`, since grid tables encode their columns as character positions and a cleanup that shortens a row shifts its `|` delimiters off the `+---+` rule (the service warns at startup if you set one without the other); reproducing the pre-fix output byte for byte also needs `DOCX_TEXT_CLEANUP=False` and `DOCX_TEXT_STRIP_HEADING_ANCHORS=False`, which are independent settings. +- `DOCX_TEXT_CLEANUP`: (Optional) Boolean. When "True" (default), the extracted Markdown is stripped of noise that carries no content: table columns that are empty in every row, empty tracked-change spans (a deleted space still costs ~70 bytes of author/date metadata), runs of blank lines from Word spacer paragraphs, and invisible characters (NBSP, soft hyphen, zero-width). Tracked changes that carry text keep their author and date untouched, and comments are preserved. +- `DOCX_TEXT_STRIP_HEADING_ANCHORS`: (Optional) Boolean. When "True" (default), the anchors pandoc derives from Word bookmarks (`# Heading {#_Toc123456789}`) are omitted — they are Word-internal TOC/cross-reference ids, not document content. +- `DOCX_TEXT_DROP_TOC`: (Optional) Boolean. When "True", a Word-generated table of contents (the block of links to `#_Toc` bookmarks) is dropped from the extracted text. Defaults to "False", since in some documents the TOC is the only outline of the agreement. + +> **Upgrading:** these defaults change what `/text` returns for `.docx` files — tables come back as pipe tables (or an HTML `
` for cells holding block content) instead of padded grid tables, and the cleanup pass runs. Anything downstream that depends on the previous Markdown shape byte for byte — a prompt template keyed on grid tables, or a stored extraction being compared against a fresh one — sees different text. Set `DOCX_TEXT_TABLE_STYLE=grid`, `DOCX_TEXT_CLEANUP=False` and `DOCX_TEXT_STRIP_HEADING_ANCHORS=False` to keep the old output. +- `EMAIL_INCLUDE_HEADERS`: (Optional) Boolean. When "True" (default), the From/To/Cc/Subject/Date headers are prepended to extracted email text for `.eml` and `.msg` files. Set "False" to extract the body only. +- `MISTRAL_API_KEY`: (Optional) API key for Mistral OCR, used for PDFs and standalone images. OCR is unavailable without it. +- `MISTRAL_OCR_MODEL`: (Optional) Mistral OCR model. Default value is `mistral-ocr-latest`. +- `MISTRAL_SERVER_URL`: (Optional) Base URL of the Mistral API. Leave unset for the SDK default (`https://api.mistral.ai`); set `https://api.eu.mistral.ai` to keep OCR traffic on Mistral's [EU regional endpoint](https://docs.mistral.ai/inference/regional-inference). Regional endpoints don't offer the Files API, which is fine here: documents and images are sent inline as base64. Confirm with Mistral that your OCR model is served on the regional endpoint before relying on it. + - Note: LibreChat's own `mistral_ocr` strategy uploads through the Files API, so on an EU-only deployment route PDFs and images to this service's `/text` endpoint instead. + - For EU embeddings as well, point `RAG_OPENAI_BASEURL` at an EU OpenAI-compatible endpoint (e.g. `https://eu.openrouter.ai/api/v1`) with a non-OpenAI model such as `mistralai/mistral-embed-2312` (1024 dimensions), and set `RAG_CHECK_EMBEDDING_CTX_LENGTH=False`: with the check on, inputs are sent as OpenAI tiktoken token IDs, which non-OpenAI models don't accept. Switching embedding models requires re-indexing existing files (see `EMBEDDINGS_DIMENSIONS`). +- Standalone image uploads (`.png`, `.jpg/.jpeg`, `.gif`, `.bmp`, `.tif/.tiff`, `.webp`) — including multi-page TIFF — are run through **Mistral OCR**, yielding one result per page. Requires `MISTRAL_API_KEY` (same key used for PDF OCR). This is separate from PDF handling; images embedded inside PDFs are covered by `MISTRAL_OCR_EMBEDDED_IMAGES` below. +- `IMAGE_OCR_MAX_PAGES`: (Optional) Max number of frames/pages of a single image upload (e.g. animated GIF or large multi-page TIFF) sent to OCR; frames beyond the cap are skipped with a warning. Default value is `100`. +- `MISTRAL_OCR_EMBEDDED_IMAGES`: (Optional) Boolean. Mistral OCR returns only a placeholder (`![img-0.jpeg](img-0.jpeg)`) for a raster image embedded in a PDF page, such as a photo or scan of a page, and does not read the text inside it. When "True" (default), those images are extracted, OCR'd in a second Mistral call each, and the recognized text replaces the placeholder. **Each embedded image is billed as an extra OCR page**; set "False" to OCR only the PDF itself. If an image's OCR call fails, its placeholder is kept and the document still loads. +- `MISTRAL_OCR_IMAGE_MIN_SIZE`: (Optional) Minimum image size in pixels for an embedded image to be extracted, so logos and icons are skipped. Default value is `100`. +- `MISTRAL_OCR_MAX_EXTRACTED_IMAGES`: (Optional) Max number of embedded images Mistral extracts per document (minimum `1`), before any filtering; this bounds the size of the OCR response. A warning is logged when the document has more, and the later images are not extracted. Default value is `200`. +- `MISTRAL_OCR_MAX_EMBEDDED_IMAGES`: (Optional) Max number of distinct embedded images OCR'd per document (minimum `1`), i.e. the number of extra billed OCR calls. It is applied after the page-fraction filter and the removal of identical images, in page order; a warning is logged when the document has more, and the extra images are left as placeholders. Default value is `50`. +- `MISTRAL_OCR_IMAGE_MIN_PAGE_FRACTION`: (Optional) Embedded images covering less than this fraction of their page (`0` to `1`) are not OCR'd and keep their placeholder, so letterheads and logos repeated on every page cost nothing. Set to `0` to OCR every extracted image. Skipped images are logged at debug level. Identical images are always OCR'd only once per document. Default value is `0.1`. +- `MISTRAL_OCR_IMAGE_CONCURRENCY`: (Optional) Max number of embedded-image OCR calls in flight at once across all documents and requests (minimum `1`); it is also the parallelism within a single document. Default value is `4`. +- `DEBUG_RAG_API`: (Optional) Set to "True" to show more verbose logging output in the server console, and to enable postgresql database routes +- `DEBUG_PGVECTOR_QUERIES`: (Optional) Set to "True" to enable detailed PostgreSQL query logging for pgvector operations. Useful for debugging performance issues with vector database queries. +- `CONSOLE_JSON`: (Optional) Set to "True" to log as json for Cloud Logging aggregations +- `EMBEDDINGS_PROVIDER`: (Optional) either "openai", "bedrock", "azure", "huggingface", "huggingfacetei", "google_genai", "vertexai", or "ollama", where "huggingface" uses sentence_transformers; defaults to "openai" +- `EMBEDDINGS_MODEL`: (Optional) Set a valid embeddings model to use from the configured provider. + - **Defaults** + - openai: "text-embedding-3-small" + - azure: "text-embedding-3-small" (will be used as your Azure Deployment) + - huggingface: "sentence-transformers/all-MiniLM-L6-v2" + - huggingfacetei: "http://huggingfacetei:3000". Hugging Face TEI uses model defined on TEI service launch. + - vertexai: "gemini-embedding-001" + - ollama: "nomic-embed-text" + - bedrock: "amazon.titan-embed-text-v1" + - google_genai: "gemini-embedding-001" +- `EMBEDDINGS_CHUNK_SIZE`: (Optional) The chunk size used by the OpenAI and Azure embeddings clients to limit the number of inputs per request. Default value is `200`. +- `EMBEDDINGS_DIMENSIONS`: (Optional) Output vector size to request from the embedding model. Only honored by the `openai` and `azure` providers, and only supported by `text-embedding-3-*` models. Leave unset to use the model's native dimensionality (1536 for `text-embedding-3-small`, 3072 for `text-embedding-3-large`). Setting a smaller value (e.g. `512`, `1024`) trades some retrieval quality for lower storage cost and faster similarity search. Note: do not change this on an existing collection — all vectors in a `pgvector` column must share the same dimensionality. +- `RAG_AZURE_OPENAI_API_VERSION`: (Optional) Default is `2023-05-15`. The version of the Azure OpenAI API. +- `RAG_AZURE_OPENAI_API_KEY`: (Optional) The API key for Azure OpenAI service. + - Note: `AZURE_OPENAI_API_KEY` will work but `RAG_AZURE_OPENAI_API_KEY` will override it in order to not conflict with LibreChat setting. +- `RAG_AZURE_OPENAI_ENDPOINT`: (Optional) The endpoint URL for Azure OpenAI service, including the resource. + - Example: `https://YOUR_RESOURCE_NAME.openai.azure.com`. + - Note: `AZURE_OPENAI_ENDPOINT` will work but `RAG_AZURE_OPENAI_ENDPOINT` will override it in order to not conflict with LibreChat setting. +- `HF_TOKEN`: (Optional) if needed for `huggingface` option. +- `OLLAMA_BASE_URL`: (Optional) defaults to `http://ollama:11434`. +- `ATLAS_SEARCH_INDEX`: (Optional) the name of the vector search index if using Atlas MongoDB, defaults to `vector_index` +- `MONGO_VECTOR_COLLECTION`: Deprecated for MongoDB, please use `ATLAS_SEARCH_INDEX` and `COLLECTION_NAME` +- `AWS_DEFAULT_REGION`: (Optional) defaults to `us-east-1` +- `AWS_ACCESS_KEY_ID`: (Optional) needed for bedrock embeddings +- `AWS_SECRET_ACCESS_KEY`: (Optional) needed for bedrock embeddings +- `GOOGLE_API_KEY`, `GOOGLE_KEY`, `RAG_GOOGLE_API_KEY`: (Optional) Google API key for Google GenAI embeddings. Priority order: RAG_GOOGLE_API_KEY > GOOGLE_KEY > GOOGLE_API_KEY +- `AWS_SESSION_TOKEN`: (Optional) may be needed for bedrock embeddings +- `GOOGLE_APPLICATION_CREDENTIALS`: (Optional) needed for Google VertexAI embeddings. This should be a path to a service account credential file in JSON format. +- `GOOGLE_CLOUD_PROJECT`: (Optional) Google Cloud project ID, needed for VertexAI embeddings. +- `GOOGLE_CLOUD_LOCATION`: (Optional) Google Cloud region for VertexAI embeddings. Defaults to `us-central1`. +- `RAG_CHECK_EMBEDDING_CTX_LENGTH` (Optional) Default is true, disabling this will send raw input to the embedder, use this for custom embedding models. + +Make sure to set these environment variables before running the application. You can set them in a `.env` file or as system environment variables. + +### `/text` endpoint + +`POST /text` (multipart form: `file_id`, `file`, optional `entity_id`) extracts a file's text without embedding it and answers `{"text", "file_id", "filename", "known_type"}`. + +- **Per-page output:** send `pages=true` to also get `"pages": [{"page": 1, "text": "…"}, …]`, so callers can cite by page. Pages are 1-based and come from the loaders that have them: PDFs, standalone images, and multi-page TIFFs (one entry per frame). Each page's text is cleaned the same way as `text`, which is unchanged by the flag. Blank pages are **kept** with empty text, so the numbering has no gaps. For formats without pages (`.docx`, `.eml`, `.msg`, `.rtf`, `.xlsx`, `.pptx`, text files…), `pages` is `[]`; use `text`. Without the field the response has no `pages` key. +- **Status codes:** `400` means a problem with the file itself (unsupported, encrypted, corrupt, or rejected by Mistral as unreadable). Failures of the OCR service get their own codes, with the same `detail` message as before: + - `503`: transient, retry later. Mistral rate limits (429), timeouts (408) and server errors (5xx) left after the SDK's own retries, or Mistral unreachable or timing out. Mistral's `Retry-After` header is forwarded when it sends one. + - `502`: Mistral rejected this server's API key (401/403), or sent a response the SDK could not use. + - `500`: OCR is not configured on this server (`MISTRAL_API_KEY` unset). + +### Embedding Batch Processing + +For large files, you can enable batched embedding processing to reduce memory consumption. This is particularly useful in memory-constrained environments like Kubernetes pods with memory limits. + +#### Configuration + +| Variable | Default | Description | +|----------|---------|-------------| +| `EMBEDDING_BATCH_SIZE` | `500` | Number of document chunks to process per batch. `0` disables batching (original behavior). | +| `EMBEDDING_MAX_QUEUE_SIZE` | `3` | Maximum number of batches to buffer in memory during async processing. | +| `PARALLEL_EXECUTION` | `2` | Maximum number of async embedding/database insertion consumers per file when batching is enabled. | + +#### Recommended Settings + +For `text-embedding-3-small` model: +- `EMBEDDING_BATCH_SIZE=750` - Good balance of throughput and memory + +For memory-constrained environments (< 2GB RAM): +- `EMBEDDING_BATCH_SIZE=100-250` + +For high-throughput environments: +- `EMBEDDING_BATCH_SIZE=1000-2000` +- `EMBEDDING_MAX_QUEUE_SIZE=5` +- Increase `PARALLEL_EXECUTION` cautiously; it applies per active file upload. + +#### Behavior + +When `EMBEDDING_BATCH_SIZE > 0`: +- Documents are processed in batches of the specified size +- Up to `PARALLEL_EXECUTION` batches for the same file can be embedded and inserted concurrently +- `PARALLEL_EXECUTION` is per request/file. Total process concurrency can be roughly `active uploads * PARALLEL_EXECUTION`, bounded indirectly by `RAG_THREAD_POOL_SIZE` and downstream provider/database limits +- On failure, remaining batch work is stopped and successfully inserted documents are rolled back +- Memory usage is bounded by queued plus active batches, roughly `EMBEDDING_BATCH_SIZE * (EMBEDDING_MAX_QUEUE_SIZE + PARALLEL_EXECUTION)` +- Ingestion lifecycle logs include route, user, file, chunk count, file size, elapsed time, and selected process memory context. Per-batch queue/insert progress is logged at debug level + +When `EMBEDDING_BATCH_SIZE <= 0`: +- All documents are processed at once (original behavior) +- Better for small files or memory-rich environments + +### Use Atlas MongoDB as Vector Database + +Instead of using the default pgvector, we could use [Atlas MongoDB](https://www.mongodb.com/products/platform/atlas-vector-search) as the vector database. To do so, set the following environment variables + +```env +VECTOR_DB_TYPE=atlas-mongo +ATLAS_MONGO_DB_URI= +COLLECTION_NAME= +ATLAS_SEARCH_INDEX= +``` + +The `ATLAS_MONGO_DB_URI` could be the same or different from what is used by LibreChat. Even if it is the same, the `$COLLECTION_NAME` collection needs to be a completely new one, separate from all collections used by LibreChat. In addition, create a vector search index for collection above (remember to assign `$ATLAS_SEARCH_INDEX`) with the following json: + +```json +{ + "fields": [ + { + "numDimensions": 1536, + "path": "embedding", + "similarity": "cosine", + "type": "vector" + }, + { + "path": "file_id", + "type": "filter" + }, + { + "path": "user_id", + "type": "filter" + } + ] +} +``` + +Follow one of the [four documented methods](https://www.mongodb.com/docs/atlas/atlas-vector-search/create-index/#procedure) to create the vector index. + +> **Upgrading an existing Atlas deployment:** `user_id` is a required filter field +> as of the release described under [Retrieval scope](#retrieval-scope). Retrieval +> now filters on it, and Atlas Vector Search rejects a `$vectorSearch` pre-filter on +> a path the index does not declare — so add it to the index definition **before** +> deploying, or `/query` and `/query_multiple` will start returning errors. + +#### Create a `file_id` Index (recommended) + +We recommend creating a standard MongoDB index on `file_id` to keep lookups fast. After creating the collection, run the following once (via Atlas UI, Compass, or `mongosh`): + +```javascript +db.getCollection("").createIndex({ file_id: 1 }) +``` + +Replace `` with the same collection used by the RAG API. This ensures lookups remain fast even as the number of embedded documents grows. + + +### Proxy Configuration + +When using the RAG API with LibreChat and you need to configure proxy settings, you can set the `HTTP_PROXY` and `HTTPS_PROXY` environment variables in the [`docker-compose.override.yml`](https://www.librechat.ai/docs/configuration/docker_override) file (from the LibreChat repository): + +```yaml +rag_api: + environment: + - HTTP_PROXY= + - HTTPS_PROXY= +``` + +This configuration will ensure that all HTTP/HTTPS requests from the RAG API container are routed through your specified proxy server. + + +### Cloud Installation Settings: + +#### AWS: +Make sure your RDS Postgres instance adheres to this requirement: + +`The pgvector extension version 0.5.0 is available on database instances in Amazon RDS running PostgreSQL 15.4-R2 and higher, 14.9-R2 and higher, 13.12-R2 and higher, and 12.16-R2 and higher in all applicable AWS Regions, including the AWS GovCloud (US) Regions.` + +In order to setup RDS Postgres with RAG API, you can follow these steps: + +* Create a RDS Instance/Cluster using the provided [AWS Documentation](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CreateDBInstance.html). +* Login to the RDS Cluster using the Endpoint connection string from the RDS Console or from your IaC Solution output. +* The login is via the *Master User*. +* Create a dedicated database for rag_api: +``` create database rag_api;```. +* Create a dedicated user\role for that database: +``` create role rag;``` + +* Switch to the database you just created: ```\c rag_api``` +* Enable the Vector extension: ```create extension vector;``` +* Use the documentation provided above to set up the connection string to the RDS Postgres Instance\Cluster. + +Notes: + * Even though you're logging with a Master user, it doesn't have all the super user privileges, that's why we cannot use the command: ```create role x with superuser;``` + * If you do not enable the extension, rag_api service will throw an error that it cannot create the extension due to the note above. + +### Dev notes: + +#### Running Tests + +##### Prerequisites + +Install test dependencies: + +```bash +pip install -r test_requirements.txt +``` + +##### Running All Tests + +```bash +# Run all tests +pytest + +# Run with verbose output +pytest -v + +# Run with coverage (if pytest-cov is installed) +pytest --cov=app +``` + +##### Running Specific Test Files + +```bash +# Run batch processing unit tests +pytest tests/test_batch_processing.py -v + +# Run batch processing integration tests (memory optimization tests) +pytest tests/test_batch_processing_integration.py -v + +# Run main API tests +pytest tests/test_main.py -v +``` + +##### Running Tests by Category + +```bash +# Run only integration tests (marked with @pytest.mark.integration) +pytest -m integration -v + +# Skip integration tests +pytest -m "not integration" -v + +# Run only async tests +pytest -k "async" -v +``` + +##### Test Categories + +| Test File | Description | +|-----------|-------------| +| `test_batch_processing.py` | Unit tests for batch processing functions | +| `test_batch_processing_integration.py` | Memory optimization and integration tests | +| `test_main.py` | API endpoint tests | +| `test_config.py` | Configuration tests | +| `test_middleware.py` | Middleware tests | +| `test_models.py` | Model tests | + +##### Memory Optimization Tests + +The `test_batch_processing_integration.py` file includes tests that verify the memory optimization behavior: + +- **`test_memory_bounded_by_batch_size`**: Verifies that the number of documents in memory at any time is bounded by `EMBEDDING_BATCH_SIZE` +- **`test_memory_tracking_with_tracemalloc`**: Uses Python's `tracemalloc` to monitor memory usage during batch processing +- **`test_sync_memory_bounded_by_batch_size`**: Same verification for the synchronous code path + +Run memory tests specifically: + +```bash +pytest tests/test_batch_processing_integration.py::TestMemoryOptimization -v +pytest tests/test_batch_processing_integration.py::TestSyncBatchedMemory -v +``` + +#### Installing pre-commit formatter + +Run the following commands to install pre-commit formatter, which uses [black](https://github.com/psf/black) code formatter: + +```bash +pip install pre-commit +pre-commit install +``` + diff --git a/app/utils/document_loader.py b/app/utils/document_loader.py index e2bcf893..835fe1e2 100644 --- a/app/utils/document_loader.py +++ b/app/utils/document_loader.py @@ -324,12 +324,21 @@ class OCRNotConfiguredError(RuntimeError): def _exception_chain(exc: BaseException) -> Iterator[BaseException]: - """``exc`` and the exceptions it was raised from or during, outermost first.""" + """``exc`` and the exceptions it was raised from or during, outermost first. + + Follows the chain Python would print: ``__cause__``, else ``__context__`` + unless ``raise ... from None`` hid it. + """ seen = set() while exc is not None and id(exc) not in seen: seen.add(id(exc)) yield exc - exc = exc.__cause__ or exc.__context__ + if exc.__cause__ is not None: + exc = exc.__cause__ + elif not exc.__suppress_context__: + exc = exc.__context__ + else: + exc = None def _is_mistral_error(exc: BaseException) -> bool: @@ -348,11 +357,14 @@ def classify_ocr_failure(exc: BaseException) -> Optional[tuple]: (429), timeouts (408) and server errors (5xx) left after the SDK's own retries, no response, and network errors or timeouts reaching it. ``retry_after`` is Mistral's ``Retry-After`` header when it sent one. - - 502 when Mistral rejects this server's credentials (401/403). + - 502 when Mistral rejects this server's credentials (401/403), or sends + a response the SDK can't use (a non-error status, e.g. a 200 whose body + fails validation). - 500 when OCR isn't configured on this server (:class:`OCRNotConfiguredError`). Other Mistral 4xx responses (e.g. 400/422 for a document it can't read) - return None: they are about the file. + return None: they are about the file. So do Mistral-module errors that are + neither HTTP errors nor ``NoResponseError``. """ try: import httpx @@ -366,14 +378,16 @@ def classify_ocr_failure(exc: BaseException) -> Optional[tuple]: return 503, None # includes timeouts and connection errors if not _is_mistral_error(error): continue + if type(error).__name__ == "NoResponseError": + return 503, None # the request went out and nothing came back status_code = getattr(error, "status_code", None) - if status_code is None: - return 503, None # NoResponseError: nothing came back + if not isinstance(status_code, int): + return None if status_code in _TRANSIENT_UPSTREAM_STATUSES or status_code >= 500: headers = getattr(error, "headers", None) retry_after = headers.get("retry-after") if headers is not None else None return 503, retry_after - if status_code in (401, 403): + if status_code in (401, 403) or status_code < 400: return 502, None return None return None diff --git a/tests/test_text_pages.py b/tests/test_text_pages.py index 6a0012d6..b58b7a60 100644 --- a/tests/test_text_pages.py +++ b/tests/test_text_pages.py @@ -14,7 +14,7 @@ import jwt import pytest from fastapi.testclient import TestClient -from mistralai.client.errors import NoResponseError, SDKError +from mistralai.client.errors import NoResponseError, ResponseValidationError, SDKError from app.utils import document_loader from main import app @@ -238,3 +238,34 @@ def test_failure_wrapped_by_another_exception_is_still_classified(): raise RuntimeError("load failed") from inner except RuntimeError as outer: assert document_loader.classify_ocr_failure(outer) == (503, None) + + +def test_failure_hidden_with_from_none_is_not_classified(): + """``raise ... from None`` hides the context, so a file error isn't blamed on OCR.""" + try: + try: + raise _upstream_error(429) + except SDKError: + raise ValueError("file is corrupt") from None + except ValueError as outer: + assert document_loader.classify_ocr_failure(outer) is None + + +def test_unusable_upstream_response_answers_502(ocr, pdf_file, auth_headers): + """A 200 the SDK can't parse is Mistral's fault, not the file's.""" + response_200 = httpx.Response(200, request=httpx.Request("POST", "https://api.mistral.ai/v1/ocr")) + ocr.ocr.process.side_effect = ResponseValidationError( + "Response validation failed", response_200, ValueError("bad schema") + ) + + response = _post_text(pdf_file, "contract.pdf", "application/pdf", auth_headers) + + assert response.status_code == 502 + + +def test_mistral_error_without_status_is_not_transient(): + class LocalSDKFailure(Exception): + pass + + LocalSDKFailure.__module__ = "mistralai.client.utils" + assert document_loader.classify_ocr_failure(LocalSDKFailure("bad request payload")) is None