From f9aa02b0b03132e60e331400688a8e9592fa1968 Mon Sep 17 00:00:00 2001 From: Henrik-3 Date: Sat, 28 Nov 2026 23:36:38 +0100 Subject: [PATCH 1/2] [FEAT] - Read scanned PDFs and images in knowledge uploads with OCR --- AGENTS.md | 5 +- e2e/tests/knowledge-setup.spec.ts | 35 +++ e2e/tests/managed-knowledge.spec.ts | 30 ++ frontend/pages/settings/tools/knowledge.vue | 46 ++- frontend/types/generated/OcrMode.ts | 6 + frontend/types/generated/OcrSettings.ts | 15 + frontend/types/generated/OcrSetup.ts | 15 + frontend/types/generated/PriceRates.ts | 6 +- frontend/types/generated/PriceServiceTier.ts | 6 +- frontend/types/generated/PriceSheet.ts | 6 +- frontend/types/generated/PriceTier.ts | 6 +- frontend/types/generated/RagSetupResponse.ts | 3 +- .../types/generated/UpdateRagSetupRequest.ts | 7 +- frontend/utils/pricing.ts | 2 +- migrations/20251226000000_initial_schema.sql | 53 +++- src/main.rs | 3 +- src/routes/admin/rag.rs | 5 +- src/tests/attachments.rs | 6 +- src/tests/rag.rs | 92 +++++- src/types/budgets/ledger.rs | 3 + src/types/models/pricing.rs | 12 +- src/types/models/repository.rs | 12 + src/types/models/requests.rs | 2 +- src/types/rag/documents.rs | 15 +- src/types/rag/ingest.rs | 65 ++++- src/types/rag/mod.rs | 33 +++ src/types/rag/models.rs | 36 ++- src/types/rag/ocr.rs | 271 ++++++++++++++++++ src/types/rag/repository.rs | 26 +- src/types/rag/requests.rs | 29 +- src/types/rag/responses.rs | 12 +- src/utils/extract.rs | 129 +++++++-- 32 files changed, 933 insertions(+), 59 deletions(-) create mode 100644 frontend/types/generated/OcrMode.ts create mode 100644 frontend/types/generated/OcrSettings.ts create mode 100644 frontend/types/generated/OcrSetup.ts create mode 100644 src/types/rag/ocr.rs diff --git a/AGENTS.md b/AGENTS.md index 0fb2fe29..27b933c2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -65,7 +65,7 @@ - A tool that sends paid requests of its own reserves through `ToolContext.budget_ledger` like the image tool does (`imagegen::reserve_budget`, estimate from `image_tool_estimate`) and puts the reservation ID into the request metadata - Provider-reported cost: `providers.reported_cost` (`ProviderReportedCost`: unit `usd`, `currency` or `credits`, optional `source` path or `header:`) becomes Omniference's `ProviderEndpoint.reported_cost` in `ai::build_engine`, which emits the cost in USD; currencies use `exchange_rates`, refreshed from the ECB by `exchange_rate_job`, and a currency without a rate falls back to token pricing - Model prices (`ModelPricing`, `src/types/models/repository.rs`): the catalog price Omniference knows for the model's provider (models.dev plus catalog overrides, through `ai::catalog()`), with an optional manual override from `model_pricing_overrides` on top; endpoint rows in `gateway_model_provider_options` are display only. Manual prices are pushed into the engine's catalog keyed by provider name and model ID (`ai::build_engine` loads them all, `ModelPricing::push_to_engine` after every change), so Omniference prices every request itself and `OxideCostSink` stores its cost as is; `ModelPricing` estimates and fallback costs also go through Omniference's `compute_cost` at the current time, so context tiers and time windows apply to budget reservations - - Prices are `PriceSheet`s (`src/types/models/pricing.rs`): base rates, context `tiers`, `service_tiers` (`flex`, `priority`, ...) and time `windows` (days, `HH:MM` start and end, timezone); token rates are USD per million tokens, the unit rates `per_audio_second`, `per_character`, `per_request` and `per_search` USD per unit and count as charging for budgets; resolved by Omniference as base → context tier → service tier → window. An override is partial: every rate or list it leaves unset (missing or `null`) comes from the catalog, and an empty list replaces the catalog's with none. The merged price is pushed to the engine, so it is recomputed on every save and engine rebuild, not when Omniference refreshes models.dev + - Prices are `PriceSheet`s (`src/types/models/pricing.rs`): base rates, context `tiers`, `service_tiers` (`flex`, `priority`, ...) and time `windows` (days, `HH:MM` start and end, timezone); token rates are USD per million tokens, the unit rates `per_audio_second`, `per_character`, `per_request`, `per_search` and `per_page` USD per unit and count as charging for budgets; resolved by Omniference as base → context tier → service tier → window. An override is partial: every rate or list it leaves unset (missing or `null`) comes from the catalog, and an empty list replaces the catalog's with none. The merged price is pushed to the engine, so it is recomputed on every save and engine rebuild, not when Omniference refreshes models.dev - Overrides are saved through `ModelPricing::save_override` / `store_override` (validated by `PriceSheet::validate`, audited as `model_pricing_updated` / `_deleted`); refusals are `PriceSheetError`, rendered as `ValidationFailed` with `details.reason`, which the frontend translates as `pricing.error.` - The response carries `override_pricing` plus `catalog` and `effective` as `PricedSheet`s (`price` and its `PriceSummary`: input/output ranges and the special rates); the admin editor is `SettingsModelsPricingEditor`, prices and special rates are shown with `formatRange` and `PricingSpecialRates` (`frontend/utils/pricing.ts`), and the Developer models list returns the same summary as `price` - `src/types/provider_routing/` - Upstream provider routing for provider kinds that route on to upstream providers (`ProviderKind::UPSTREAM_ROUTING`, `routes_upstream()`: `OPENROUTER` and `CORTECS`). The installation (`provider_routing: {selector_enabled, allowed_providers}` in `/api/v1/base` and the admin PATCH) and each team (`teams.provider_selector_enabled`, `teams.allowed_upstream_providers`) set whether users get the chat provider selector and which upstream providers requests may reach; `EffectiveProviderRouting::combine` intersects the allowlists and lets a team's "off" win. `ProviderRoutingMiddleware`, registered on the engine in `ai::build_engine`, restricts every request's `ChatRequestIR::provider_routing` to that allowlist (gateway: the key's team; web chat and titles: all of the user's teams) and refuses others with a 403 @@ -74,7 +74,7 @@ - To add a routing provider (e.g. Vercel): add its kind to `UPSTREAM_ROUTING`, map `ProviderRouting` in its Omniference adapter or vendor dialect, and add a `sync` function in `sources/` called from `sources::sync` - Cortecs (`CortecsDialect` in Omniference, Responses adapter): `only` becomes `allowed_providers`, `order` becomes `allowed_providers` with `provider_order: "custom"`, and Cortecs never falls back beyond that list, so web chat's "prefer" puts the model's other stored providers the user may use after the picked one (`picked_provider`); "lock" stays `only: [slug]`. Its catalog and every model's provider options come from one `/v1/models?extended=true` call in the model sync (`sync_cortecs_catalog`, `source_gateway = 'cortecs'`, `cortecs_options`, written in one transaction by `GatewayCatalogModel::replace_gateway_provider_options`); the provider-options refresh re-runs that sync. Cortecs reports EUR per 1M tokens (converted to USD with `exchange_rates`, left empty without a rate), latency in seconds (stored as ms) and uptime as a fraction (stored as percent); `ttft` and `cache_hit_rate` stay in `raw`. The admin Catalog tab stays OpenRouter-only - Provider kinds without their own Omniference adapter pass `ProviderKind::catalog_slug()` as `catalog_provider_slug`, the vendor slug Omniference uses for models.dev prices and its vendor profile (`catalog/providers/.toml`); every `ProviderConfig` OxideChat builds must set it (`profile` and `resolved_profile` stay `None`: registration resolves the profile). `MISTRAL` uses the OpenAI-compatible Chat adapter (`/v1/chat/completions`), where Omniference's `MistralDialect` applies; `CORTECS` uses the OpenAI Responses adapter (`/v1/responses`) -- `src/types/rag/` - Knowledge (RAG, HEN-22, built as stacked PRs; slices 1, 2a, 2b, 2c, 2d and 4): `rag_config` (single row: reranker model, `top_n` and optional `min_score`, default managed connection, chunking defaults `chunk_size`/`chunk_overlap_percent`; knowledge uploads have no quotas of their own and count toward the shared file limits) and `rag_connections` (where vectors live), managed under `/api/v1/admin/rag` (`admin.rag.view` / `.edit`, page `/settings/tools/knowledge`, a sub page of Tools; `/settings/knowledge-setup` redirects there); knowledge is on while the Knowledge Search builtin tool row is enabled (`RagConfig::enabled`, `Tool::builtin_enabled`), there is no separate switch, and `/api/v1/base` returns that as `rag: {enabled}` +- `src/types/rag/` - Knowledge (RAG, HEN-22, built as stacked PRs; slices 1, 2a, 2b, 2c, 2d, 4 and 5b): `rag_config` (single row: reranker model, `top_n` and optional `min_score`, default managed connection, chunking defaults `chunk_size`/`chunk_overlap_percent`; knowledge uploads have no quotas of their own and count toward the shared file limits) and `rag_connections` (where vectors live), managed under `/api/v1/admin/rag` (`admin.rag.view` / `.edit`, page `/settings/tools/knowledge`, a sub page of Tools; `/settings/knowledge-setup` redirects there); knowledge is on while the Knowledge Search builtin tool row is enabled (`RagConfig::enabled`, `Tool::builtin_enabled`), there is no separate switch, and `/api/v1/base` returns that as `rag: {enabled}` - A connection has a `kind` (`pgvector`, `qdrant`) and a `mode` (`managed`: `OxideChat` writes, pgvector only; `read_only`: another pipeline fills it), both fixed at create. Its URL never holds a password, and a pgvector URL takes no query parameter but `sslmode` and no percent-encoded host (sqlx would read host, port, socket and key files from them past the host checks): the Postgres password or Qdrant API key is the encrypted `secret`, a new host needs it again (`RagConnection::redirects_secret`), and Qdrant keys go over https only. A managed pgvector connection without URL is the main database; `RAG_PGVECTOR_URL` replaces the address and password of the default managed connection; the first managed connection saved while no default is set becomes the default storage (`make_default_if_none`), and the add dialog (`SettingsKnowledgeConnectionsCard`) asks what to connect (OxideChat's own database, another PostgreSQL server, or an existing collection) and only then shows address and password - A managed connection's embedding model is checked with one test embedding billed to the saving admin (`probe_embedding`, `oxide_request_type = rag_setup`), which stores `vector_size`; a new model or size bumps `index_generation`. Reranker and embedding models are checked with `gateway::model_type`, and the admin model list takes `?type=embedding|reranking` for the pickers - `VectorStore` (`store.rs`) opens a connection for `health` (pgvector 0.8+ or the Qdrant version), `list_collections`, `describe` (vectors with size and distance, payload field paths, three sample records without vectors and with strings cut by `shorten`) and `search` (nearest records as payload and score, inside the view's fixed filter); addresses follow the outbound rules (`private_hosts_allowed`), read-only Postgres sessions set `default_transaction_read_only`, external pgvector pools are reused per address, secret and mode (`PG_POOLS`, an `ArcSwap` map; the host check still runs on every connect and idle connections close after a minute), and failures are `StoreError` codes (`rag.store_error.`), never the server's own text. Validation failures are `RagError`, rendered as `ValidationFailed` with `details.reason` (`rag.error.`) @@ -86,6 +86,7 @@ - Connect flow: `POST /api/v1/admin/rag/connections/{id}/inspect` (`admin.rag.edit`) returns `InspectResponse` (`error` or `collection: CollectionInfo`) for a collection and filter, checked like a saved view (`InspectRequest::validate`); the editor is `SettingsKnowledgeEditor` with `SettingsKnowledgeSourceForm` (steps: connection, collection, sample, fields, filter, embedding model, who may see what), `SettingsKnowledgeSharing` and `SettingsKnowledgeTestSearch`. The e2e stand-in serves a read-only Qdrant under `${MOCK_LLM_URL}/qdrant` (`handbook` with mock-embed's 3 dimensions, `wide` with 4, `intranet` whose records list `oxide_access` labels; it answers `match.any` and `facet`) - Managed knowledge bases (slice 4, `chunker.rs`, `documents.rs`, `ingest.rs`, `src/utils/extract.rs`, `rag_documents` / `rag_chunks`): a managed knowledge base has `view = NULL`, binds to the default managed pgvector connection (`rag_config.default_connection_id`), carries a `scope` (`personal` with `settings.knowledge.edit`, `team` for team admins, `installation` for `admin.rag.edit`, `GET /api/v1/knowledge-bases/scopes`), a PostgreSQL `search_language` (`regconfig`, validated against `SEARCH_LANGUAGES`), and soft deletion (`deleted_at`); `rag_documents.knowledge_base_id` uses `ON DELETE RESTRICT` so vectors are never cascaded away, and `User::delete` marks personal KB documents `deleting` (and soft-deletes non-empty personal KBs) inside its transaction and notifies `JobState.rag_ingest_notify` - Upload & ingest: `POST /api/v1/knowledge-bases/{id}/documents?filename=…` (25 MiB limit) checks `DocumentKind::detect` (text/code, HTML, PDF with `%PDF-`), the shared hourly upload limit and storage quota through `FileStorage::begin_store` (`RagError::RateLimited`, `RagError::StorageQuotaExceeded`), and KB model access against the connection's embedding model; it stores the file as a `files` row (`source = 'knowledge'`, `KNOWLEDGE_SOURCE`; name, type, size, original bytes in `data` and, once extracted, `text`) that the `rag_documents` row points to (`file_id`, `ON DELETE RESTRICT`; the worker deletes both after purging vectors), as `status = 'pending'` and notifies `rag_ingest_notify`. Two `rag_ingest_worker` background tasks (`src/jobs.rs`) claim jobs via `FOR UPDATE SKIP LOCKED`, extract HTML/PDF/text in a sandboxed child process (`OxideChat extract`, handled in plain `fn main()` before Tokio starts, 4 concurrent children, empty env, 30 s, 1 GiB `RLIMIT_AS` on Linux, 8 MiB text cap, PDF pages marked ``), chunk with `chunk_document` (heading hierarchy, ~15% overlap, no cross-section overlap on `#`/`##`, split Markdown tables repeat header + separator row, `doc › heading` embed prefix, SHA-256 `content_hash`), batch-embed (`embed_batch`, <=64 inputs / ~16k tokens, 2 in flight, billed as `rag_ingest`), and write L2-normalized vectors into per-connection per-generation pgvector tables `rag_vectors__g` (`halfvec(N)` + HNSW `halfvec_cosine_ops` + GIN `access`); extracted text replaces the kept bytes only if it fits the uploader's storage quota (`FileStorage::begin_extracted`, else `quota_exceeded`), failed uploads keep `files.data` for 7 days for `POST …/retry`, a claim is the row's `locked_at`, which every later write of that worker must still match (a re-queued or reaped document makes the old worker's writes no-ops), a worker touches `updated_at` every minute while it works and a document untouched for 10 min is queued again, a panic fails only its document, `#` lines are headings only in Markdown, text and HTML files (`has_headings`), and `deleting` rows purge vectors before removing Postgres rows and finished soft-deleted KBs; `Team::delete` hands a team's knowledge bases to the same path (`KnowledgeBase::delete_team_owned`), viewers list only the documents their labels grant (`RagDocument::visible_to`), `GET …/documents/{doc_id}/text` returns a document's extracted text under the same rule (`RagDocument::text`, the eye button in `SettingsKnowledgeDocuments`), document lists and text need `KnowledgeActor::can_search` or edit rights (`admin.rag.view` alone sees bases, not their documents), and a managed connection's address cannot change while documents are stored on it (`ConnectionHasDocuments`) + - Document reading (slice 5b, `ocr.rs`): `rag_config.ocr_mode` (`off`, `fallback`, `always`), `ocr_model_id` and `ocr_system_prompt` (`NULL` uses `DEFAULT_OCR_PROMPT`), in the setup request and response as `ocr: {mode, model_id, system_prompt}` (the response adds `default_system_prompt`; `check_ocr_model` accepts an Omniference `ocr` model or a chat model with `IMAGE` input, and the admin model list takes `?type=document_reader` for the picker). `OcrPlan::load` returns the reader only while OCR is on and the knowledge base's model restriction allows its model outright, else OCR is skipped. The worker reads images (PNG, JPEG, WebP, GIF, accepted on upload only while `OcrPlan::load` finds a reader, else `ocr_unavailable`) and, for PDFs, the pages `pages_to_read` picks (`always`: every page; `fallback`: pages with fewer than 32 visible characters; none for a chat model without `FILE` input): OCR models get the whole PDF with zero-based `pages` through `engine.ocr()`; chat models get sub-PDFs of 10 pages cut in the extraction child (`extract::pdf_subset`, `pdf-pages` subcommand) with the system prompt at temperature 0, a batch cut off at the length limit is split in half once, and `` markers in the reply assign the text to pages (`assign_pages`). Every request is reserved against the uploader's budget as `rag_ocr` (`UnitEstimate.pages` priced by `per_page`); a failed read keeps the PDF's own text and fails the document only when nothing is left. PDF extraction always marks every page, and `extract::checked_text` refuses text that is only page markers - Hybrid search, per-document access & re-indexing: `hybrid_search_managed` runs pgvector cosine search (`SET LOCAL hnsw.iterative_scan = relaxed_order`) alongside time-limited Postgres FTS (`websearch_to_tsquery`, 1.5 s timeout), re-checks `d.status = 'ready'` and `access` fail-closed in Postgres, and merges with RRF; per-document "Limit access" uses `GET/PUT …/documents/{doc_id}/assignments` (`team:`, `role:`, `user:` stored on `rag_documents.access`, `rag_chunks.access`, and pgvector `access`; empty clears back to `NULL` inheriting the KB). Changing a managed connection's embedding model checks KB model-access conflicts (`ConnectionModelConflict`), exposes `POST /api/v1/admin/rag/connections/{id}/reindex-estimate`, bumps `index_generation`, marks documents `pending` with `reindex_by`, blocks search with `StoreError::Reindexing` while documents are still `pending` or `processing` behind it (failed ones do not block), and drops generation tables older than the current one once those finish. Frontend adds `SettingsKnowledgeDocuments`, scope/language controls in `Editor.vue`, Mine / Shared with me / All tabs on `/settings/knowledge`, chunking settings and re-index confirmation/progress on `/settings/tools/knowledge`, and page badges on `ToolExecutionDisplay` - `src/types/presets/` - Presets (`model_presets`): a base model plus instructions, sampling (`PresetSampling`), reasoning, tools (optionally locked) and up to four starters, addressed as `presets/` - The slug is unique across all scopes, and `presets/` is a reserved namespace: providers cannot be named `presets` and model sync skips IDs starting with `presets/` (both also enforced by CHECK constraints) diff --git a/e2e/tests/knowledge-setup.spec.ts b/e2e/tests/knowledge-setup.spec.ts index 68e14cf8..19765e7e 100644 --- a/e2e/tests/knowledge-setup.spec.ts +++ b/e2e/tests/knowledge-setup.spec.ts @@ -2,6 +2,7 @@ import type {Page} from '@playwright/test'; import {test, expect, type Api} from './support/fixtures'; import {uniqueName} from './support/gateway'; import {MOCK_LLM_KEY, MOCK_LLM_URL} from './support/constants'; +import {createSyncedProvider} from './support/providers'; const MANAGED = 'E2E main store'; const QDRANT = 'E2E qdrant'; @@ -135,6 +136,40 @@ test.describe('knowledge setup', () => { } }); + test('document reading is set up through the save bar', async ({page, api, t}) => { + const {providerId, model} = await createSyncedProvider(api, uniqueName('Reader')); + try { + await api.patch(`/api/v1/admin/models/${model.id}`, {input_modalities: ['TEXT', 'IMAGE']}); + await page.goto('/settings/tools/knowledge'); + await expect(page.getByTestId('knowledge-ocr-prompt')).toBeHidden(); + await page.getByTestId('knowledge-ocr-mode').click(); + await page.getByTestId('knowledge-ocr-mode-fallback').click(); + + const listRequest = page.waitForRequest(request => /\/api\/v1\/admin\/models\?/.test(request.url())); + await page.getByRole('button', {name: t('settings.knowledge_setup.ocr_model_none')}).click(); + expect(new URL((await listRequest).url()).searchParams.get('type')).toBe('document_reader'); + await page.getByPlaceholder(t('chat.model_selector.search_models')).fill(model.displayName); + await page.getByText(model.displayName, {exact: true}).last().click(); + + const prompt = page.getByTestId('knowledge-ocr-prompt'); + await expect(prompt).toHaveValue(//); + await expect(page.getByTestId('knowledge-ocr-prompt-reset')).toBeHidden(); + await prompt.fill('Transcribe every word.'); + await page.getByTestId('settings-save-bar-save').click(); + await expect(page.getByTestId('settings-save-bar')).toBeHidden(); + expect((await api.get('/api/v1/admin/rag')).ocr).toMatchObject({mode: 'fallback', model_id: model.id, system_prompt: 'Transcribe every word.'}); + + await page.getByTestId('knowledge-ocr-prompt-reset').click(); + await expect(prompt).toHaveValue(//); + await page.getByTestId('settings-save-bar-save').click(); + await expect(page.getByTestId('settings-save-bar')).toBeHidden(); + expect((await api.get('/api/v1/admin/rag')).ocr).toMatchObject({mode: 'fallback', system_prompt: null}); + } finally { + await api.put('/api/v1/admin/rag', {reranker: {model_id: null, top_n: 6}, defaults: {connection_id: null}, ocr: {mode: 'off', model_id: null}}); + await api.delete(`/api/v1/admin/providers/${providerId}`); + } + }); + test('the old setup address leads to the page under Tools', async ({page}) => { await page.goto('/settings/knowledge-setup'); await expect(page).toHaveURL(/\/settings\/tools\/knowledge$/); diff --git a/e2e/tests/managed-knowledge.spec.ts b/e2e/tests/managed-knowledge.spec.ts index ffa3ef3c..9d0e5ecc 100644 --- a/e2e/tests/managed-knowledge.spec.ts +++ b/e2e/tests/managed-knowledge.spec.ts @@ -1,6 +1,9 @@ import {test, expect, Api} from './support/fixtures'; import {uniqueName} from './support/gateway'; import {AUTH_FILES, LLM, MEMBER, MOCK_LLM_KEY, MOCK_LLM_URL} from './support/constants'; +import {createSyncedProvider} from './support/providers'; + +const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64'); const CONNECTION = 'E2E managed pgvector'; const BASE = 'E2E managed handbook'; @@ -113,6 +116,33 @@ test.describe('managed knowledge bases', () => { await expect(hits.first()).toContainText('Rail tickets are booked through the internal travel desk'); }); + test('images are refused without document reading and read by its model once it is set up', async ({page, api, t, allowErrors}) => { + test.skip(!pgvectorReady || !baseId || !LLM.isMock, 'requires an indexed managed base and the local mock LLM'); + allowErrors(/400/); + const scan = {name: 'scan.png', mimeType: 'image/png', buffer: PNG}; + const settings = {reranker: {model_id: null, top_n: 6}, defaults: {connection_id: connectionId}, chunking: {chunk_size: 400, overlap_percent: 15}}; + + await page.goto(`/settings/knowledge/${baseId}?tab=documents`); + await page.getByTestId('knowledge-documents-input').setInputFiles(scan); + await expect(page.getByText(t('rag.error.ocr_unavailable'))).toBeVisible(); + + const {providerId, model} = await createSyncedProvider(api, uniqueName('Reader')); + try { + await api.patch(`/api/v1/admin/models/${model.id}`, {input_modalities: ['TEXT', 'IMAGE']}); + await api.put('/api/v1/admin/rag', {...settings, ocr: {mode: 'fallback', model_id: model.id}}); + await page.getByTestId('knowledge-documents-input').setInputFiles(scan); + await expect(page.getByTestId('knowledge-document-status-scan.png')).toContainText(t('knowledge.documents.status.ready'), {timeout: 30_000}); + await page.getByTestId('knowledge-document-text-scan.png').click(); + await expect(page.getByTestId('knowledge-document-text')).toContainText('Mock reply: Transcribe this image.'); + await page.keyboard.press('Escape'); + } finally { + const docs: {id: string; filename: string}[] = await api.get(`/api/v1/knowledge-bases/${baseId}/documents`); + for (const doc of docs.filter(item => item.filename === scan.name)) await api.delete(`/api/v1/knowledge-bases/${baseId}/documents/${doc.id}`); + await api.put('/api/v1/admin/rag', {...settings, ocr: {mode: 'off', model_id: null}}); + await api.delete(`/api/v1/admin/providers/${providerId}`); + } + }); + test('per-document limit access hides restricted documents from other users', async ({page, browser, baseURL}) => { test.skip(!pgvectorReady || !baseId, 'requires indexed managed base'); diff --git a/frontend/pages/settings/tools/knowledge.vue b/frontend/pages/settings/tools/knowledge.vue index 1b2ead0d..9d85c661 100644 --- a/frontend/pages/settings/tools/knowledge.vue +++ b/frontend/pages/settings/tools/knowledge.vue @@ -56,6 +56,40 @@ +
+

{{ store.getTranslation('settings.knowledge_setup.ocr_title') }}

+

{{ store.getTranslation('settings.knowledge_setup.ocr_description') }}

+ + + + + + + {{ store.getTranslation(`settings.knowledge_setup.ocr_mode_option.${mode}`) }} + + + + +
+

{{ store.getTranslation('settings.knowledge_setup.steps.title') }}

    @@ -74,10 +108,12 @@ import {ArrowLeft} from 'lucide-vue-next'; import {computed, onBeforeUnmount, onMounted, reactive, ref, watch} from 'vue'; import {useMainStore} from '@/stores'; import DefaultModelPicker from '~/components/settings/DefaultModelPicker.vue'; +import type {OcrMode} from '~/types/generated/OcrMode'; import type {RagSetupResponse} from '~/types/generated/RagSetupResponse'; const NONE = 'none'; -const SECTIONS = ['reranker', 'defaults', 'chunking'] as const; +const SECTIONS = ['reranker', 'defaults', 'chunking', 'ocr'] as const; +const OCR_MODES = ['off', 'fallback', 'always'] as const; const store = useMainStore(); const canEdit = computed(() => store.hasPermission(ADMIN_RAG_EDIT)); @@ -87,6 +123,12 @@ const form = reactive({ reranker: {model_id: null as string | null, top_n: 6, min_score: null as number | null}, defaults: {connection_id: null as string | null}, chunking: {chunk_size: 400, overlap_percent: 15}, + ocr: {mode: 'off' as OcrMode, model_id: null as string | null, system_prompt: null as string | null}, +}); + +const ocrPrompt = computed({ + get: () => form.ocr.system_prompt ?? setup.value?.ocr.default_system_prompt ?? '', + set: (value: string) => (form.ocr.system_prompt = value === setup.value?.ocr.default_system_prompt ? null : value), }); const minScore = computed({ @@ -107,6 +149,7 @@ function fill(value: RagSetupResponse) { form.reranker = {...value.reranker}; form.defaults = {...value.defaults}; form.chunking = {...value.chunking}; + form.ocr = {mode: value.ocr.mode, model_id: value.ocr.model_id, system_prompt: value.ocr.system_prompt ?? null}; } function apply(value: RagSetupResponse) { @@ -138,6 +181,7 @@ const settingsForm = useSettingsForm({ if (form.reranker.min_score !== null && !Number.isFinite(form.reranker.min_score)) return 'rag.error.invalid_min_score'; if (!Number.isInteger(form.chunking.chunk_size) || form.chunking.chunk_size < 100 || form.chunking.chunk_size > 2000) return 'rag.error.invalid_chunking'; if (!Number.isInteger(form.chunking.overlap_percent) || form.chunking.overlap_percent < 0 || form.chunking.overlap_percent > 50) return 'rag.error.invalid_chunking'; + if (form.ocr.mode !== 'off' && !form.ocr.model_id) return 'rag.error.ocr_model_required'; return null; }, save: async () => { diff --git a/frontend/types/generated/OcrMode.ts b/frontend/types/generated/OcrMode.ts new file mode 100644 index 00000000..d35fe881 --- /dev/null +++ b/frontend/types/generated/OcrMode.ts @@ -0,0 +1,6 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * When uploads are read by the OCR model: never, only for PDF pages without text (and images), or for every PDF page. + */ +export type OcrMode = "off" | "fallback" | "always"; diff --git a/frontend/types/generated/OcrSettings.ts b/frontend/types/generated/OcrSettings.ts new file mode 100644 index 00000000..2b3398f9 --- /dev/null +++ b/frontend/types/generated/OcrSettings.ts @@ -0,0 +1,15 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { OcrMode } from "./OcrMode"; + +/** + * Document reading (OCR) for knowledge uploads. + */ +export type OcrSettings = { mode: OcrMode, +/** + * An OCR model, or a chat model that takes images (and PDFs, for PDF pages). + */ +model_id: string | null, +/** + * Instructions for chat models; `None` uses the default ones. OCR models take none. + */ +system_prompt: string | null, }; diff --git a/frontend/types/generated/OcrSetup.ts b/frontend/types/generated/OcrSetup.ts new file mode 100644 index 00000000..0598d020 --- /dev/null +++ b/frontend/types/generated/OcrSetup.ts @@ -0,0 +1,15 @@ +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. +import type { OcrMode } from "./OcrMode"; + +/** + * Document reading settings with the instructions "Reset to default" restores. + */ +export type OcrSetup = { default_system_prompt: string, mode: OcrMode, +/** + * An OCR model, or a chat model that takes images (and PDFs, for PDF pages). + */ +model_id: string | null, +/** + * Instructions for chat models; `None` uses the default ones. OCR models take none. + */ +system_prompt: string | null, }; diff --git a/frontend/types/generated/PriceRates.ts b/frontend/types/generated/PriceRates.ts index 6b3e7dd6..17a0e5ac 100644 --- a/frontend/types/generated/PriceRates.ts +++ b/frontend/types/generated/PriceRates.ts @@ -20,4 +20,8 @@ per_request?: number, /** * USD per search (rerank). */ -per_search?: number, }; +per_search?: number, +/** + * USD per document page read (OCR). + */ +per_page?: number, }; diff --git a/frontend/types/generated/PriceServiceTier.ts b/frontend/types/generated/PriceServiceTier.ts index 95e7ffb2..da2a9939 100644 --- a/frontend/types/generated/PriceServiceTier.ts +++ b/frontend/types/generated/PriceServiceTier.ts @@ -20,4 +20,8 @@ per_request?: number, /** * USD per search (rerank). */ -per_search?: number, }; +per_search?: number, +/** + * USD per document page read (OCR). + */ +per_page?: number, }; diff --git a/frontend/types/generated/PriceSheet.ts b/frontend/types/generated/PriceSheet.ts index 1e869f2d..18b68451 100644 --- a/frontend/types/generated/PriceSheet.ts +++ b/frontend/types/generated/PriceSheet.ts @@ -23,4 +23,8 @@ per_request?: number, /** * USD per search (rerank). */ -per_search?: number, }; +per_search?: number, +/** + * USD per document page read (OCR). + */ +per_page?: number, }; diff --git a/frontend/types/generated/PriceTier.ts b/frontend/types/generated/PriceTier.ts index 22eca65f..4b014fff 100644 --- a/frontend/types/generated/PriceTier.ts +++ b/frontend/types/generated/PriceTier.ts @@ -19,4 +19,8 @@ per_request?: number, /** * USD per search (rerank). */ -per_search?: number, }; +per_search?: number, +/** + * USD per document page read (OCR). + */ +per_page?: number, }; diff --git a/frontend/types/generated/RagSetupResponse.ts b/frontend/types/generated/RagSetupResponse.ts index f60ee612..2b034343 100644 --- a/frontend/types/generated/RagSetupResponse.ts +++ b/frontend/types/generated/RagSetupResponse.ts @@ -1,10 +1,11 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { ChunkingSettings } from "./ChunkingSettings"; import type { ConnectionResponse } from "./ConnectionResponse"; +import type { OcrSetup } from "./OcrSetup"; import type { RagDefaults } from "./RagDefaults"; import type { RerankerSettings } from "./RerankerSettings"; /** * Everything the knowledge setup page shows. */ -export type RagSetupResponse = { connections: Array, reranker: RerankerSettings, defaults: RagDefaults, chunking: ChunkingSettings, }; +export type RagSetupResponse = { connections: Array, reranker: RerankerSettings, defaults: RagDefaults, chunking: ChunkingSettings, ocr: OcrSetup, }; diff --git a/frontend/types/generated/UpdateRagSetupRequest.ts b/frontend/types/generated/UpdateRagSetupRequest.ts index ca052967..dfaa45df 100644 --- a/frontend/types/generated/UpdateRagSetupRequest.ts +++ b/frontend/types/generated/UpdateRagSetupRequest.ts @@ -1,9 +1,14 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { ChunkingSettings } from "./ChunkingSettings"; +import type { OcrSettings } from "./OcrSettings"; import type { RagDefaults } from "./RagDefaults"; import type { RerankerSettings } from "./RerankerSettings"; /** * Saves the installation's knowledge settings; `GET` returns the same objects. */ -export type UpdateRagSetupRequest = { reranker: RerankerSettings, defaults: RagDefaults, chunking?: ChunkingSettings, }; +export type UpdateRagSetupRequest = { reranker: RerankerSettings, defaults: RagDefaults, chunking?: ChunkingSettings, +/** + * `None` keeps the stored document reading settings. + */ +ocr?: OcrSettings, }; diff --git a/frontend/utils/pricing.ts b/frontend/utils/pricing.ts index 9813ef75..89d7e6a6 100644 --- a/frontend/utils/pricing.ts +++ b/frontend/utils/pricing.ts @@ -7,7 +7,7 @@ import type {PriceTier} from '~/types/generated/PriceTier'; import type {PriceWeekday} from '~/types/generated/PriceWeekday'; import type {PriceWindow} from '~/types/generated/PriceWindow'; -export const RATE_FIELDS = ['input', 'output', 'cache_read', 'cache_write', 'reasoning', 'input_audio', 'output_audio', 'per_audio_second', 'per_character', 'per_request', 'per_search'] as const; +export const RATE_FIELDS = ['input', 'output', 'cache_read', 'cache_write', 'reasoning', 'input_audio', 'output_audio', 'per_audio_second', 'per_character', 'per_request', 'per_search', 'per_page'] as const; export type RateField = (typeof RATE_FIELDS)[number]; export const WEEKDAYS: PriceWeekday[] = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']; diff --git a/migrations/20251226000000_initial_schema.sql b/migrations/20251226000000_initial_schema.sql index 7f2274a1..15287e6c 100644 --- a/migrations/20251226000000_initial_schema.sql +++ b/migrations/20251226000000_initial_schema.sql @@ -1028,6 +1028,9 @@ CREATE TABLE IF NOT EXISTS rag_config ( default_connection_id UUID REFERENCES rag_connections(id) ON DELETE SET NULL, chunk_size INTEGER NOT NULL DEFAULT 400 CHECK (chunk_size BETWEEN 100 AND 2000), chunk_overlap_percent INTEGER NOT NULL DEFAULT 15 CHECK (chunk_overlap_percent BETWEEN 0 AND 50), + ocr_mode TEXT NOT NULL DEFAULT 'off' CHECK (ocr_mode IN ('off', 'fallback', 'always')), + ocr_model_id UUID REFERENCES models(id) ON DELETE SET NULL, + ocr_system_prompt TEXT, updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); @@ -5019,6 +5022,8 @@ INSERT INTO i18n_translations (language, key_path, value) VALUES ('de', 'pricing.rate.per_request', 'Pro Anfrage'), ('en', 'pricing.rate.per_search', 'Per search'), ('de', 'pricing.rate.per_search', 'Pro Suche'), + ('en', 'pricing.rate.per_page', 'Per page'), + ('de', 'pricing.rate.per_page', 'Pro Seite'), ('en', 'pricing.context_tiers', 'Context tiers'), ('de', 'pricing.context_tiers', 'Kontextstufen'), ('en', 'pricing.context_tiers_desc', 'Rates for long prompts, from a number of input tokens on.'), @@ -5801,8 +5806,8 @@ INSERT INTO i18n_translations (language, key_path, value) VALUES ('de', 'rag.doc_error.busy', 'Die Textextraktion ist ausgelastet. Bitte gleich erneut versuchen.'), ('en', 'rag.doc_error.extract_failed', 'Text could not be extracted from this file.'), ('de', 'rag.doc_error.extract_failed', 'Aus dieser Datei konnte kein Text extrahiert werden.'), - ('en', 'rag.doc_error.budget_exceeded', 'Embedding stopped because the budget is used up.'), - ('de', 'rag.doc_error.budget_exceeded', 'Das Embedding wurde gestoppt, weil das Budget aufgebraucht ist.'), + ('en', 'rag.doc_error.budget_exceeded', 'Indexing stopped because the budget is used up.'), + ('de', 'rag.doc_error.budget_exceeded', 'Die Indexierung wurde gestoppt, weil das Budget aufgebraucht ist.'), ('en', 'rag.doc_error.embedding_failed', 'The embedding model failed while indexing this document.'), ('de', 'rag.doc_error.embedding_failed', 'Das Embedding-Modell ist beim Indexieren dieses Dokuments fehlgeschlagen.'), ('en', 'rag.doc_error.embedding_model_not_allowed', 'The knowledge base''s model restrictions do not allow the connection''s embedding model.'), @@ -5811,6 +5816,20 @@ INSERT INTO i18n_translations (language, key_path, value) VALUES ('de', 'rag.doc_error.store_failed', 'Vektoren konnten nicht in die Speicherverbindung geschrieben werden.'), ('en', 'rag.doc_error.connection_not_ready', 'The storage connection has no embedding model configured.'), ('de', 'rag.doc_error.connection_not_ready', 'Für die Speicherverbindung ist kein Embedding-Modell eingerichtet.'), + ('en', 'rag.error.not_ocr_model', 'Pick an OCR model or a chat model that takes images.'), + ('de', 'rag.error.not_ocr_model', 'Wähle ein OCR-Modell oder ein Chat-Modell, das Bilder annimmt.'), + ('en', 'rag.error.ocr_model_required', 'Pick a model to read documents with, or turn document reading off.'), + ('de', 'rag.error.ocr_model_required', 'Wähle ein Modell zum Lesen von Dokumenten oder schalte das Lesen von Dokumenten aus.'), + ('en', 'rag.error.invalid_ocr_prompt', 'The instructions can have at most 8000 characters.'), + ('de', 'rag.error.invalid_ocr_prompt', 'Die Anweisungen dürfen höchstens 8000 Zeichen lang sein.'), + ('en', 'rag.error.ocr_unavailable', 'Images can only be uploaded while document reading is set up and this knowledge base''s model restrictions allow its model.'), + ('de', 'rag.error.ocr_unavailable', 'Bilder können nur hochgeladen werden, solange das Lesen von Dokumenten eingerichtet ist und die Modelleinschränkungen dieser Wissensdatenbank sein Modell erlauben.'), + ('en', 'rag.error.ocr_failed', 'The document reading model failed.'), + ('de', 'rag.error.ocr_failed', 'Das Lesemodell ist fehlgeschlagen.'), + ('en', 'rag.doc_error.ocr_failed', 'The document reading model failed while reading this file.'), + ('de', 'rag.doc_error.ocr_failed', 'Das Lesemodell ist beim Lesen dieser Datei fehlgeschlagen.'), + ('en', 'rag.doc_error.ocr_unavailable', 'Document reading is off or not allowed for this knowledge base, so this image cannot be read.'), + ('de', 'rag.doc_error.ocr_unavailable', 'Das Lesen von Dokumenten ist aus oder für diese Wissensdatenbank nicht erlaubt, daher kann dieses Bild nicht gelesen werden.'), ('en', 'settings.knowledge_setup.chunking_title', 'Chunking'), ('de', 'settings.knowledge_setup.chunking_title', 'Chunking'), ('en', 'settings.knowledge_setup.chunk_size', 'Chunk size (tokens)'), @@ -5821,6 +5840,36 @@ INSERT INTO i18n_translations (language, key_path, value) VALUES ('de', 'settings.knowledge_setup.chunk_overlap', 'Chunk-Überlappung (%)'), ('en', 'settings.knowledge_setup.chunk_overlap_hint', 'Overlap between neighboring passages (0 to 50%).'), ('de', 'settings.knowledge_setup.chunk_overlap_hint', 'Überlappung zwischen benachbarten Abschnitten (0 bis 50 %).'), + ('en', 'settings.knowledge_setup.ocr_title', 'Document reading (OCR)'), + ('de', 'settings.knowledge_setup.ocr_title', 'Dokumente lesen (OCR)'), + ('en', 'settings.knowledge_setup.ocr_description', 'Reads scanned PDF pages and images in knowledge uploads with a model. Their content is sent to that model''s provider, just like the embedding and reranker providers receive document text.'), + ('de', 'settings.knowledge_setup.ocr_description', 'Liest gescannte PDF-Seiten und Bilder in Wissens-Uploads mit einem Modell. Ihr Inhalt wird an den Anbieter dieses Modells gesendet, so wie die Anbieter von Embedding und Reranker den Dokumenttext erhalten.'), + ('en', 'settings.knowledge_setup.ocr_mode', 'When to read documents'), + ('de', 'settings.knowledge_setup.ocr_mode', 'Wann Dokumente gelesen werden'), + ('en', 'settings.knowledge_setup.ocr_mode_option.off', 'Off'), + ('de', 'settings.knowledge_setup.ocr_mode_option.off', 'Aus'), + ('en', 'settings.knowledge_setup.ocr_mode_option.fallback', 'Only pages without text'), + ('de', 'settings.knowledge_setup.ocr_mode_option.fallback', 'Nur Seiten ohne Text'), + ('en', 'settings.knowledge_setup.ocr_mode_option.always', 'Every PDF page'), + ('de', 'settings.knowledge_setup.ocr_mode_option.always', 'Jede PDF-Seite'), + ('en', 'settings.knowledge_setup.ocr_mode_hint.off', 'Only text in the file itself is indexed. Image uploads are refused.'), + ('de', 'settings.knowledge_setup.ocr_mode_hint.off', 'Nur der Text in der Datei selbst wird indexiert. Bild-Uploads werden abgelehnt.'), + ('en', 'settings.knowledge_setup.ocr_mode_hint.fallback', 'PDF pages with almost no text, and images, are read by the model. Other pages keep their own text.'), + ('de', 'settings.knowledge_setup.ocr_mode_hint.fallback', 'PDF-Seiten mit fast keinem Text und Bilder werden vom Modell gelesen. Andere Seiten behalten ihren eigenen Text.'), + ('en', 'settings.knowledge_setup.ocr_mode_hint.always', 'Every PDF page and every image is read by the model. Better for tables and layouts, but each page is billed.'), + ('de', 'settings.knowledge_setup.ocr_mode_hint.always', 'Jede PDF-Seite und jedes Bild wird vom Modell gelesen. Besser für Tabellen und Layouts, aber jede Seite wird abgerechnet.'), + ('en', 'settings.knowledge_setup.ocr_model', 'Reading model'), + ('de', 'settings.knowledge_setup.ocr_model', 'Lesemodell'), + ('en', 'settings.knowledge_setup.ocr_model_hint', 'An OCR model such as Mistral OCR, or a chat model that takes images. PDF pages need an OCR model or a chat model that takes PDF files. Billed to the uploader.'), + ('de', 'settings.knowledge_setup.ocr_model_hint', 'Ein OCR-Modell wie Mistral OCR oder ein Chat-Modell, das Bilder annimmt. PDF-Seiten brauchen ein OCR-Modell oder ein Chat-Modell, das PDF-Dateien annimmt. Abgerechnet bei der hochladenden Person.'), + ('en', 'settings.knowledge_setup.ocr_model_none', 'No model'), + ('de', 'settings.knowledge_setup.ocr_model_none', 'Kein Modell'), + ('en', 'settings.knowledge_setup.ocr_prompt', 'Instructions for chat models'), + ('de', 'settings.knowledge_setup.ocr_prompt', 'Anweisungen für Chat-Modelle'), + ('en', 'settings.knowledge_setup.ocr_prompt_hint', 'Sent as the system prompt when a chat model reads pages. OCR models take no instructions.'), + ('de', 'settings.knowledge_setup.ocr_prompt_hint', 'Wird als Systemprompt gesendet, wenn ein Chat-Modell Seiten liest. OCR-Modelle nehmen keine Anweisungen an.'), + ('en', 'settings.knowledge_setup.ocr_prompt_reset', 'Reset to default'), + ('de', 'settings.knowledge_setup.ocr_prompt_reset', 'Auf Standard zurücksetzen'), ('en', 'settings.knowledge_setup.connections.reindexing', 'Re-indexing ({done}/{total})'), ('de', 'settings.knowledge_setup.connections.reindexing', 'Neuindexierung ({done}/{total})'), ('en', 'settings.knowledge_setup.connections.reindex_confirm_title', 'Re-index stored knowledge?'), diff --git a/src/main.rs b/src/main.rs index 1674df76..49dc2759 100644 --- a/src/main.rs +++ b/src/main.rs @@ -21,7 +21,8 @@ use std::sync::Arc; fn main() { let mut args = std::env::args().skip(1); if args.next().as_deref() == Some(utils::extract::SUBCOMMAND) { - std::process::exit(utils::extract::child_main(args.next().as_deref())); + let kind = args.next(); + std::process::exit(utils::extract::child_main(kind.as_deref(), args.next().as_deref())); } match tokio::runtime::Builder::new_multi_thread().enable_all().build() { Ok(runtime) => runtime.block_on(serve()), diff --git a/src/routes/admin/rag.rs b/src/routes/admin/rag.rs index 05c48b10..b985e132 100644 --- a/src/routes/admin/rag.rs +++ b/src/routes/admin/rag.rs @@ -3,7 +3,7 @@ use crate::types::consts::{ADMIN_RAG_EDIT, ADMIN_RAG_VIEW}; use crate::types::rag::{ ConnectionMode, ConnectionTestResponse, InspectRequest, InspectResponse, RagConfig, RagConnection, RagError, ReindexEstimateRequest, SaveConnectionRequest, StoreError, - UpdateRagSetupRequest, VectorStore, check_reranker, probe_embedding, + UpdateRagSetupRequest, VectorStore, check_ocr_model, check_reranker, probe_embedding, }; use crate::types::{AppError, AuthUser, JobState, User, json_ok}; use crate::utils::response::ErrorCode; @@ -37,6 +37,9 @@ pub async fn update_setup(State(state): State>, auth: AuthUser, Js if let Some(model_id) = &req.reranker.model_id { check_reranker(&state.db, model_id).await?; } + if let Some(model_id) = req.ocr.as_ref().and_then(|ocr| ocr.model_id.as_ref()) { + check_ocr_model(&state.db, model_id).await?; + } RagConfig::save(&state.db, &auth.id, &req).await?; json_ok(RagConfig::setup(&state.db).await?) } diff --git a/src/tests/attachments.rs b/src/tests/attachments.rs index ef5bf43e..bdf60acc 100644 --- a/src/tests/attachments.rs +++ b/src/tests/attachments.rs @@ -1,7 +1,7 @@ #[cfg(test)] mod extraction { use crate::types::FileError; - use crate::utils::extract::{DocumentKind, extract, parse}; + use crate::utils::extract::{DocumentKind, checked_text, extract, parse}; const PDF: &[u8] = include_bytes!("fixtures/two_pages.pdf"); @@ -49,7 +49,9 @@ mod extraction { #[test] fn a_pdf_without_text_is_empty() -> Result<(), Box> { - assert_eq!(parse(DocumentKind::Pdf, &blank_pdf()?).as_deref(), Some("")); + let text = parse(DocumentKind::Pdf, &blank_pdf()?).unwrap_or_default(); + assert_eq!(text.trim(), ""); + assert!(matches!(checked_text(&text), Err(FileError::Empty))); Ok(()) } diff --git a/src/tests/rag.rs b/src/tests/rag.rs index 67215543..cd3fe26c 100644 --- a/src/tests/rag.rs +++ b/src/tests/rag.rs @@ -105,6 +105,7 @@ pub(crate) mod validation { reranker: RerankerSettings { model_id: None, top_n, min_score: None }, defaults: RagDefaults { connection_id: None }, chunking: None, + ocr: None, }; assert!(setup(1).validate().is_ok()); assert!(setup(50).validate().is_ok()); @@ -241,6 +242,7 @@ mod connections { reranker: RerankerSettings { model_id: None, top_n: 6, min_score: None }, defaults: RagDefaults { connection_id }, chunking: None, + ocr: None, }; assert!(matches!( @@ -1617,7 +1619,7 @@ mod chunker_and_extract { use crate::types::rag::{ChunkConfig, chunk_document, has_headings, normalize_vector, sha256_hex, split_embedding_batches}; use crate::utils::extract::{self, DocumentKind}; - fn sample_pdf(pages: &[&str]) -> Vec { + pub(super) fn sample_pdf(pages: &[&str]) -> Vec { let mut objects: Vec = Vec::new(); let mut kids = Vec::new(); let font_id = 3 + pages.len() * 2; @@ -1825,6 +1827,93 @@ mod chunker_and_extract { } } +#[cfg(test)] +mod ocr { + use super::chunker_and_extract::sample_pdf; + use crate::types::models::PriceSheet; + use crate::types::rag::{OcrMode, OcrReader, OcrSettings, RagError, RerankerSettings, RagDefaults, UpdateRagSetupRequest, assign_pages, pages_to_read}; + use crate::utils::extract; + + fn pages(texts: &[&str]) -> Vec { + texts.iter().map(|text| (*text).to_owned()).collect() + } + + #[test] + fn pages_split_and_join_at_their_markers() { + let text = "\nFirst\n\n\n\n\nThird\nmore"; + let split = extract::split_pages(text); + assert_eq!(split, pages(&["First", "", "Third\nmore"])); + assert_eq!(extract::join_pages(&split), "\nFirst\n\n\n\n\n\nThird\nmore"); + assert!(matches!(extract::checked_text("\n\n\n"), Err(crate::types::FileError::Empty))); + assert_eq!(extract::checked_text(" \nx ").ok().as_deref(), Some("\nx")); + } + + #[test] + fn images_are_recognized_by_extension_and_content() { + assert_eq!(extract::image_mime("scan.PNG", b"\x89PNG\r\n\x1a\n...."), Some("image/png")); + assert_eq!(extract::image_mime("scan.jpg", &[0xFF, 0xD8, 0xFF, 0xE0]), Some("image/jpeg")); + assert_eq!(extract::image_mime("scan.webp", b"RIFF\0\0\0\0WEBPVP8 "), Some("image/webp")); + assert_eq!(extract::image_mime("scan.gif", b"GIF89a.."), Some("image/gif")); + assert_eq!(extract::image_mime("scan.png", b"GIF89a.."), None); + assert_eq!(extract::image_mime("scan.svg", b""), None); + } + + #[test] + fn fallback_reads_only_pages_without_text_and_always_reads_every_page() { + let doc = pages(&["A full page of extracted text that is long enough.", "", " 12 ", "Another page with plenty of readable text in it."]); + let pdf = OcrReader::Vision { pdf: true }; + assert_eq!(pages_to_read(OcrMode::Fallback, pdf, &doc), vec![2, 3]); + assert_eq!(pages_to_read(OcrMode::Always, OcrReader::Ocr, &doc), vec![1, 2, 3, 4]); + assert!(pages_to_read(OcrMode::Always, OcrReader::Vision { pdf: false }, &doc).is_empty()); + assert!(pages_to_read(OcrMode::Off, OcrReader::Ocr, &doc).is_empty()); + } + + #[test] + fn vision_replies_are_assigned_to_the_pages_of_their_batch() { + let read = assign_pages("\n# Four\n\n\nFive\n\nnot asked", &[4, 5]); + assert_eq!(read.get(&4).map(String::as_str), Some("# Four")); + assert_eq!(read.get(&5).map(String::as_str), Some("Five\n\nnot asked")); + let unmarked = assign_pages("Just text", &[7]); + assert_eq!(unmarked.get(&7).map(String::as_str), Some("Just text")); + assert!(assign_pages("", &[1]).is_empty()); + } + + #[test] + fn a_pdf_is_cut_to_the_pages_asked_for() { + let pdf = sample_pdf(&["Hello page one", "Hello page two", "Hello page three"]); + let cut = extract::cut_pdf(&pdf, &[3, 1]).expect("cut"); + let text = extract::parse(extract::DocumentKind::Pdf, &cut).expect("text"); + let split = extract::split_pages(&text); + assert_eq!(split.len(), 2, "{text}"); + assert!(split.iter().any(|page| page.contains("page three")) && split.iter().any(|page| page.contains("page one")), "{text}"); + assert!(!text.contains("page two"), "{text}"); + assert!(extract::cut_pdf(&pdf, &[0]).is_none()); + assert!(extract::cut_pdf(&pdf, &[4]).is_none()); + } + + #[test] + fn reading_needs_a_model_and_bounded_instructions() { + let request = |mode, model_id, system_prompt| UpdateRagSetupRequest { + reranker: RerankerSettings { model_id: None, top_n: 6, min_score: None }, + defaults: RagDefaults { connection_id: None }, + chunking: None, + ocr: Some(OcrSettings { mode, model_id, system_prompt }), + }; + assert!(matches!(request(OcrMode::Fallback, None, None).validate(), Err(RagError::OcrModelRequired))); + assert!(request(OcrMode::Off, None, None).validate().is_ok()); + let model = Some(uuid::Uuid::new_v4()); + assert!(request(OcrMode::Always, model, Some("x".repeat(8000))).validate().is_ok()); + assert!(matches!(request(OcrMode::Always, model, Some("x".repeat(8001))).validate(), Err(RagError::InvalidOcrPrompt))); + } + + #[test] + fn page_rates_reach_the_engine_and_count_as_charging() { + let sheet: PriceSheet = serde_json::from_value(serde_json::json!({"input": 0, "output": 0, "per_page": 0.002})).expect("sheet"); + assert!(sheet.rates.charges_per_unit()); + assert_eq!(sheet.to_engine().and_then(|pricing| pricing.per_page), Some(0.002)); + } +} + #[cfg(test)] mod managed { use super::validation::request; @@ -1887,6 +1976,7 @@ mod managed { connection_id: Some(connection.id), }, chunking: Some(ChunkingSettings::default()), + ocr: None, }; RagConfig::save(pool, admin, &update).await?; Ok((connection, provider, model)) diff --git a/src/types/budgets/ledger.rs b/src/types/budgets/ledger.rs index 1af755b9..34f78cf5 100644 --- a/src/types/budgets/ledger.rs +++ b/src/types/budgets/ledger.rs @@ -84,6 +84,8 @@ pub struct UnitEstimate { pub characters: u64, pub requests: u32, pub searches: u32, + /// Document pages read by OCR. + pub pages: u32, } impl TokenEstimate { @@ -100,6 +102,7 @@ impl TokenEstimate { characters: 0, requests: 0, searches: 0, + pages: 0, }, } } diff --git a/src/types/models/pricing.rs b/src/types/models/pricing.rs index 91b0049c..f54696d3 100644 --- a/src/types/models/pricing.rs +++ b/src/types/models/pricing.rs @@ -52,6 +52,10 @@ pub struct PriceRates { #[serde(default, skip_serializing_if = "Option::is_none")] #[cfg_attr(test, ts(optional))] pub per_search: Option, + /// USD per document page read (OCR). + #[serde(default, skip_serializing_if = "Option::is_none")] + #[cfg_attr(test, ts(optional))] + pub per_page: Option, } /// Rates that apply once the prompt has at least `min_context_tokens` input tokens. @@ -216,13 +220,17 @@ impl PriceRates { per_character: self.per_character.or(below.per_character), per_request: self.per_request.or(below.per_request), per_search: self.per_search.or(below.per_search), + per_page: self.per_page.or(below.per_page), } } - /// Whether any per-unit rate (audio second, character, request, search) is above zero. + /// Whether any per-unit rate (audio second, character, request, search, page) is above zero. #[must_use] pub fn charges_per_unit(&self) -> bool { - [self.per_audio_second, self.per_character, self.per_request, self.per_search].into_iter().flatten().any(|rate| rate > 0.0) + [self.per_audio_second, self.per_character, self.per_request, self.per_search, self.per_page] + .into_iter() + .flatten() + .any(|rate| rate > 0.0) } } diff --git a/src/types/models/repository.rs b/src/types/models/repository.rs index 2c4db4c1..6e135d99 100644 --- a/src/types/models/repository.rs +++ b/src/types/models/repository.rs @@ -365,6 +365,17 @@ impl Model { AND COALESCE(sys_mc.capabilities, m.capabilities, '[]'::jsonb) ? 'RERANK' AND NOT (COALESCE(sys_mc.capabilities, m.capabilities, '[]'::jsonb) ? 'EMBEDDINGS' OR COALESCE(sys_mc.output_modalities, m.output_modalities, '[]'::jsonb) ? 'EMBEDDINGS') ) + OR ( + $6 = 'document_reader' + AND ( + COALESCE(sys_mc.capabilities, m.capabilities, '[]'::jsonb) ? 'OCR' + OR ( + EXISTS (SELECT 1 FROM jsonb_array_elements_text(COALESCE(sys_mc.input_modalities, m.input_modalities, '[]'::jsonb)) AS input(value) WHERE LOWER(input.value) = 'image') + AND EXISTS (SELECT 1 FROM jsonb_array_elements_text(COALESCE(sys_mc.output_modalities, m.output_modalities, '[]'::jsonb)) AS output(value) WHERE LOWER(output.value) = 'text') + AND NOT COALESCE(sys_mc.capabilities, m.capabilities, '[]'::jsonb) ?| ARRAY['EMBEDDINGS', 'RERANK', 'SPEECH_TO_TEXT', 'TEXT_TO_SPEECH', 'SYSTEM_ONE'] + ) + ) + ) ) ORDER BY m.display_name, p.name LIMIT $1 OFFSET $2 @@ -897,6 +908,7 @@ impl ModelPricing { input_characters: priced(rates.per_character, units.characters), requests: units.requests, searches: clamp(priced(rates.per_search, u64::from(units.searches))), + pages: clamp(priced(rates.per_page, u64::from(units.pages))), ..Default::default() }; Ok(omniference::catalog::compute_cost(Some(&pricing), &usage, now, None) diff --git a/src/types/models/requests.rs b/src/types/models/requests.rs index 0faa8b14..ca704a51 100644 --- a/src/types/models/requests.rs +++ b/src/types/models/requests.rs @@ -9,7 +9,7 @@ pub struct ModelListParams { pub provider_id: Option, /// Only models whose every output modality is this one, e.g. `text`. pub output_only: Option, - /// Only `embedding` or `reranking` models; other types match nothing. + /// Only `embedding` or `reranking` models, or `document_reader`: OCR models and chat models that take images; other types match nothing. #[serde(rename = "type")] pub model_type: Option, } diff --git a/src/types/rag/documents.rs b/src/types/rag/documents.rs index f8b2f4eb..849c4ff4 100644 --- a/src/types/rag/documents.rs +++ b/src/types/rag/documents.rs @@ -1,12 +1,12 @@ //! Uploaded documents of managed knowledge bases, stored as `files` rows under the shared upload limits, and per-document "Limit access" labels. use super::{ - DocumentStatus, KnowledgeActor, KnowledgeBase, ModelTargets, RagConfig, RagConnection, RagDocumentResponse, RagDocumentTextResponse, RagError, VectorStore, check_embedding_allowed, + DocumentStatus, KnowledgeActor, KnowledgeBase, ModelTargets, OcrPlan, RagConfig, RagConnection, RagDocumentResponse, RagDocumentTextResponse, RagError, VectorStore, check_embedding_allowed, }; use crate::logging::AuditLog; use crate::types::files::KNOWLEDGE_SOURCE; use crate::types::{AssignmentKind, AssignmentTarget, AssignmentsResponse, AuditEntry, FileStorage, JobState, ReplaceAssignmentsRequest}; -use crate::utils::extract::{DocumentKind, MAX_UPLOAD_BYTES}; +use crate::utils::extract::{self, DocumentKind, MAX_UPLOAD_BYTES}; use chrono::{DateTime, Utc}; use sqlx::PgPool; use uuid::Uuid; @@ -157,7 +157,8 @@ impl RagDocument { if bytes.len() > MAX_UPLOAD_BYTES { return Err(RagError::FileTooLarge); } - let kind = DocumentKind::detect(filename, bytes).ok_or(RagError::UnsupportedFile)?; + let detected = DocumentKind::detect(filename, bytes).map(DocumentKind::mime_type); + let mime_type = detected.or_else(|| extract::image_mime(filename, bytes)).ok_or(RagError::UnsupportedFile)?; let connection = RagConnection::find(&state.db, &base.connection_id).await?.ok_or(RagError::NotFound)?; let embedding = connection.embedding_settings().ok_or(RagError::ConnectionNotReady)?; if connection.vector_size.is_none() { @@ -165,6 +166,12 @@ impl RagDocument { } let targets = ModelTargets::load(&state.db, &[base.id]).await?.remove(&base.id).unwrap_or_default(); check_embedding_allowed(&state.db, &targets, &embedding.model_id).await?; + if detected.is_none() { + let config = RagConfig::get(&state.db).await?; + if OcrPlan::load(&state.db, &config, &targets).await?.is_none() { + return Err(RagError::OcrUnavailable); + } + } let size = i64::try_from(bytes.len()).unwrap_or(i64::MAX); let mut tx = FileStorage::begin_store(&state.db, &actor.user_id, bytes.len()).await?; @@ -181,7 +188,7 @@ impl RagDocument { .bind(actor.user_id) .bind(KNOWLEDGE_SOURCE) .bind(filename) - .bind(kind.mime_type()) + .bind(mime_type) .bind(size) .bind(bytes) .fetch_one(&mut *tx) diff --git a/src/types/rag/ingest.rs b/src/types/rag/ingest.rs index 1e20377e..2af2876d 100644 --- a/src/types/rag/ingest.rs +++ b/src/types/rag/ingest.rs @@ -1,8 +1,8 @@ //! Background ingest and deletion worker for managed knowledge bases. use super::{ - ChunkConfig, DocumentStatus, ManagedVector, ModelTargets, RagConfig, RagConnection, RagError, TextChunk, VectorStore, check_embedding_allowed, check_search_language, chunk_document, has_headings, - embed_batch, + ChunkConfig, DocumentStatus, ManagedVector, ModelTargets, OcrBilling, OcrPlan, RagConfig, RagConnection, RagError, TextChunk, VectorStore, check_embedding_allowed, check_search_language, chunk_document, + embed_batch, has_headings, }; use crate::types::{FileError, FileStorage, JobState}; use crate::utils::extract::{self, DocumentKind}; @@ -249,6 +249,7 @@ async fn claim_pending(pool: &PgPool) -> Result, sqlx::E struct IngestTarget<'a> { config: RagConfig, + targets: ModelTargets, connection: RagConnection, embedding: super::EmbeddingSettings, billing_user: Uuid, @@ -280,6 +281,7 @@ async fn prepare_ingest_target<'a>(state: &'a JobState, doc: &ClaimedDocument) - .map_err(|_| "store_failed")?; Ok(IngestTarget { config, + targets, connection, embedding, billing_user, @@ -306,7 +308,7 @@ async fn ingest_document(state: &JobState, doc: &ClaimedDocument) -> Result<(), } async fn index_fresh_document(state: &JobState, doc: &ClaimedDocument, target: &IngestTarget<'_>) -> Result<(), &'static str> { - let text = extract_or_reuse_text(state, doc).await?; + let text = extract_or_reuse_text(state, doc, target).await?; let config = ChunkConfig { headings: has_headings(&doc.filename, &doc.mime_type), pages: doc.mime_type == DocumentKind::Pdf.mime_type(), @@ -380,13 +382,12 @@ async fn write_vectors(pool: &PgPool, target: &WrittenVectors<'_>, rows: Vec Result { +async fn extract_or_reuse_text(state: &JobState, doc: &ClaimedDocument, target: &IngestTarget<'_>) -> Result { let Some(bytes) = &doc.source_bytes else { return doc.text.clone().filter(|text| !text.trim().is_empty()).ok_or("empty"); }; - let kind = DocumentKind::from_mime(&doc.mime_type).ok_or("extract_failed")?; - let text = extract::extract(kind, bytes).await.map_err(|error| error.reason())?; - let pages = if kind == DocumentKind::Pdf { extract::page_count(&text) } else { None }; + let text = read_document(state, doc, target, bytes).await?; + let pages = if doc.mime_type == DocumentKind::Pdf.mime_type() { extract::page_count(&text) } else { None }; store_text(state, doc, &text, pages).await.map_err(|error| match error { FileError::QuotaExceeded => "quota_exceeded", _ => "store_failed", @@ -394,6 +395,56 @@ async fn extract_or_reuse_text(state: &JobState, doc: &ClaimedDocument) -> Resul Ok(text) } +async fn read_document(state: &JobState, doc: &ClaimedDocument, target: &IngestTarget<'_>, bytes: &[u8]) -> Result { + let plan = OcrPlan::load(&state.db, &target.config, &target.targets).await.map_err(|_| "store_failed")?; + let reader = plan.zip(doc.uploaded_by); + if doc.mime_type.starts_with("image/") { + let (plan, user_id) = reader.ok_or("ocr_unavailable")?; + let text = plan.read_image(OcrBilling { state, user_id: &user_id }, &doc.mime_type, bytes).await.map_err(ocr_error)?; + return extract::checked_text(&text).map_err(|error| error.reason()); + } + let kind = DocumentKind::from_mime(&doc.mime_type).ok_or("extract_failed")?; + let Some((plan, user_id)) = reader.filter(|_| kind == DocumentKind::Pdf) else { + return extract::extract(kind, bytes).await.map_err(|error| error.reason()); + }; + read_pdf(&plan, OcrBilling { state, user_id: &user_id }, &doc.id, bytes).await +} + +async fn read_pdf(plan: &OcrPlan, billing: OcrBilling<'_>, document_id: &Uuid, bytes: &[u8]) -> Result { + let mut pages = extract::pdf_pages(bytes).await.map_err(|error| error.reason())?; + let wanted = plan.pages_to_read(&pages); + let failure = if wanted.is_empty() { + None + } else { + match plan.read_pdf_pages(billing, bytes, &wanted).await { + Ok(read) => { + for (page, text) in read { + if let Some(slot) = pages.get_mut(page.saturating_sub(1) as usize) { + *slot = text.replace('\0', ""); + } + } + None + } + Err(error) => { + tracing::warn!(%document_id, %error, "[JOBS] OCR failed; keeping the extracted text"); + Some(ocr_error(error)) + } + } + }; + match extract::checked_text(&extract::join_pages(&pages)) { + Err(FileError::Empty) => Err(failure.unwrap_or("empty")), + other => other.map_err(|error| error.reason()), + } +} + +fn ocr_error(error: RagError) -> &'static str { + match error { + RagError::BudgetExceeded => "budget_exceeded", + RagError::Database(_) => "store_failed", + _ => "ocr_failed", + } +} + async fn store_text(state: &JobState, doc: &ClaimedDocument, text: &str, pages: Option) -> Result<(), FileError> { let mut tx = match &doc.uploaded_by { Some(user_id) => FileStorage::begin_extracted(&state.db, user_id, &doc.file_id, text.len()).await?, diff --git a/src/types/rag/mod.rs b/src/types/rag/mod.rs index 4f735ee8..f2610d4e 100644 --- a/src/types/rag/mod.rs +++ b/src/types/rag/mod.rs @@ -7,6 +7,7 @@ mod ingest; mod knowledge_bases; mod model_access; mod models; +mod ocr; mod repository; mod requests; mod responses; @@ -23,6 +24,7 @@ pub use ingest::*; pub use knowledge_bases::*; pub use model_access::*; pub use models::*; +pub use ocr::*; pub use requests::*; pub use responses::*; pub use retrieval::*; @@ -55,6 +57,18 @@ pub enum ConnectionMode { ReadOnly, } +/// When uploads are read by the OCR model: never, only for PDF pages without text (and images), or for every PDF page. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, sqlx::Type)] +#[sqlx(type_name = "text", rename_all = "snake_case")] +#[serde(rename_all = "snake_case")] +#[cfg_attr(test, derive(ts_rs::TS))] +pub enum OcrMode { + #[default] + Off, + Fallback, + Always, +} + /// Who owns a managed knowledge base; external knowledge bases are always `installation`. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, sqlx::Type)] #[sqlx(type_name = "text", rename_all = "snake_case")] @@ -120,6 +134,10 @@ pub struct RagConfig { pub default_connection_id: Option, pub chunk_size: i32, pub chunk_overlap_percent: i32, + pub ocr_mode: OcrMode, + pub ocr_model_id: Option, + /// `None` uses [`DEFAULT_OCR_PROMPT`]. + pub ocr_system_prompt: Option, } /// Why knowledge settings or a connection could not be saved; `reason()` is translated as `rag.error.`. @@ -145,6 +163,16 @@ pub enum RagError { NotEmbeddingModel, #[error("not a reranking model")] NotRerankingModel, + #[error("not an OCR model or a chat model that reads images")] + NotOcrModel, + #[error("document reading needs a model")] + OcrModelRequired, + #[error("invalid document reading instructions")] + InvalidOcrPrompt, + #[error("images can only be read while document reading is set up and allowed")] + OcrUnavailable, + #[error("document reading failed: {0}")] + OcrFailed(String), #[error("the model or its provider is missing or disabled")] ModelUnavailable, #[error("the test embedding failed: {0}")] @@ -264,6 +292,11 @@ impl RagError { Self::InvalidDimensions => "invalid_dimensions", Self::NotEmbeddingModel => "not_embedding_model", Self::NotRerankingModel => "not_reranking_model", + Self::NotOcrModel => "not_ocr_model", + Self::OcrModelRequired => "ocr_model_required", + Self::InvalidOcrPrompt => "invalid_ocr_prompt", + Self::OcrUnavailable => "ocr_unavailable", + Self::OcrFailed(_) => "ocr_failed", Self::ModelUnavailable => "model_unavailable", Self::EmbeddingFailed(_) => "embedding_failed", Self::DimensionsMismatch => "dimensions_mismatch", diff --git a/src/types/rag/models.rs b/src/types/rag/models.rs index bc72cef5..852a4df5 100644 --- a/src/types/rag/models.rs +++ b/src/types/rag/models.rs @@ -20,7 +20,20 @@ const EMBED_BATCH_MAX_INPUTS: usize = 64; const EMBED_BATCH_MAX_TOKENS: usize = 16_000; const EMBED_IN_FLIGHT_PER_DOC: usize = 2; -async fn load(pool: &PgPool, model_id: &Uuid, expected_type: &str, wrong_type: RagError) -> Result<(Model, Provider), RagError> { +/// An enabled model with its provider, its Omniference model type and its input modalities (codes such as `IMAGE`, `FILE`). +pub(super) struct ModelKind { + pub model: Model, + pub provider: Provider, + pub model_type: &'static str, + pub input_modalities: Vec, +} + +/// Loads an enabled model with what kind of requests it serves. +/// +/// # Errors +/// +/// Returns `ModelUnavailable` or a database error. +pub(super) async fn model_kind(pool: &PgPool, model_id: &Uuid) -> Result { let model = Model::find_by_id(pool, model_id).await?.ok_or(RagError::ModelUnavailable)?; let provider = Provider::find_for_admin(pool, &model.provider_id).await?.ok_or(RagError::ModelUnavailable)?; if !model.is_enabled || !provider.is_enabled { @@ -28,7 +41,8 @@ async fn load(pool: &PgPool, model_id: &Uuid, expected_type: &str, wrong_type: R } let kind = sqlx::query!( r#"SELECT COALESCE(mc.capabilities, m.capabilities, '[]'::jsonb) AS "capabilities!: Json>", - COALESCE(mc.output_modalities, m.output_modalities, '[]'::jsonb) AS "output_modalities!: Json>" + COALESCE(mc.output_modalities, m.output_modalities, '[]'::jsonb) AS "output_modalities!: Json>", + COALESCE(mc.input_modalities, m.input_modalities, '[]'::jsonb) AS "input_modalities!: Json>" FROM models m LEFT JOIN model_configs mc ON mc.model_id = m.id AND mc.owner_id IS NULL WHERE m.id = $1"#, model.id @@ -36,10 +50,20 @@ async fn load(pool: &PgPool, model_id: &Uuid, expected_type: &str, wrong_type: R .fetch_optional(pool) .await? .ok_or(RagError::ModelUnavailable)?; - if model_type(&kind.capabilities.0, &kind.output_modalities.0) != expected_type { + Ok(ModelKind { + model_type: model_type(&kind.capabilities.0, &kind.output_modalities.0), + input_modalities: kind.input_modalities.0.iter().map(|code| code.to_ascii_uppercase()).collect(), + model, + provider, + }) +} + +async fn load(pool: &PgPool, model_id: &Uuid, expected_type: &str, wrong_type: RagError) -> Result<(Model, Provider), RagError> { + let kind = model_kind(pool, model_id).await?; + if kind.model_type != expected_type { return Err(wrong_type); } - Ok((model, provider)) + Ok((kind.model, kind.provider)) } /// Checks that `model_id` is an enabled reranking model. @@ -229,7 +253,7 @@ pub async fn rerank(state: &JobState, user_id: &Uuid, model_id: &Uuid, query: &s Ok(results.into_iter().filter_map(|result| Some((usize::try_from(result.index).ok()?, result.relevance_score))).collect()) } -async fn reserve(state: &JobState, user_id: &Uuid, model: &Model, estimate: TokenEstimate, request_type: &str) -> Result<(BudgetAdmission, BTreeMap), RagError> { +pub(super) async fn reserve(state: &JobState, user_id: &Uuid, model: &Model, estimate: TokenEstimate, request_type: &str) -> Result<(BudgetAdmission, BTreeMap), RagError> { let admission = match state .budget_ledger .reserve_for_model(&state.db, BudgetSubject::user(*user_id), &model.id, estimate) @@ -251,7 +275,7 @@ async fn reserve(state: &JobState, user_id: &Uuid, model: &Model, estimate: Toke Ok((admission, metadata)) } -async fn model_ref(model: &Model, provider: &Provider) -> Result { +pub(super) async fn model_ref(model: &Model, provider: &Provider) -> Result { let engine = crate::ai::get(); let registered = engine.get_provider(&provider.name).await; let provider_config = match registered { diff --git a/src/types/rag/ocr.rs b/src/types/rag/ocr.rs new file mode 100644 index 00000000..2a939555 --- /dev/null +++ b/src/types/rag/ocr.rs @@ -0,0 +1,271 @@ +//! Document reading (OCR) for managed knowledge uploads: scanned PDF pages and images are read by an OCR model (Mistral OCR, through Omniference's `ocr` request kind) or by a chat model that takes images or PDFs. + +use super::models::{ModelKind, model_kind, model_ref, reserve}; +use super::{ModelTargets, OcrMode, RagConfig, RagError}; +use crate::types::{JobState, TokenEstimate, UnitEstimate}; +use crate::utils::extract; +use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64}; +use futures_util::StreamExt; +use omniference::stream::{FinishReason, StreamEvent}; +use omniference::types::{ChatRequestIR, ContentPart, Message as OmniMessage, Modality, OcrDocument, OcrRequestIR, Role}; +use sqlx::PgPool; +use std::collections::BTreeMap; +use uuid::Uuid; + +/// The instructions a vision model reads pages with, unless the admin changed them. +pub const DEFAULT_OCR_PROMPT: &str = "You transcribe document pages into Markdown. +- Write down every word exactly as it appears, in reading order. Never summarize, translate, shorten or correct anything. +- Keep the structure: headings as Markdown headings, lists as lists, tables as Markdown tables with every row and column. +- Describe each figure, chart or photo in one line in square brackets, for example [Figure: bar chart of sales per quarter]. +- Start every page with a line , using the page numbers you are told. +- Reply with the transcription only, without any comment."; + +/// Pages a vision model reads in one request. +const VISION_BATCH_PAGES: usize = 10; + +/// A page with fewer visible characters than this is read again in `fallback` mode. +const MIN_PAGE_CHARS: usize = 32; + +const VISION_INPUT_TOKENS_PER_PAGE: u64 = 1_600; +const VISION_OUTPUT_TOKENS_PER_PAGE: u64 = 1_200; + +/// How a model reads documents. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OcrReader { + /// A dedicated OCR model: whole PDFs or selected pages, and images. + Ocr, + /// A chat model with image input; `pdf` when it also takes PDFs. + Vision { pdf: bool }, +} + +impl OcrReader { + fn of(kind: &ModelKind) -> Option { + let accepts = |code: &str| kind.input_modalities.iter().any(|modality| modality == code); + match kind.model_type { + "ocr" => Some(Self::Ocr), + "chat" if accepts("IMAGE") => Some(Self::Vision { pdf: accepts("FILE") }), + _ => None, + } + } + + const fn reads_pdfs(self) -> bool { + matches!(self, Self::Ocr | Self::Vision { pdf: true }) + } +} + +/// Checks that `model_id` is an enabled OCR model or a chat model that takes images. +/// +/// # Errors +/// +/// Returns `ModelUnavailable`, `NotOcrModel` or a database error. +pub async fn check_ocr_model(pool: &PgPool, model_id: &Uuid) -> Result { + OcrReader::of(&model_kind(pool, model_id).await?).ok_or(RagError::NotOcrModel) +} + +/// Who reads: the server state and the user every reading request is reserved against and billed to. +#[derive(Clone, Copy)] +pub struct OcrBilling<'a> { + pub state: &'a JobState, + pub user_id: &'a Uuid, +} + +/// The configured document reader, when OCR is on and the knowledge base's model restriction allows its model. +pub struct OcrPlan { + pub mode: OcrMode, + pub reader: OcrReader, + kind: ModelKind, + prompt: String, +} + +impl OcrPlan { + /// The reader for a knowledge base with model restriction `targets`; `None` while OCR is off, its model is gone or not allowed. + /// + /// # Errors + /// + /// Returns a database error. + pub async fn load(pool: &PgPool, config: &RagConfig, targets: &ModelTargets) -> Result, sqlx::Error> { + let Some(model_id) = config.ocr_model_id.filter(|_| config.ocr_mode != OcrMode::Off) else { + return Ok(None); + }; + let kind = match model_kind(pool, &model_id).await { + Ok(kind) => kind, + Err(RagError::Database(error)) => return Err(error), + Err(_) => return Ok(None), + }; + let Some(reader) = OcrReader::of(&kind) else { + return Ok(None); + }; + if !ModelTargets::allow_outright(pool, std::slice::from_ref(targets), &model_id).await? { + return Ok(None); + } + Ok(Some(Self { + mode: config.ocr_mode, + reader, + kind, + prompt: config.ocr_system_prompt.clone().unwrap_or_else(|| DEFAULT_OCR_PROMPT.to_owned()), + })) + } + + /// Reads an image as Markdown, billed to `user_id` as `rag_ocr`. + /// + /// # Errors + /// + /// Returns why the budget or the provider refused it, or that nothing was read. + pub async fn read_image(&self, billing: OcrBilling<'_>, mime: &str, bytes: &[u8]) -> Result { + let url = format!("data:{mime};base64,{}", BASE64.encode(bytes)); + let text = match self.reader { + OcrReader::Ocr => self.ocr(billing, OcrDocument::Image { url }, None, 1).await?.into_values().collect::>().join("\n\n"), + OcrReader::Vision { .. } => { + let part = ContentPart::ImageUrl { url, mime: Some(mime.to_owned()) }; + self.vision(billing, part, "Transcribe this image.", 1).await?.0 + } + }; + let text = text.replace('\0', ""); + if text.trim().is_empty() { Err(RagError::OcrFailed("no text".to_owned())) } else { Ok(text) } + } + + /// The pages of a PDF this plan reads, see [`pages_to_read`]. + #[must_use] + pub fn pages_to_read(&self, pages: &[String]) -> Vec { + pages_to_read(self.mode, self.reader, pages) + } + + /// Reads the 1-based `pages` of a PDF, billed to `user_id` as `rag_ocr`; returns the Markdown of each page read. + /// + /// # Errors + /// + /// Returns why the budget, the provider or the PDF cutter refused it. + pub async fn read_pdf_pages(&self, billing: OcrBilling<'_>, bytes: &[u8], pages: &[u32]) -> Result, RagError> { + match self.reader { + OcrReader::Ocr => { + let url = format!("data:application/pdf;base64,{}", BASE64.encode(bytes)); + let zero_based = pages.iter().map(|page| page.saturating_sub(1)).collect(); + let read = self.ocr(billing, OcrDocument::Document { url }, Some(zero_based), pages.len()).await?; + Ok(read.into_iter().map(|(index, text)| (index + 1, text)).filter(|(page, _)| pages.contains(page)).collect()) + } + OcrReader::Vision { .. } => { + let mut read = BTreeMap::new(); + for batch in pages.chunks(VISION_BATCH_PAGES) { + read.extend(self.vision_pages(billing, bytes, batch, true).await?); + } + Ok(read) + } + } + } + + async fn vision_pages(&self, billing: OcrBilling<'_>, bytes: &[u8], batch: &[u32], may_split: bool) -> Result, RagError> { + let subset = extract::pdf_subset(bytes, batch).await.map_err(|error| RagError::OcrFailed(error.reason().to_owned()))?; + let part = ContentPart::File { + file_id: None, + filename: Some("pages.pdf".to_owned()), + file_data: Some(format!("data:application/pdf;base64,{}", BASE64.encode(&subset))), + }; + let numbers = batch.iter().map(u32::to_string).collect::>().join(", "); + let instruction = format!("The attached PDF holds pages {numbers} of the document, in this order. Start each page with using these numbers."); + let (text, cut_off) = self.vision(billing, part, &instruction, batch.len()).await?; + if cut_off && may_split && batch.len() > 1 { + let (first, second) = batch.split_at(batch.len() / 2); + let mut read = Box::pin(self.vision_pages(billing, bytes, first, false)).await?; + read.extend(Box::pin(self.vision_pages(billing, bytes, second, false)).await?); + return Ok(read); + } + Ok(assign_pages(&text, batch)) + } + + async fn ocr(&self, billing: OcrBilling<'_>, document: OcrDocument, pages: Option>, page_count: usize) -> Result, RagError> { + let estimate = TokenEstimate { + units: UnitEstimate { + requests: 1, + pages: u32::try_from(page_count).unwrap_or(u32::MAX), + ..UnitEstimate::default() + }, + ..TokenEstimate::text(0, 0) + }; + let (admission, metadata) = reserve(billing.state, billing.user_id, &self.kind.model, estimate, "rag_ocr").await?; + let request = OcrRequestIR { + model: model_ref(&self.kind.model, &self.kind.provider).await?, + document, + pages, + raw_request: None, + metadata, + }; + let response = crate::ai::get().ocr(request).await.map_err(|error| RagError::OcrFailed(error.to_string()))?; + drop(admission); + Ok(response.pages.into_iter().map(|page| (page.index, page.markdown)).collect()) + } + + async fn vision(&self, billing: OcrBilling<'_>, part: ContentPart, instruction: &str, pages: usize) -> Result<(String, bool), RagError> { + let pages = pages as u64; + let input = TokenEstimate::input_for_bytes((self.prompt.len() + instruction.len()) as u64).saturating_add(pages.saturating_mul(VISION_INPUT_TOKENS_PER_PAGE)); + let estimate = TokenEstimate::text(input, pages.saturating_mul(VISION_OUTPUT_TOKENS_PER_PAGE)); + let (admission, metadata) = reserve(billing.state, billing.user_id, &self.kind.model, estimate, "rag_ocr").await?; + let mut ir = ChatRequestIR { + model: model_ref(&self.kind.model, &self.kind.provider).await?, + stream: true, + ..ChatRequestIR::default() + }; + ir.model.input_modalities = self.kind.input_modalities.iter().filter_map(|code| Modality::from_code(code)).collect(); + ir.sampling.temperature = Some(0.0); + ir.metadata.extend(metadata); + ir.messages = vec![ + OmniMessage { + role: Role::System, + parts: vec![ContentPart::Text(self.prompt.clone())], + name: None, + }, + OmniMessage { + role: Role::User, + parts: vec![part, ContentPart::Text(instruction.to_owned())], + name: None, + }, + ]; + let mut stream = crate::ai::get().chat(ir).await.map_err(|error| RagError::OcrFailed(error.to_string()))?; + let mut text = String::new(); + let mut cut_off = false; + while let Some(event) = stream.next().await { + match event { + StreamEvent::TextDelta { content } => text.push_str(&content), + StreamEvent::Finish { reason } => cut_off = reason == FinishReason::Length, + StreamEvent::Error { message, .. } => return Err(RagError::OcrFailed(message)), + StreamEvent::Done => break, + _ => {} + } + } + drop(admission); + Ok((text, cut_off)) + } +} + +/// The 1-based PDF pages `reader` reads in `mode`: every page in `always` mode, else those with almost no text; none for a model that cannot take PDFs. +#[must_use] +pub fn pages_to_read(mode: OcrMode, reader: OcrReader, pages: &[String]) -> Vec { + if !reader.reads_pdfs() || mode == OcrMode::Off { + return Vec::new(); + } + let sparse = |page: &String| page.chars().filter(|c| !c.is_whitespace()).count() < MIN_PAGE_CHARS; + (1..) + .zip(pages) + .filter(|(_, page)| mode == OcrMode::Always || sparse(page)) + .map(|(number, _)| number) + .collect() +} + +/// Splits a vision model's transcription of `batch` at its page markers; text without markers belongs to the first page. +#[must_use] +pub fn assign_pages(text: &str, batch: &[u32]) -> BTreeMap { + let mut read: BTreeMap = BTreeMap::new(); + let mut current = batch.first().copied(); + for line in text.lines() { + if let Some(page) = extract::parse_page_marker(line).and_then(|page| u32::try_from(page).ok()).filter(|page| batch.contains(page)) { + current = Some(page); + read.entry(page).or_default(); + continue; + } + if let Some(page) = current { + let entry = read.entry(page).or_default(); + entry.push_str(line); + entry.push('\n'); + } + } + read.into_iter().map(|(page, text)| (page, text.trim().to_owned())).filter(|(_, text)| !text.is_empty()).collect() +} diff --git a/src/types/rag/repository.rs b/src/types/rag/repository.rs index e0fdf355..0a70c051 100644 --- a/src/types/rag/repository.rs +++ b/src/types/rag/repository.rs @@ -1,5 +1,5 @@ use super::{ - ChunkConfig, ChunkingSettings, ConnectionEmbedding, ConnectionKind, ConnectionMode, ConnectionResponse, ENV_PGVECTOR_URL, EmbeddingSettings, ModelTargets, RagConfig, + ChunkConfig, ChunkingSettings, DEFAULT_OCR_PROMPT, OcrSettings, OcrSetup, ConnectionEmbedding, ConnectionKind, ConnectionMode, ConnectionResponse, ENV_PGVECTOR_URL, EmbeddingSettings, ModelTargets, RagConfig, RagConnection, RagDefaults, RagError, RagSetupResponse, ReindexEstimateResponse, ReindexProgress, RerankerSettings, SaveConnectionRequest, UpdateRagSetupRequest, check_embedding_allowed, estimate_embedding_cost, }; @@ -51,7 +51,8 @@ impl RagConfig { pub async fn get(pool: &PgPool) -> Result { sqlx::query_as!( Self, - "SELECT reranker_model_id, reranker_top_n, reranker_min_score, default_connection_id, chunk_size, chunk_overlap_percent FROM rag_config" + r#"SELECT reranker_model_id, reranker_top_n, reranker_min_score, default_connection_id, chunk_size, chunk_overlap_percent, + ocr_mode AS "ocr_mode: super::OcrMode", ocr_model_id, ocr_system_prompt FROM rag_config"# ) .fetch_one(pool) .await @@ -96,8 +97,19 @@ impl RagConfig { .fetch_one(&mut *tx) .await .map_err(|error| RagError::foreign_key_or(error, RagError::NotFound))?; + if let Some(ocr) = &request.ocr { + let prompt = ocr.system_prompt.as_deref().map(str::trim).filter(|prompt| !prompt.is_empty() && *prompt != DEFAULT_OCR_PROMPT); + sqlx::query("UPDATE rag_config SET ocr_mode = $1, ocr_model_id = $2, ocr_system_prompt = $3") + .bind(ocr.mode) + .bind(ocr.model_id) + .bind(prompt) + .execute(&mut *tx) + .await + .map_err(|error| RagError::foreign_key_or(error, RagError::ModelUnavailable))?; + } let chunking = serde_json::json!({ "chunk_size": chunk_size, "overlap_percent": overlap_percent }); - let metadata = serde_json::json!({ "reranker": request.reranker, "defaults": request.defaults, "chunking": chunking }); + let ocr = request.ocr.as_ref().map(|ocr| serde_json::json!({ "mode": ocr.mode, "model_id": ocr.model_id, "custom_prompt": ocr.system_prompt.is_some() })); + let metadata = serde_json::json!({ "reranker": request.reranker, "defaults": request.defaults, "chunking": chunking, "ocr": ocr }); AuditLog::write( &mut tx, AuditEntry { @@ -143,6 +155,14 @@ impl RagConfig { chunk_size: u32::try_from(config.chunk_size).unwrap_or(400), overlap_percent: u32::try_from(config.chunk_overlap_percent).unwrap_or(15), }, + ocr: OcrSetup { + settings: OcrSettings { + mode: config.ocr_mode, + model_id: config.ocr_model_id, + system_prompt: config.ocr_system_prompt, + }, + default_system_prompt: DEFAULT_OCR_PROMPT, + }, }) } diff --git a/src/types/rag/requests.rs b/src/types/rag/requests.rs index 630d82d4..13d54d63 100644 --- a/src/types/rag/requests.rs +++ b/src/types/rag/requests.rs @@ -1,4 +1,4 @@ -use super::{ConnectionKind, ConnectionMode, ExternalView, KnowledgeScope, ModelTargets, RagError, check_search_language}; +use super::{ConnectionKind, ConnectionMode, ExternalView, KnowledgeScope, ModelTargets, OcrMode, RagError, check_search_language}; use serde::{Deserialize, Serialize}; use uuid::Uuid; @@ -68,8 +68,27 @@ pub struct UpdateRagSetupRequest { #[serde(default)] #[cfg_attr(test, ts(optional))] pub chunking: Option, + /// `None` keeps the stored document reading settings. + #[serde(default)] + #[cfg_attr(test, ts(optional))] + pub ocr: Option, } +/// Document reading (OCR) for knowledge uploads. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct OcrSettings { + pub mode: OcrMode, + /// An OCR model, or a chat model that takes images (and PDFs, for PDF pages). + pub model_id: Option, + /// Instructions for chat models; `None` uses the default ones. OCR models take none. + #[serde(default)] + pub system_prompt: Option, +} + +/// Longest custom instructions for document reading. +pub const MAX_OCR_PROMPT_CHARS: usize = 8000; + /// Optional model that sorts search hits by relevance. #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] #[cfg_attr(test, derive(ts_rs::TS))] @@ -275,6 +294,14 @@ impl UpdateRagSetupRequest { { return Err(RagError::InvalidChunking); } + if let Some(ocr) = &self.ocr { + if ocr.mode != OcrMode::Off && ocr.model_id.is_none() { + return Err(RagError::OcrModelRequired); + } + if ocr.system_prompt.as_ref().is_some_and(|prompt| prompt.chars().count() > MAX_OCR_PROMPT_CHARS) { + return Err(RagError::InvalidOcrPrompt); + } + } Ok(()) } } diff --git a/src/types/rag/responses.rs b/src/types/rag/responses.rs index 10656ce3..b4b76ba7 100644 --- a/src/types/rag/responses.rs +++ b/src/types/rag/responses.rs @@ -1,5 +1,5 @@ use super::{ - ChunkingSettings, ConnectionKind, ConnectionMode, Distance, DocumentStatus, ExternalView, KnowledgeHit, KnowledgeScope, RagDefaults, RerankerSettings, StoreError, + ChunkingSettings, ConnectionKind, ConnectionMode, Distance, DocumentStatus, ExternalView, KnowledgeHit, KnowledgeScope, OcrSettings, RagDefaults, RerankerSettings, StoreError, }; use chrono::{DateTime, Utc}; use serde::Serialize; @@ -13,6 +13,16 @@ pub struct RagSetupResponse { pub reranker: RerankerSettings, pub defaults: RagDefaults, pub chunking: ChunkingSettings, + pub ocr: OcrSetup, +} + +/// Document reading settings with the instructions "Reset to default" restores. +#[derive(Debug, Serialize)] +#[cfg_attr(test, derive(ts_rs::TS))] +pub struct OcrSetup { + #[serde(flatten)] + pub settings: OcrSettings, + pub default_system_prompt: &'static str, } /// Progress of an active re-index on a managed connection. diff --git a/src/utils/extract.rs b/src/utils/extract.rs index 0ac83f54..5787c4a5 100644 --- a/src/utils/extract.rs +++ b/src/utils/extract.rs @@ -22,6 +22,10 @@ pub const MAX_TEXT_BYTES: usize = 8 * 1024 * 1024; /// The command-line argument that starts the extraction child process. pub const SUBCOMMAND: &str = "extract"; +const PDF_PAGES_ARG: &str = "pdf-pages"; + +const MAX_SUBSET_BYTES: usize = 2 * MAX_UPLOAD_BYTES; + const TIMEOUT: Duration = Duration::from_secs(30); const MAX_CONCURRENT_CHILDREN: usize = 4; @@ -96,10 +100,19 @@ impl DocumentKind { pub async fn extract(kind: DocumentKind, bytes: &[u8]) -> Result { let text = match kind { DocumentKind::Text => decode_text(bytes)?, - DocumentKind::Html | DocumentKind::Pdf => run_child(kind, bytes).await?, + DocumentKind::Html | DocumentKind::Pdf => run_child(kind.arg(), bytes).await?, }; + checked_text(&text) +} + +/// The text with its surrounding whitespace trimmed, refused when it holds nothing but page markers or is too long. +/// +/// # Errors +/// +/// Returns `Empty` or `TextTooLong`. +pub fn checked_text(text: &str) -> Result { let text = text.trim(); - if text.is_empty() { + if text.lines().all(|line| line.trim().is_empty() || is_page_line(line)) { return Err(FileError::Empty); } if text.len() > MAX_TEXT_BYTES { @@ -108,6 +121,69 @@ pub async fn extract(kind: DocumentKind, bytes: &[u8]) -> Result Result, FileError> { + Ok(split_pages(&run_child(DocumentKind::Pdf.arg(), bytes).await?)) +} + +/// A PDF with only the 1-based `pages` of `bytes`, in that order, cut in the child process. +/// +/// # Errors +/// +/// Returns an [`FileError`] when the PDF cannot be read or cut in time. +pub async fn pdf_subset(bytes: &[u8], pages: &[u32]) -> Result, FileError> { + let list = pages.iter().map(u32::to_string).collect::>().join(","); + run_child_bytes(&[PDF_PAGES_ARG, &list], bytes, MAX_SUBSET_BYTES).await +} + +/// Splits extracted PDF text at its page marker lines; text before the first marker is dropped. +#[must_use] +pub fn split_pages(text: &str) -> Vec { + let mut pages: Vec = Vec::new(); + for line in text.lines() { + if is_page_line(line) { + pages.push(String::new()); + } else if let Some(page) = pages.last_mut() { + page.push_str(line); + page.push('\n'); + } + } + pages.iter().map(|page| page.trim().to_owned()).collect() +} + +/// Page texts marked with `` the way PDF extraction marks them. +#[must_use] +pub fn join_pages(pages: &[String]) -> String { + pages + .iter() + .enumerate() + .map(|(index, page)| format!("\n{}", index + 1, page.trim())) + .collect::>() + .join("\n\n") +} + +fn is_page_line(line: &str) -> bool { + let line = line.trim(); + line.starts_with("") +} + +/// The media type of a PNG, JPEG, WebP or GIF image, judged by its extension and its first bytes. +#[must_use] +pub fn image_mime(filename: &str, bytes: &[u8]) -> Option<&'static str> { + let extension = Path::new(filename).extension()?.to_str()?.to_ascii_lowercase(); + match extension.as_str() { + "png" => bytes.starts_with(b"\x89PNG\r\n\x1a\n").then_some("image/png"), + "jpg" | "jpeg" => bytes.starts_with(&[0xFF, 0xD8, 0xFF]).then_some("image/jpeg"), + "webp" => (bytes.len() > 12 && bytes.starts_with(b"RIFF") && &bytes[8..12] == b"WEBP").then_some("image/webp"), + "gif" => (bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a")).then_some("image/gif"), + _ => None, + } +} + /// The highest `` marker in extracted text. #[must_use] pub fn page_count(text: &str) -> Option { @@ -130,7 +206,12 @@ fn decode_text(bytes: &[u8]) -> Result { Ok(text.replace("\r\n", "\n").replace('\r', "\n")) } -async fn run_child(kind: DocumentKind, bytes: &[u8]) -> Result { +async fn run_child(arg: &str, bytes: &[u8]) -> Result { + let output = run_child_bytes(&[arg], bytes, MAX_TEXT_BYTES).await?; + String::from_utf8(output).map_err(|_| FileError::ExtractFailed) +} + +async fn run_child_bytes(args: &[&str], bytes: &[u8], limit: usize) -> Result, FileError> { let _slot = tokio::time::timeout(TIMEOUT, CHILD_SLOTS.acquire()) .await .map_err(|_| FileError::Busy)? @@ -141,7 +222,7 @@ async fn run_child(kind: DocumentKind, bytes: &[u8]) -> Result Result MAX_TEXT_BYTES { + if output.len() > limit { return Err(FileError::TextTooLong); } let status = child.wait().await.map_err(|_| FileError::ExtractFailed)?; if !status.success() { return Err(FileError::ExtractFailed); } - String::from_utf8(output).map_err(|_| FileError::ExtractFailed) + Ok(output) }; tokio::time::timeout(TIMEOUT, work).await.map_err(|_| FileError::TimedOut)? } -/// Entry point of the extraction child process: reads the file from stdin and writes its text to stdout. +/// Entry point of the extraction child process: reads the file from stdin and writes its text (or, for `pdf-pages`, the cut PDF) to stdout. #[must_use] -pub fn child_main(kind: Option<&str>) -> i32 { +pub fn child_main(kind: Option<&str>, pages: Option<&str>) -> i32 { limit_memory(); - let Some(kind) = kind.and_then(DocumentKind::from_arg) else { - return 2; - }; let mut input = Vec::new(); if std::io::stdin().take(MAX_UPLOAD_BYTES as u64 + 1).read_to_end(&mut input).is_err() || input.len() > MAX_UPLOAD_BYTES { return 1; } - let Some(text) = parse(kind, &input) else { + let output = match kind { + Some(PDF_PAGES_ARG) => pages.and_then(|pages| subset(&input, pages)), + _ => match kind.and_then(DocumentKind::from_arg) { + Some(kind) => parse(kind, &input).map(String::into_bytes), + None => return 2, + }, + }; + let Some(output) = output else { return 1; }; - match std::io::stdout().lock().write_all(text.as_bytes()) { + match std::io::stdout().lock().write_all(&output) { Ok(()) => 0, Err(_) => 1, } } +fn subset(input: &[u8], pages: &str) -> Option> { + let pages: Vec = pages.split(',').map(|page| page.parse().ok()).collect::>()?; + cut_pdf(input, &pages) +} + +/// A PDF with only the 1-based `pages` of `input`, in the current process; only the child process calls this. +#[must_use] +pub fn cut_pdf(input: &[u8], pages: &[u32]) -> Option> { + let pages: Vec = pages.iter().map(|page| usize::try_from(*page).ok()?.checked_sub(1)).collect::>()?; + let mut editor = pdf_oxide::editor::DocumentEditor::from_bytes(input.to_vec()).ok()?; + editor.extract_pages_to_bytes(&pages).ok() +} + /// Parses a file in the current process; only the child process calls this for HTML and PDF. /// /// A file whose parsed text is only whitespace yields an empty string, and NUL characters, which Postgres cannot store, are left out. @@ -212,9 +310,6 @@ pub fn parse(kind: DocumentKind, input: &[u8]) -> Option { fn pdf_text(input: &[u8]) -> Option { let doc = pdf_oxide::PdfDocument::from_bytes(input.to_vec()).ok()?; let pages: Vec> = (0..doc.page_count().ok()?).map(|page| doc.extract_text(page).ok().map(|text| text.replace('\0', ""))).collect(); - if pages.iter().flatten().all(|page| page.trim().is_empty()) { - return Some(String::new()); - } let marked: Vec = pages .iter() .enumerate() From be8c8c65452037c4b7270d83dbecc458ca8fb4de Mon Sep 17 00:00:00 2001 From: Henrik-3 Date: Sun, 29 Nov 2026 12:09:55 +0100 Subject: [PATCH 2/2] [FIX] - Keep OCR results on failures and recheck model access per request --- AGENTS.md | 2 +- frontend/pages/settings/tools/knowledge.vue | 4 +- src/routes/admin/rag.rs | 4 +- src/tests/rag.rs | 8 ++++ src/types/models/pricing.rs | 21 ++++++-- src/types/models/repository.rs | 5 +- src/types/rag/documents.rs | 2 +- src/types/rag/ingest.rs | 34 ++++++------- src/types/rag/ocr.rs | 53 +++++++++++++++------ src/types/rag/repository.rs | 33 +++++++------ src/utils/extract.rs | 9 +++- 11 files changed, 111 insertions(+), 64 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 27b933c2..4de581cb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -86,7 +86,7 @@ - Connect flow: `POST /api/v1/admin/rag/connections/{id}/inspect` (`admin.rag.edit`) returns `InspectResponse` (`error` or `collection: CollectionInfo`) for a collection and filter, checked like a saved view (`InspectRequest::validate`); the editor is `SettingsKnowledgeEditor` with `SettingsKnowledgeSourceForm` (steps: connection, collection, sample, fields, filter, embedding model, who may see what), `SettingsKnowledgeSharing` and `SettingsKnowledgeTestSearch`. The e2e stand-in serves a read-only Qdrant under `${MOCK_LLM_URL}/qdrant` (`handbook` with mock-embed's 3 dimensions, `wide` with 4, `intranet` whose records list `oxide_access` labels; it answers `match.any` and `facet`) - Managed knowledge bases (slice 4, `chunker.rs`, `documents.rs`, `ingest.rs`, `src/utils/extract.rs`, `rag_documents` / `rag_chunks`): a managed knowledge base has `view = NULL`, binds to the default managed pgvector connection (`rag_config.default_connection_id`), carries a `scope` (`personal` with `settings.knowledge.edit`, `team` for team admins, `installation` for `admin.rag.edit`, `GET /api/v1/knowledge-bases/scopes`), a PostgreSQL `search_language` (`regconfig`, validated against `SEARCH_LANGUAGES`), and soft deletion (`deleted_at`); `rag_documents.knowledge_base_id` uses `ON DELETE RESTRICT` so vectors are never cascaded away, and `User::delete` marks personal KB documents `deleting` (and soft-deletes non-empty personal KBs) inside its transaction and notifies `JobState.rag_ingest_notify` - Upload & ingest: `POST /api/v1/knowledge-bases/{id}/documents?filename=…` (25 MiB limit) checks `DocumentKind::detect` (text/code, HTML, PDF with `%PDF-`), the shared hourly upload limit and storage quota through `FileStorage::begin_store` (`RagError::RateLimited`, `RagError::StorageQuotaExceeded`), and KB model access against the connection's embedding model; it stores the file as a `files` row (`source = 'knowledge'`, `KNOWLEDGE_SOURCE`; name, type, size, original bytes in `data` and, once extracted, `text`) that the `rag_documents` row points to (`file_id`, `ON DELETE RESTRICT`; the worker deletes both after purging vectors), as `status = 'pending'` and notifies `rag_ingest_notify`. Two `rag_ingest_worker` background tasks (`src/jobs.rs`) claim jobs via `FOR UPDATE SKIP LOCKED`, extract HTML/PDF/text in a sandboxed child process (`OxideChat extract`, handled in plain `fn main()` before Tokio starts, 4 concurrent children, empty env, 30 s, 1 GiB `RLIMIT_AS` on Linux, 8 MiB text cap, PDF pages marked ``), chunk with `chunk_document` (heading hierarchy, ~15% overlap, no cross-section overlap on `#`/`##`, split Markdown tables repeat header + separator row, `doc › heading` embed prefix, SHA-256 `content_hash`), batch-embed (`embed_batch`, <=64 inputs / ~16k tokens, 2 in flight, billed as `rag_ingest`), and write L2-normalized vectors into per-connection per-generation pgvector tables `rag_vectors__g` (`halfvec(N)` + HNSW `halfvec_cosine_ops` + GIN `access`); extracted text replaces the kept bytes only if it fits the uploader's storage quota (`FileStorage::begin_extracted`, else `quota_exceeded`), failed uploads keep `files.data` for 7 days for `POST …/retry`, a claim is the row's `locked_at`, which every later write of that worker must still match (a re-queued or reaped document makes the old worker's writes no-ops), a worker touches `updated_at` every minute while it works and a document untouched for 10 min is queued again, a panic fails only its document, `#` lines are headings only in Markdown, text and HTML files (`has_headings`), and `deleting` rows purge vectors before removing Postgres rows and finished soft-deleted KBs; `Team::delete` hands a team's knowledge bases to the same path (`KnowledgeBase::delete_team_owned`), viewers list only the documents their labels grant (`RagDocument::visible_to`), `GET …/documents/{doc_id}/text` returns a document's extracted text under the same rule (`RagDocument::text`, the eye button in `SettingsKnowledgeDocuments`), document lists and text need `KnowledgeActor::can_search` or edit rights (`admin.rag.view` alone sees bases, not their documents), and a managed connection's address cannot change while documents are stored on it (`ConnectionHasDocuments`) - - Document reading (slice 5b, `ocr.rs`): `rag_config.ocr_mode` (`off`, `fallback`, `always`), `ocr_model_id` and `ocr_system_prompt` (`NULL` uses `DEFAULT_OCR_PROMPT`), in the setup request and response as `ocr: {mode, model_id, system_prompt}` (the response adds `default_system_prompt`; `check_ocr_model` accepts an Omniference `ocr` model or a chat model with `IMAGE` input, and the admin model list takes `?type=document_reader` for the picker). `OcrPlan::load` returns the reader only while OCR is on and the knowledge base's model restriction allows its model outright, else OCR is skipped. The worker reads images (PNG, JPEG, WebP, GIF, accepted on upload only while `OcrPlan::load` finds a reader, else `ocr_unavailable`) and, for PDFs, the pages `pages_to_read` picks (`always`: every page; `fallback`: pages with fewer than 32 visible characters; none for a chat model without `FILE` input): OCR models get the whole PDF with zero-based `pages` through `engine.ocr()`; chat models get sub-PDFs of 10 pages cut in the extraction child (`extract::pdf_subset`, `pdf-pages` subcommand) with the system prompt at temperature 0, a batch cut off at the length limit is split in half once, and `` markers in the reply assign the text to pages (`assign_pages`). Every request is reserved against the uploader's budget as `rag_ocr` (`UnitEstimate.pages` priced by `per_page`); a failed read keeps the PDF's own text and fails the document only when nothing is left. PDF extraction always marks every page, and `extract::checked_text` refuses text that is only page markers + - Document reading (slice 5b, `ocr.rs`): `rag_config.ocr_mode` (`off`, `fallback`, `always`), `ocr_model_id` and `ocr_system_prompt` (`NULL` uses `DEFAULT_OCR_PROMPT`), in the setup request and response as `ocr: {mode, model_id, system_prompt}` (the response adds `default_system_prompt`; `check_ocr_model` accepts an Omniference `ocr` model or a chat model with `IMAGE` input, and the admin model list takes `?type=document_reader` for the picker). `OcrPlan::load` returns the reader only while OCR is on and the knowledge base's model restriction allows its model outright, else OCR is skipped. The worker reads images (PNG, JPEG, WebP, GIF, accepted on upload only while `OcrPlan::load` finds a reader, else `ocr_unavailable`) and, for PDFs, the pages `pages_to_read` picks (`always`: every page; `fallback`: pages with fewer than 32 visible characters; none for a chat model without `FILE` input): OCR models get the whole PDF with zero-based `pages` through `engine.ocr()`; chat models get sub-PDFs of 10 pages cut in the extraction child (`extract::pdf_subset`, `pdf-pages` subcommand) with the system prompt at temperature 0, a batch cut off at the length limit is split in half once, and `` markers in the reply assign the text to pages (`assign_pages`). Every request is reserved against the uploader's budget as `rag_ocr` (`UnitEstimate.pages` priced by `per_page`); a failed read keeps the PDF's own text and fails the document only when nothing is left: a reply still cut off at the length limit counts as failed, pages read before a failed batch are kept, an empty reading never replaces a page's text, and the base's model restriction is checked again before every request (`OcrPlan::check_allowed`). Lines in a page's text that look like page markers are escaped with a backslash (`extract::escape_markers`). PDF extraction always marks every page, and `extract::checked_text` refuses text that is only page markers - Hybrid search, per-document access & re-indexing: `hybrid_search_managed` runs pgvector cosine search (`SET LOCAL hnsw.iterative_scan = relaxed_order`) alongside time-limited Postgres FTS (`websearch_to_tsquery`, 1.5 s timeout), re-checks `d.status = 'ready'` and `access` fail-closed in Postgres, and merges with RRF; per-document "Limit access" uses `GET/PUT …/documents/{doc_id}/assignments` (`team:`, `role:`, `user:` stored on `rag_documents.access`, `rag_chunks.access`, and pgvector `access`; empty clears back to `NULL` inheriting the KB). Changing a managed connection's embedding model checks KB model-access conflicts (`ConnectionModelConflict`), exposes `POST /api/v1/admin/rag/connections/{id}/reindex-estimate`, bumps `index_generation`, marks documents `pending` with `reindex_by`, blocks search with `StoreError::Reindexing` while documents are still `pending` or `processing` behind it (failed ones do not block), and drops generation tables older than the current one once those finish. Frontend adds `SettingsKnowledgeDocuments`, scope/language controls in `Editor.vue`, Mine / Shared with me / All tabs on `/settings/knowledge`, chunking settings and re-index confirmation/progress on `/settings/tools/knowledge`, and page badges on `ToolExecutionDisplay` - `src/types/presets/` - Presets (`model_presets`): a base model plus instructions, sampling (`PresetSampling`), reasoning, tools (optionally locked) and up to four starters, addressed as `presets/` - The slug is unique across all scopes, and `presets/` is a reserved namespace: providers cannot be named `presets` and model sync skips IDs starting with `presets/` (both also enforced by CHECK constraints) diff --git a/frontend/pages/settings/tools/knowledge.vue b/frontend/pages/settings/tools/knowledge.vue index 9d85c661..ba57affc 100644 --- a/frontend/pages/settings/tools/knowledge.vue +++ b/frontend/pages/settings/tools/knowledge.vue @@ -186,7 +186,9 @@ const settingsForm = useSettingsForm({ }, save: async () => { try { - setup.value = await saveRagSetup(form); + const saved = await saveRagSetup(form); + setup.value = saved; + fill(saved); } catch (error: any) { throw new Error(ragErrorMessage(error, '')); } diff --git a/src/routes/admin/rag.rs b/src/routes/admin/rag.rs index b985e132..f22d2837 100644 --- a/src/routes/admin/rag.rs +++ b/src/routes/admin/rag.rs @@ -2,7 +2,7 @@ use crate::types::consts::{ADMIN_RAG_EDIT, ADMIN_RAG_VIEW}; use crate::types::rag::{ - ConnectionMode, ConnectionTestResponse, InspectRequest, InspectResponse, RagConfig, RagConnection, RagError, ReindexEstimateRequest, SaveConnectionRequest, StoreError, + ConnectionMode, ConnectionTestResponse, InspectRequest, InspectResponse, OcrMode, RagConfig, RagConnection, RagError, ReindexEstimateRequest, SaveConnectionRequest, StoreError, UpdateRagSetupRequest, VectorStore, check_ocr_model, check_reranker, probe_embedding, }; use crate::types::{AppError, AuthUser, JobState, User, json_ok}; @@ -37,7 +37,7 @@ pub async fn update_setup(State(state): State>, auth: AuthUser, Js if let Some(model_id) = &req.reranker.model_id { check_reranker(&state.db, model_id).await?; } - if let Some(model_id) = req.ocr.as_ref().and_then(|ocr| ocr.model_id.as_ref()) { + if let Some(model_id) = req.ocr.as_ref().filter(|ocr| ocr.mode != OcrMode::Off).and_then(|ocr| ocr.model_id.as_ref()) { check_ocr_model(&state.db, model_id).await?; } RagConfig::save(&state.db, &auth.id, &req).await?; diff --git a/src/tests/rag.rs b/src/tests/rag.rs index cd3fe26c..cd7054a6 100644 --- a/src/tests/rag.rs +++ b/src/tests/rag.rs @@ -1846,6 +1846,8 @@ mod ocr { assert_eq!(extract::join_pages(&split), "\nFirst\n\n\n\n\n\nThird\nmore"); assert!(matches!(extract::checked_text("\n\n\n"), Err(crate::types::FileError::Empty))); assert_eq!(extract::checked_text(" \nx ").ok().as_deref(), Some("\nx")); + let joined = extract::join_pages(&pages(&["Quoted\n", "Two"])); + assert_eq!(extract::split_pages(&joined), pages(&["Quoted\n\\", "Two"]), "literal marker lines do not start pages"); } #[test] @@ -1911,6 +1913,12 @@ mod ocr { let sheet: PriceSheet = serde_json::from_value(serde_json::json!({"input": 0, "output": 0, "per_page": 0.002})).expect("sheet"); assert!(sheet.rates.charges_per_unit()); assert_eq!(sheet.to_engine().and_then(|pricing| pricing.per_page), Some(0.002)); + let timed: PriceSheet = serde_json::from_value(serde_json::json!({ + "input": 0, "output": 0, + "windows": [{"start": "08:00", "end": "18:00", "rates": {"per_page": 0.004}}] + })) + .expect("timed sheet"); + assert!(!timed.rates.charges_per_unit() && timed.charges_beyond_tokens(), "a page rate in a time window charges"); } } diff --git a/src/types/models/pricing.rs b/src/types/models/pricing.rs index f54696d3..1604be10 100644 --- a/src/types/models/pricing.rs +++ b/src/types/models/pricing.rs @@ -316,17 +316,28 @@ impl PriceSheet { validate_windows(self.windows.as_deref().unwrap_or_default()) } + /// Base rates, then context tiers, service tiers with their own tiers, and time windows. + fn layers(&self) -> impl Iterator { + let services = self.service_tiers.iter().flat_map(|services| services.values()).flat_map(|service| std::iter::once(&service.rates).chain(service.tiers.iter().map(|tier| &tier.rates))); + std::iter::once(&self.rates) + .chain(self.tiers.iter().flatten().map(|tier| &tier.rates)) + .chain(services) + .chain(self.windows.iter().flatten().map(|window| &window.rates)) + } + + /// Whether any layer of this price charges for reasoning or per unit; token ranges are in `summary`. + #[must_use] + pub fn charges_beyond_tokens(&self) -> bool { + self.layers().any(|rates| rates.reasoning.is_some_and(|rate| rate > 0.0) || rates.charges_per_unit()) + } + /// Input and output ranges and the special rates of this price, or `None` without base rates. #[must_use] pub fn summary(&self) -> Option { let services = self.service_tiers.clone().unwrap_or_default(); let tiers = self.tiers.as_deref().unwrap_or_default(); let windows = self.windows.as_deref().unwrap_or_default(); - let layers: Vec<&PriceRates> = std::iter::once(&self.rates) - .chain(tiers.iter().map(|tier| &tier.rates)) - .chain(services.values().flat_map(|service| std::iter::once(&service.rates).chain(service.tiers.iter().map(|tier| &tier.rates)))) - .chain(windows.iter().map(|window| &window.rates)) - .collect(); + let layers: Vec<&PriceRates> = self.layers().collect(); let range = |pick: fn(&PriceRates) -> Option| -> Option { let values: Vec = layers.iter().filter_map(|rates| pick(rates)).collect(); pick(&self.rates)?; diff --git a/src/types/models/repository.rs b/src/types/models/repository.rs index 6e135d99..9b12a5e6 100644 --- a/src/types/models/repository.rs +++ b/src/types/models/repository.rs @@ -367,6 +367,8 @@ impl Model { ) OR ( $6 = 'document_reader' + AND COALESCE(m.is_enabled, false) + AND COALESCE(p.is_enabled, false) AND ( COALESCE(sys_mc.capabilities, m.capabilities, '[]'::jsonb) ? 'OCR' OR ( @@ -880,8 +882,7 @@ impl ModelPricing { let Some(effective) = self.effective.as_ref() else { return false; }; - let reasoning = effective.price.rates.reasoning.is_some_and(|rate| rate > 0.0); - reasoning || effective.price.rates.charges_per_unit() || effective.summary.as_ref().is_some_and(|summary| positive(&summary.input) || positive(&summary.output)) + effective.price.charges_beyond_tokens() || effective.summary.as_ref().is_some_and(|summary| positive(&summary.input) || positive(&summary.output)) } /// Prices an estimate for a model at the current time, at the context tier the estimated prompt diff --git a/src/types/rag/documents.rs b/src/types/rag/documents.rs index 849c4ff4..3c3de796 100644 --- a/src/types/rag/documents.rs +++ b/src/types/rag/documents.rs @@ -168,7 +168,7 @@ impl RagDocument { check_embedding_allowed(&state.db, &targets, &embedding.model_id).await?; if detected.is_none() { let config = RagConfig::get(&state.db).await?; - if OcrPlan::load(&state.db, &config, &targets).await?.is_none() { + if OcrPlan::load(&state.db, &config, &base.id).await?.is_none() { return Err(RagError::OcrUnavailable); } } diff --git a/src/types/rag/ingest.rs b/src/types/rag/ingest.rs index 2af2876d..c968070a 100644 --- a/src/types/rag/ingest.rs +++ b/src/types/rag/ingest.rs @@ -249,7 +249,6 @@ async fn claim_pending(pool: &PgPool) -> Result, sqlx::E struct IngestTarget<'a> { config: RagConfig, - targets: ModelTargets, connection: RagConnection, embedding: super::EmbeddingSettings, billing_user: Uuid, @@ -281,7 +280,6 @@ async fn prepare_ingest_target<'a>(state: &'a JobState, doc: &ClaimedDocument) - .map_err(|_| "store_failed")?; Ok(IngestTarget { config, - targets, connection, embedding, billing_user, @@ -396,7 +394,7 @@ async fn extract_or_reuse_text(state: &JobState, doc: &ClaimedDocument, target: } async fn read_document(state: &JobState, doc: &ClaimedDocument, target: &IngestTarget<'_>, bytes: &[u8]) -> Result { - let plan = OcrPlan::load(&state.db, &target.config, &target.targets).await.map_err(|_| "store_failed")?; + let plan = OcrPlan::load(&state.db, &target.config, &doc.knowledge_base_id).await.map_err(|_| "store_failed")?; let reader = plan.zip(doc.uploaded_by); if doc.mime_type.starts_with("image/") { let (plan, user_id) = reader.ok_or("ocr_unavailable")?; @@ -413,24 +411,19 @@ async fn read_document(state: &JobState, doc: &ClaimedDocument, target: &IngestT async fn read_pdf(plan: &OcrPlan, billing: OcrBilling<'_>, document_id: &Uuid, bytes: &[u8]) -> Result { let mut pages = extract::pdf_pages(bytes).await.map_err(|error| error.reason())?; let wanted = plan.pages_to_read(&pages); - let failure = if wanted.is_empty() { - None - } else { - match plan.read_pdf_pages(billing, bytes, &wanted).await { - Ok(read) => { - for (page, text) in read { - if let Some(slot) = pages.get_mut(page.saturating_sub(1) as usize) { - *slot = text.replace('\0', ""); - } - } - None - } - Err(error) => { - tracing::warn!(%document_id, %error, "[JOBS] OCR failed; keeping the extracted text"); - Some(ocr_error(error)) - } + let (read, error) = if wanted.is_empty() { Default::default() } else { plan.read_pdf_pages(billing, bytes, &wanted).await }; + for (page, text) in read { + let text = text.replace('\0', ""); + if !text.trim().is_empty() + && let Some(slot) = pages.get_mut(page.saturating_sub(1) as usize) + { + *slot = text; } - }; + } + let failure = error.map(|error| { + tracing::warn!(%document_id, %error, "[JOBS] OCR failed; keeping the extracted text"); + ocr_error(error) + }); match extract::checked_text(&extract::join_pages(&pages)) { Err(FileError::Empty) => Err(failure.unwrap_or("empty")), other => other.map_err(|error| error.reason()), @@ -440,6 +433,7 @@ async fn read_pdf(plan: &OcrPlan, billing: OcrBilling<'_>, document_id: &Uuid, b fn ocr_error(error: RagError) -> &'static str { match error { RagError::BudgetExceeded => "budget_exceeded", + RagError::OcrUnavailable => "ocr_unavailable", RagError::Database(_) => "store_failed", _ => "ocr_failed", } diff --git a/src/types/rag/ocr.rs b/src/types/rag/ocr.rs index 2a939555..d4fcab23 100644 --- a/src/types/rag/ocr.rs +++ b/src/types/rag/ocr.rs @@ -75,15 +75,16 @@ pub struct OcrPlan { pub reader: OcrReader, kind: ModelKind, prompt: String, + knowledge_base_id: Uuid, } impl OcrPlan { - /// The reader for a knowledge base with model restriction `targets`; `None` while OCR is off, its model is gone or not allowed. + /// The reader for a knowledge base; `None` while OCR is off, its model is gone or not allowed by the base's model restriction. /// /// # Errors /// /// Returns a database error. - pub async fn load(pool: &PgPool, config: &RagConfig, targets: &ModelTargets) -> Result, sqlx::Error> { + pub async fn load(pool: &PgPool, config: &RagConfig, knowledge_base_id: &Uuid) -> Result, sqlx::Error> { let Some(model_id) = config.ocr_model_id.filter(|_| config.ocr_mode != OcrMode::Off) else { return Ok(None); }; @@ -95,7 +96,7 @@ impl OcrPlan { let Some(reader) = OcrReader::of(&kind) else { return Ok(None); }; - if !ModelTargets::allow_outright(pool, std::slice::from_ref(targets), &model_id).await? { + if !allowed(pool, knowledge_base_id, &model_id).await? { return Ok(None); } Ok(Some(Self { @@ -103,9 +104,14 @@ impl OcrPlan { reader, kind, prompt: config.ocr_system_prompt.clone().unwrap_or_else(|| DEFAULT_OCR_PROMPT.to_owned()), + knowledge_base_id: *knowledge_base_id, })) } + async fn check_allowed(&self, pool: &PgPool) -> Result<(), RagError> { + if allowed(pool, &self.knowledge_base_id, &self.kind.model.id).await? { Ok(()) } else { Err(RagError::OcrUnavailable) } + } + /// Reads an image as Markdown, billed to `user_id` as `rag_ocr`. /// /// # Errors @@ -117,7 +123,11 @@ impl OcrPlan { OcrReader::Ocr => self.ocr(billing, OcrDocument::Image { url }, None, 1).await?.into_values().collect::>().join("\n\n"), OcrReader::Vision { .. } => { let part = ContentPart::ImageUrl { url, mime: Some(mime.to_owned()) }; - self.vision(billing, part, "Transcribe this image.", 1).await?.0 + let (text, cut_off) = self.vision(billing, part, "Transcribe this image.", 1).await?; + if cut_off { + return Err(RagError::OcrFailed("cut_off".to_owned())); + } + text } }; let text = text.replace('\0', ""); @@ -130,25 +140,27 @@ impl OcrPlan { pages_to_read(self.mode, self.reader, pages) } - /// Reads the 1-based `pages` of a PDF, billed to `user_id` as `rag_ocr`; returns the Markdown of each page read. - /// - /// # Errors - /// - /// Returns why the budget, the provider or the PDF cutter refused it. - pub async fn read_pdf_pages(&self, billing: OcrBilling<'_>, bytes: &[u8], pages: &[u32]) -> Result, RagError> { + /// Reads the 1-based `pages` of a PDF, billed to `user_id` as `rag_ocr`; returns the Markdown of each page read, and why reading stopped early, + /// when the budget, the provider or the PDF cutter refused a batch (the pages read before it are kept). + pub async fn read_pdf_pages(&self, billing: OcrBilling<'_>, bytes: &[u8], pages: &[u32]) -> (BTreeMap, Option) { match self.reader { OcrReader::Ocr => { let url = format!("data:application/pdf;base64,{}", BASE64.encode(bytes)); let zero_based = pages.iter().map(|page| page.saturating_sub(1)).collect(); - let read = self.ocr(billing, OcrDocument::Document { url }, Some(zero_based), pages.len()).await?; - Ok(read.into_iter().map(|(index, text)| (index + 1, text)).filter(|(page, _)| pages.contains(page)).collect()) + match self.ocr(billing, OcrDocument::Document { url }, Some(zero_based), pages.len()).await { + Ok(read) => (read.into_iter().map(|(index, text)| (index + 1, text)).filter(|(page, _)| pages.contains(page)).collect(), None), + Err(error) => (BTreeMap::new(), Some(error)), + } } OcrReader::Vision { .. } => { let mut read = BTreeMap::new(); for batch in pages.chunks(VISION_BATCH_PAGES) { - read.extend(self.vision_pages(billing, bytes, batch, true).await?); + match self.vision_pages(billing, bytes, batch, true).await { + Ok(batch) => read.extend(batch), + Err(error) => return (read, Some(error)), + } } - Ok(read) + (read, None) } } } @@ -169,6 +181,9 @@ impl OcrPlan { read.extend(Box::pin(self.vision_pages(billing, bytes, second, false)).await?); return Ok(read); } + if cut_off { + return Err(RagError::OcrFailed("cut_off".to_owned())); + } Ok(assign_pages(&text, batch)) } @@ -181,6 +196,7 @@ impl OcrPlan { }, ..TokenEstimate::text(0, 0) }; + self.check_allowed(&billing.state.db).await?; let (admission, metadata) = reserve(billing.state, billing.user_id, &self.kind.model, estimate, "rag_ocr").await?; let request = OcrRequestIR { model: model_ref(&self.kind.model, &self.kind.provider).await?, @@ -197,7 +213,9 @@ impl OcrPlan { async fn vision(&self, billing: OcrBilling<'_>, part: ContentPart, instruction: &str, pages: usize) -> Result<(String, bool), RagError> { let pages = pages as u64; let input = TokenEstimate::input_for_bytes((self.prompt.len() + instruction.len()) as u64).saturating_add(pages.saturating_mul(VISION_INPUT_TOKENS_PER_PAGE)); - let estimate = TokenEstimate::text(input, pages.saturating_mul(VISION_OUTPUT_TOKENS_PER_PAGE)); + let mut estimate = TokenEstimate::text(input, pages.saturating_mul(VISION_OUTPUT_TOKENS_PER_PAGE)); + estimate.units.requests = 1; + self.check_allowed(&billing.state.db).await?; let (admission, metadata) = reserve(billing.state, billing.user_id, &self.kind.model, estimate, "rag_ocr").await?; let mut ir = ChatRequestIR { model: model_ref(&self.kind.model, &self.kind.provider).await?, @@ -236,6 +254,11 @@ impl OcrPlan { } } +async fn allowed(pool: &PgPool, knowledge_base_id: &Uuid, model_id: &Uuid) -> Result { + let targets = ModelTargets::load(pool, std::slice::from_ref(knowledge_base_id)).await?.remove(knowledge_base_id).unwrap_or_default(); + ModelTargets::allow_outright(pool, std::slice::from_ref(&targets), model_id).await +} + /// The 1-based PDF pages `reader` reads in `mode`: every page in `always` mode, else those with almost no text; none for a model that cannot take PDFs. #[must_use] pub fn pages_to_read(mode: OcrMode, reader: OcrReader, pages: &[String]) -> Vec { diff --git a/src/types/rag/repository.rs b/src/types/rag/repository.rs index 0a70c051..4e0f8673 100644 --- a/src/types/rag/repository.rs +++ b/src/types/rag/repository.rs @@ -23,6 +23,15 @@ fn protect(secret: Option<&str>) -> Result, RagError> { .transpose() } +async fn save_ocr(tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, ocr: &OcrSettings) -> Result<(), RagError> { + let prompt = ocr.system_prompt.as_deref().map(str::trim).filter(|prompt| !prompt.is_empty() && *prompt != DEFAULT_OCR_PROMPT); + sqlx::query!("UPDATE rag_config SET ocr_mode = $1, ocr_model_id = $2, ocr_system_prompt = $3", ocr.mode as _, ocr.model_id, prompt) + .execute(&mut **tx) + .await + .map_err(|error| RagError::foreign_key_or(error, RagError::ModelUnavailable))?; + Ok(()) +} + fn to_i32(value: Option) -> Option { value.and_then(|value| i32::try_from(value).ok()) } @@ -83,29 +92,23 @@ impl RagConfig { } } let mut tx = pool.begin().await?; - let (chunk_size, overlap_percent): (i32, i32) = sqlx::query_as( + let saved = sqlx::query!( "UPDATE rag_config SET reranker_model_id = $1, reranker_top_n = $2, default_connection_id = $3, chunk_size = COALESCE($4, chunk_size), chunk_overlap_percent = COALESCE($5, chunk_overlap_percent), reranker_min_score = $6, updated_at = NOW() RETURNING chunk_size, chunk_overlap_percent", + request.reranker.model_id, + to_i32(Some(request.reranker.top_n)), + request.defaults.connection_id, + to_i32(request.chunking.map(|chunking| chunking.chunk_size)), + to_i32(request.chunking.map(|chunking| chunking.overlap_percent)), + request.reranker.min_score, ) - .bind(request.reranker.model_id) - .bind(to_i32(Some(request.reranker.top_n))) - .bind(request.defaults.connection_id) - .bind(to_i32(request.chunking.map(|chunking| chunking.chunk_size))) - .bind(to_i32(request.chunking.map(|chunking| chunking.overlap_percent))) - .bind(request.reranker.min_score) .fetch_one(&mut *tx) .await .map_err(|error| RagError::foreign_key_or(error, RagError::NotFound))?; + let (chunk_size, overlap_percent) = (saved.chunk_size, saved.chunk_overlap_percent); if let Some(ocr) = &request.ocr { - let prompt = ocr.system_prompt.as_deref().map(str::trim).filter(|prompt| !prompt.is_empty() && *prompt != DEFAULT_OCR_PROMPT); - sqlx::query("UPDATE rag_config SET ocr_mode = $1, ocr_model_id = $2, ocr_system_prompt = $3") - .bind(ocr.mode) - .bind(ocr.model_id) - .bind(prompt) - .execute(&mut *tx) - .await - .map_err(|error| RagError::foreign_key_or(error, RagError::ModelUnavailable))?; + save_ocr(&mut tx, ocr).await?; } let chunking = serde_json::json!({ "chunk_size": chunk_size, "overlap_percent": overlap_percent }); let ocr = request.ocr.as_ref().map(|ocr| serde_json::json!({ "mode": ocr.mode, "model_id": ocr.model_id, "custom_prompt": ocr.system_prompt.is_some() })); diff --git a/src/utils/extract.rs b/src/utils/extract.rs index 5787c4a5..5f06c01e 100644 --- a/src/utils/extract.rs +++ b/src/utils/extract.rs @@ -161,11 +161,16 @@ pub fn join_pages(pages: &[String]) -> String { pages .iter() .enumerate() - .map(|(index, page)| format!("\n{}", index + 1, page.trim())) + .map(|(index, page)| format!("\n{}", index + 1, escape_markers(page.trim()))) .collect::>() .join("\n\n") } +/// Page text whose own lines that look like page markers are escaped, so only the marker lines written here split pages. +fn escape_markers(text: &str) -> String { + text.lines().map(|line| if is_page_line(line) { format!("\\{line}") } else { line.to_owned() }).collect::>().join("\n") +} + fn is_page_line(line: &str) -> bool { let line = line.trim(); line.starts_with("") @@ -314,7 +319,7 @@ fn pdf_text(input: &[u8]) -> Option { .iter() .enumerate() .map(|(index, page)| match page { - Some(page) => format!("\n{}", index + 1, page.trim()), + Some(page) => format!("\n{}", index + 1, escape_markers(page.trim())), None => format!("", index + 1), }) .collect();