Repository navigation
[Draft] [WIP] Studio: RAG (knowledge bases, per-thread docs, hybrid search, multimodal) - #5759
Closed
rolandtannous wants to merge 158 commits into
Closed
rolandtannous wants to merge 158 commits into
rolandtannous wants to merge 158 commits into
Conversation
Backend (studio/backend/): - core/rag/: parsers (PDF/TXT/MD/DOCX/HTML via pypdf/python-docx/bs4), recursive token-aware chunker, embeddings singleton via FastSentenceTransformer.from_pretrained(for_inference=True), Qdrant local vector store, bm25s lexical index, RRF hybrid retrieval, spawn-subprocess ingestion job with SSE progress, optional CrossEncoder reranker (off-by-default). - routes/rag.py: KB CRUD, doc upload (KB + per-thread), doc list/delete, ingestion SSE, hybrid+rerank search, thread-index list/clear. - routes/chat_history.py: purge thread RAG artifacts on thread delete and clear-all (rag_documents has no FK cascade to chat_threads so uploads work on un-persisted threads). - studio.db gains 4 RAG tables; storage_roots gains rag_*() helpers. - auth/authentication.py: get_current_subject_sse accepts ?token=... so EventSource can stream ingestion progress. Frontend (studio/frontend/): - features/rag/: api client, Zustand store, hooks, dropzone, KB list, doc rows, ingestion-progress, thread-index list components. - Settings dialog gains a Knowledge Bases tab (master/detail + thread documents list); /knowledge-bases deep-links to it. - features/chat/: per-thread ragSource/enableRerank/ragTopK state in chat-runtime-store; Retrieval section in chat-settings-sheet with KB DropdownMenu (active highlight + per-row trash), thread doc list with Clear-thread-index button, RAG Top K slider, reranker toggle; chat-adapter retrieves before /v1/chat/completions and injects hits as a system block; shared-composer + button routes documents into pendingDocs (auto-uploads, send blocked while indexing).
Replace bare-pypdf/python-docx/BeautifulSoup extraction with Markdown-
preserving parsers so the chunker can split on real heading boundaries
instead of running paragraphs together.
Parsers
- pdf.py: pymupdf + pymupdf4llm.to_markdown() per page; pypdf kept as
fallback when pymupdf can't open the file.
- docx.py: mammoth.convert_to_html() + markdownify, with an explicit
style_map so Title/Heading 1..6 become h1..h6 in the output.
- html.py: BeautifulSoup pre-scrub (drop script/style) then markdownify
so <h*>, <table>, <ul> convert faithfully.
- text.py: signature update only; TXT/MD pass through unchanged.
- parsers/__init__.py: new ParsedImage + ParseResult dataclass; parse()
signature is now parse(path, *, want_images=False) -> ParseResult.
ParseResult is iterable over .pages for backward compat.
Chunker
- chunking.py: prepend Markdown heading separators ("\n# " .. "\n#### ")
to the priority list so heading-aware splits happen for free once the
parsers emit Markdown.
Ingestion
- ingestion.py: single call site updated to consume ParseResult.pages.
Deps (no-torch-runtime.txt)
+ pymupdf>=1.24, pymupdf4llm>=0.0.17, mammoth>=1.7, markdownify>=0.13
- pypdf kept as a fallback path.
Tests
- test_rag_parsers.py asserts Markdown headings survive PDF/DOCX/HTML
extraction; also exercises ParseResult iteration backward-compat.
- test_rag_chunking.py: new case verifying chunks start at Markdown
heading boundaries when the input is Markdown.
Foundation for Phase 3B-late (heading-aware spans for late chunking)
and Phase 3B-multimodal (want_images=True enables image extraction in
the same parser layer). No schema or opt-in flags in this commit.
Phase 3 lays two orthogonal per-KB knobs in the data and API layers so
follow-up commits (Phase 3B-late, Phase 3B-multimodal) only need to add
their code path and UI selector, not schema or types.
Schema (studio/backend/storage/studio_db.py)
- rag_knowledge_bases gains chunking_strategy ('standard'|'late', default
'standard') and mode ('text'|'multimodal', default 'text'). Both are
immutable after KB creation — changing either invalidates existing
chunks because they were ingested through a specific pipeline.
- rag_chunks gains kind ('text'|'image'|'caption', default 'text'),
image_path (NULLABLE), linked_chunk_id (NULLABLE) — used by Phase
3B-multimodal to pair image chunks with their captions.
- Idempotent ALTER TABLE additions for existing installs (mirrors the
chat_threads display_name / *_code_exec_container_id pattern earlier
in the file).
API (studio/backend/routes/rag.py)
- ChunkingStrategy + KBMode Literal aliases.
- CreateKBRequest accepts both fields with backward-compat defaults.
- KBResponse exposes both.
- _validate_mode_combo rejects (multimodal, late) with 400 — no public
open-weight embedder supports both at once. Surface the constraint
early rather than failing silently during ingestion.
Config (studio/backend/utils/rag/config.py)
- RAG_EMBEDDER_MATRIX dict keyed by (mode, strategy) → embedder name.
- resolve_embedder() helper falls back to RAG_EMBEDDING_MODEL for legacy
KBs that pre-date the columns.
- (multimodal, late) intentionally absent.
Frontend (studio/frontend/src/features/rag/)
- api/rag-api.ts: ChunkingStrategy + KBMode types; KnowledgeBase
interface and createKnowledgeBase request type updated.
- stores/rag-store.ts: createKB signature uses the shared request type.
No user-visible UI changes yet — the only currently-usable combination
is (text, standard), so adding one-option selectors would be UX noise.
Phase 3B-late and Phase 3B-multimodal each add the relevant selector
option as part of shipping the code path.
When a KB has chunking_strategy = 'late', ingestion takes a separate code path that embeds the full document in a single forward pass and mean-pools token embeddings per chunk span. Each chunk vector carries full-document context via the encoder's bidirectional attention — Jina's published technique, ~+6.5 nDCG@10 on long docs. Backend - chunking.py: new chunk_pages_with_spans() that joins all pages into a single full_doc, runs the existing recursive splitter, and returns per-chunk (char_start, char_end) offsets. Page-number metadata is recovered by overlap with the original page ranges so PDF citations still work. Existing chunk_pages() unchanged. - embeddings.py: new late_chunk_encode(doc_text, char_spans). Tokenizes the doc with return_offsets_mapping, runs the underlying transformer to get per-token last_hidden_state, then mean-pools per chunk span. When the doc exceeds the embedder's context, falls back to windowed late chunking with a 512-token overlap so cross-window context is partially preserved. - ingestion.py _subprocess_worker: branches on chunking_strategy. 'late' path: chunk_pages_with_spans -> late_chunk_encode -> one big chunks_batch message. 'standard' path unchanged. Both reuse the same parent-side pump. - ingestion.enqueue_ingestion: new chunking_strategy + mode kwargs; defaults to 'standard' / 'text' for legacy callers. embedder model resolved via resolve_embedder() from the (mode, strategy) matrix. - routes/rag.py: KB-doc upload reads chunking_strategy + mode from the KB row (defensive .get for pre-Phase-3 schemas) and threads them through _start_ingestion. Frontend - kb-create-dialog.tsx: new "Chunking strategy" select with Standard / Late options. Embedding-model placeholder switches to nomic when Late is picked. createKB request now carries chunking_strategy. - kb-list.tsx + chat-settings-sheet.tsx: small "⚡ Late" badge next to late-chunking KB names in the settings KB list and the chat sidebar dropdown so users see the mode at a glance. Tests - test_rag_late_chunking.py: pure-python tests for chunk_pages_with_spans (chunks index back into full_doc; page numbers inherited by overlap; pages joined with blank line). A server-marked test loads all-MiniLM-L6-v2 to exercise late_chunk_encode end-to-end. No multimodal yet; that's Phase 3B-multimodal (next PR).
When a KB has mode = 'multimodal', ingestion extracts images alongside
text and embeds both into a shared 512-d vector space via BGE-VL-base.
Image hits become first-class search results — useful for slides,
reports, and diagrams where text-only retrieval loses ~30-50% of the
content.
Backend
- embeddings.py: new encode_images(image_bytes_list) — opens bytes via
PIL and routes to the SentenceTransformer (BGE-VL accepts PIL images
in the same encode call as text).
- ingestion.py: _subprocess_worker gains document_id arg and a new
_stream_image_chunks() helper. For multimodal KBs the standard text
chunking runs first, then images are saved to
rag_uploads_root() / 'images' / <document_id> / img-NNNN.<ext> and
embedded; for each image with an adjacent caption, both an
'image'-kind chunk (vector = encoded image) and a 'caption'-kind
chunk (vector = encoded caption text) are streamed back with a
shared pair_group field.
- ingestion.py parent: _insert_chunks_and_collect_for_bm25 now reads
kind / image_path / pair_group from the subprocess message,
populates the new rag_chunks columns, and runs a second pass that
sets linked_chunk_id for each image ↔ caption pair. BM25 indexes
text + caption chunks only — image chunks have no tokenisable body.
- retrieval.py: Hit gains a `kind` field plumbed through bm25, dense,
RRF, and rerank paths.
- reranker.py: image-kind hits skip CrossEncoder rerank (text-only
model) but are appended back in their original relative position
rather than dropped.
- routes/rag.py: new GET /api/rag/images/{document_id}/{filename}
static-file route with realpath containment check. SearchHit gains
`kind` and `image_url` fields so the chat UI can render image
thumbnails alongside text hits. KB-doc upload threads kind/mode
through to ingestion.
Frontend
- rag-api.ts: SearchHit gains optional `kind` and `image_url`.
- kb-create-dialog.tsx: new Mode select (Text / Multimodal) alongside
the existing Chunking strategy select. The forbidden
(multimodal + late) combo is enforced in the UI — each side
disables the conflicting option on the other side with a tooltip
explaining why. Embedding-model placeholder cycles through the
three valid defaults (bge-small / nomic / BGE-VL).
- kb-list.tsx + chat-settings-sheet.tsx: 🖼️ MM badge alongside the
⚡ Late one so multimodal KBs are obvious at a glance.
Tests
- test_rag_multimodal.py: parser returns images when want_images=True
and skips them when False; _validate_mode_combo rejects the
forbidden (multimodal, late) pair with 400; RAG_EMBEDDER_MATRIX
contains the three valid combos and excludes the forbidden one;
image URL construction shape is verified. A server-marked test
loads BGE-VL-base end-to-end and confirms image + text vectors
share the same dimension.
Phase 3 of the plan is now feature-complete on the backend; the
remaining items (re-ingest UX for changing strategy on existing KBs)
are tracked under "Backfill UX" and can land separately.
Closes the upgrade-path gap from Phase 3: a KB or thread whose chunks
were ingested under one strategy can now be rebuilt under a different
one without losing the uploaded files.
Backend
- routes/rag.py:
- POST /api/rag/knowledge-bases/{kb_id}/reingest takes optional
chunking_strategy / mode / embedding_model in the body. Validates
the (multimodal, late) constraint via _validate_mode_combo, updates
the rag_knowledge_bases row, wipes scope artifacts (sqlite chunks
via cascade, Qdrant collection, bm25), and re-INSERTs a fresh
rag_documents row + ingestion job per stored file. Returns the new
job IDs so callers can stream progress via the existing SSE.
- POST /api/rag/threads/{thread_id}/reingest is the simpler thread
variant — no body, rebuilds with current defaults.
- Shared _reingest_scope helper strips the UUID upload prefix when
re-naming docs so users see the original filenames again.
Frontend
- rag-api.ts: reingestKnowledgeBase(kbId, opts) and
reingestThreadDocuments(threadId) wrappers + ReingestResponse type.
- rag-store.ts: reingestKB / reingestThread actions refresh the KB +
doc lists and subscribe to every returned job so the existing
IngestionProgress chips render without further wiring.
- kb-reconfigure-dialog.tsx (new): mirrors KBCreateDialog but
pre-fills with the KB's current strategy / mode / embedder, enforces
the same (multimodal + late) constraint with disabled options, and
confirms before submitting. Submit label flips between "Re-index"
(no settings change) and "Reconfigure & re-index".
- kb-detail-panel.tsx: header gains the chunking + mode summary and
a "Reconfigure…" button that opens the dialog. Button is disabled
when the KB has no documents.
- chat-settings-sheet.tsx Retrieval section: "Re-index" button beside
the existing "Clear thread index" when the thread has documents.
Tests
- test_rag_reingest.py: ReingestKBRequest accepts optional fields,
rejects unknown enum values via Pydantic, and the shared mode-combo
guard still bites on the reingest path.
Adds a floating progress-card stack mounted at the app root that watches useRagStore.jobs and renders one card per in-flight ingestion job, regardless of which page the user is on. Wraps the existing IngestionProgress component so the progress UI stays consistent with the per-doc chips in the KB detail panel and chat sidebar. - Terminal cards (complete/error) linger for 4s then auto-dismiss. - A manual dismiss button is always available. - Reduced-motion preference is respected (no slide animation). - Positioned bottom-right, z-50, pointer-events-none container so clicks pass through to the page underneath. Mounted in app/routes/__root.tsx next to the existing SettingsDialog so it's visible across every authenticated route. Closes the last deferred item from Phase 2.
Power users can now set their preferred chunking strategy / mode /
embedder once in Settings → Knowledge Bases and have new KBs use those
values by default, instead of toggling on every create.
Backend
- routes/rag.py:
- GET /api/rag/defaults returns the stored RagDefaults (or sensible
fallbacks when nothing is set: standard / text / null embedder).
- PUT /api/rag/defaults is PATCH-style — only fields present in the
body overwrite. The (multimodal, late) constraint is enforced
here too, so users can't poison the defaults with a combination
the create path would reject.
- Persistence reuses the existing chat_settings store via
upsert_chat_settings_merge; the values live under a single
rag.defaults key as a nested JSON dict.
Frontend
- rag-api.ts: getRagDefaults / setRagDefaults wrappers + RagDefaults
+ UpdateRagDefaultsRequest types.
- rag-store.ts: defaults state, loadDefaults / updateDefaults
actions. loadDefaults swallows errors so a missing endpoint just
leaves defaults null.
- rag-defaults-section.tsx (new): self-contained mode + strategy +
embedding-model controls, persists on change. Used in the Settings
KB tab below the ThreadIndexList section.
- knowledge-bases-tab.tsx: mounts RagDefaultsSection below thread
indexes with a separator.
- kb-create-dialog.tsx: loads defaults on open and prefills the form
with them (falls back to hard-coded standard / text when defaults
haven't loaded yet). reset() returns to the latest defaults rather
than the hard-coded ones.
Threads can now opt into late chunking or multimodal mode independently
of the KBs they reference. Per-thread settings persist in chat_settings
under thread:<id>:rag and fall back to the app-level defaults when the
thread hasn't set anything explicitly.
Backend (routes/rag.py)
- ThreadRagSettings / UpdateThreadRagSettingsRequest Pydantic models.
- GET/PUT /api/rag/threads/{thread_id}/settings backed by
chat_settings (upsert_chat_settings_merge). Same (multimodal, late)
constraint enforcement as the create + defaults endpoints.
- POST /api/rag/threads/{thread_id}/reingest now accepts the same
body shape — if any field is set, the new settings are persisted
via set_thread_rag_settings BEFORE the reingest, so subsequent
uploads pick up the change too.
- upload_thread_document reads the per-thread settings and passes
them through to _start_ingestion, replacing the previous hard-coded
('standard', 'text', RAG_EMBEDDING_MODEL) defaults.
Frontend
- rag-api.ts: ThreadRagSettings type + getThreadRagSettings /
setThreadRagSettings wrappers. reingestThreadDocuments now accepts
optional UpdateThreadRagSettingsRequest opts.
- rag-store.ts: threadSettings map keyed by threadId, plus
loadThreadSettings / updateThreadSettings actions. reingestThread
refreshes the local settings copy when opts were supplied.
- chat-settings-sheet.tsx Retrieval section: when source = thread,
shows side-by-side Mode + Chunking selects above the documents
list. Selecting a different value:
- persists immediately if the thread has no docs
- prompts "Re-index N documents?" if docs exist; on Yes calls
reingestThread with the new opts, on No reverts the select
The (multimodal, late) constraint is enforced via per-option
disabled + tooltip, matching the KB create dialog.
@pytest.mark.server integration coverage that drives the ingestion
subprocess in-process and asserts the full multimodal pipeline
produces image + caption chunks with proper kind / image_path /
pair_group metadata. Default pytest runs skip; explicitly:
pytest -m server tests/python/test_rag_multimodal_integration.py
Generates a small PDF (text + PNG figure + caption paragraph) via
pymupdf, points UNSLOTH_STUDIO_HOME at tmp_path, resets the embedder
singleton, and calls _subprocess_worker with mode='multimodal'.
Asserts:
- at least one chunk of each kind (text / image / caption) is emitted
- image chunks carry a real on-disk image_path under tmp_path
- image + caption chunks share a pair_group
A second test confirms BGE-VL produces text and image vectors of the
same dimension — sanity-check for the shared-space assumption that
the multimodal retrieval path relies on.
Downloads BGE-VL-base (~600 MB) on first run, so the test is gated
behind the existing server marker rather than the default suite.
Promotes RAG to a first-class composer toggle alongside Think / Web
Search / Code, with tool-use semantics on local models that support
tools and a pre-fetch fallback on external providers. The model
decides when to call `search_knowledge_base` on local inference; on
external providers retrieval still fires before each message (the
existing pre-fetch path), gated on the same button.
Backend
- core/rag/tool.py (new): search_knowledge_base handler + JSON-schema
tool spec. Resolves scope (kb_id wins over thread_id) from the
request's rag_scope, runs retrieve_hybrid + optional rerank, then
hydrates filename / page_number / text from sqlite and formats as
numbered Markdown citations ('[1] file.pdf (page 5): ...') for the
LLM to cite. Empty scope returns a user-facing hint; empty results
return a clear no-match message instead of an empty string.
- core/inference/tools.py: SEARCH_KNOWLEDGE_BASE_TOOL added to
ALL_TOOLS (lazy import keeps tools.py importable on inference
paths that never touch RAG). execute_tool() gains a tool_context
parameter that carries per-request extras the LLM doesn't see
(currently just rag_scope). The new 'search_knowledge_base' branch
dispatches to the handler with scope unpacked from tool_context.
- core/inference/llama_cpp.py + safetensors_agentic.py +
orchestrator.py: thread tool_context through generate_chat_completion_
with_tools / run_safetensors_tool_loop / execute_tool. Both local
backends (GGUF llama-server and safetensors agentic) carry the same
context object.
- models/inference.py: ChatCompletionRequest gains optional
rag_scope: dict ({kb_id?, thread_id?, enable_rerank?, default_top_k?,
reranker_model?}). Ignored unless 'search_knowledge_base' is in
enabled_tools.
- routes/inference.py: both the GGUF and safetensors call sites for
generate_chat_completion_with_tools forward payload.rag_scope into
tool_context.
Frontend
- chat-runtime-store.ts: global ragToolEnabled boolean + setter +
CHAT_RAG_TOOL_ENABLED_KEY localStorage, mirroring toolsEnabled /
codeToolsEnabled. Settings-hydration migration auto-flips
ragToolEnabled=true for pre-Phase-4 users who already had ragSource
set, so existing RAG users don't silently lose retrieval on upgrade.
- shared-composer.tsx: new 'RAG' pill button after Images (uses
lucide BookOpenIcon, composer-pill-btn style, data-active toggle).
Disabled when no model is loaded. Toggling on from ragSource='off'
auto-flips source to 'thread' so the sidebar lands ready-to-go.
- chat-adapter.ts:
* The existing pre-fetch block is now gated on ragToolEnabled AND
only fires when the tool path isn't viable (external provider OR
local model without tool-use support). Tool-capable local models
skip pre-fetch and let the LLM decide.
* The local-model body assembly adds 'search_knowledge_base' to
enabled_tools and packs ragSource + enableRerank + ragTopK into a
rag_scope object the backend tool handler consumes.
- chat-settings-sheet.tsx: entire Retrieval CollapsibleSection is
wrapped in {ragToolEnabled && ...} so it hides when the button is
off — the button is now the single on/off control. The 'Off'
option is removed from the Source dropdown (the button handles
that). Default open when shown so settings are one click away.
Tests
- test_rag_tool_handler.py: handler covers empty query, missing
scope, kb_id > thread_id precedence, thread-only path, citation
formatting (numbered + page numbers + unknown source); tool spec
shape (function/name/required); execute_tool dispatch with and
without tool_context; ALL_TOOLS includes the new spec without
dropping the existing ones.
Verification scope
- Local GGUF with tools: toggle button on, upload doc, ask about
doc content → assistant emits a search_knowledge_base tool call
card (rendered by the existing ToolFallback component since no
custom UI exists yet — that's a v2 nice-to-have).
- External provider (Anthropic / OpenAI / etc.): same button, same
UX, but uses the pre-fetch path under the hood.
- Migration: pre-existing ragSource != off → button initializes ON
so retrieval keeps working.
Two errors surfaced by the frontend build (`tsc -b`) after the Phase 4 commit c74fc13 landed: src/features/chat/chat-settings-sheet.tsx(449,9): TS2451 — cannot redeclare block-scoped 'activeThreadId'. src/features/rag/stores/rag-store.ts(326,9): TS2774 — condition will always return true since this function is always defined. Fixes - chat-settings-sheet.tsx: an `activeThreadId` declaration already existed near the code-exec section (line 636). Phase 2B's RAG retrieval-section block introduced a second declaration at line 449. The earlier one is needed for the Retrieval block; drop the later redeclaration — downstream code still resolves it via lexical scope. - rag-store.ts subscribeJob: `get().jobUnsubscribers[jobId]` indexes a `Record<string, () => void>`. Without `noUncheckedIndexedAccess` TS infers the result as the function type (never undefined), so `if (existing)` is always-truthy. Replace with `if (jobId in get().jobUnsubscribers) return;` — same semantics, satisfies TS.
Two useEffects added in Phase 2C and Phase 4 followed the anti-pattern of calling a state setter inside the effect and listing the setter's output in the dep array. Both could re-fire indefinitely when the selected slice changed shape on each render — which the chat page hit on first load. chat-settings-sheet.tsx (thread settings loader) - Before: `useEffect(load, [..., threadSettings, ...])` with `if (!threadSettings) load()` inside. After load, the Zustand selector returned a freshly-constructed slice, dep changed, effect re-ran. If anything in between caused threadSettings to briefly flicker undefined (e.g. a race during initial hydration or a fast subsequent thread switch), the load fired again and the cycle repeated. - After: ref-guarded by activeThreadId — `threadSettingsLoadedRef` tracks which threadId has been loaded; the effect deps shrink to `[ragSource.kind, activeThreadId, loadThreadSettings]`, all stable per-thread, removing the feedback loop. ingestion-toast-stack.tsx (terminal-job auto-dismiss) - Before: `useEffect(..., [jobs, dismissedJobs])` with `setDismissedJobs(prev => new Set(prev).add(jobId))` inside the scheduled setTimeout. Each setter creates a new Set reference; the dep change re-triggers the effect, which clears and reschedules timers. Under fast SSE event arrival or a strict-mode double-mount, the scheduler runs faster than its cleanup and React caps the depth. - After: dismissedJobs is read via a ref (kept in sync at the top of the component); the effect only depends on `[jobs]`. A `scheduledJobsRef` prevents duplicate timer scheduling for the same job across multiple effect runs, and the setDismissedJobs updater no-ops when the job is already dismissed. No behavior change for the happy path — toasts still auto-dismiss after DISMISS_DELAY_MS; thread settings still load on first sight of a thread.
Fresh [] literals from useRagStore selectors triggered Zustand's Object.is snapshot check on every render, causing React #185 on the chat page when documentsByScope[key] was unpopulated.
The Phase 4 RAG button only existed in shared-composer; the assistant-ui in-thread composer renders its own pill set, so RAG was missing once a thread had messages.
When ragToolEnabled is on, the in-thread composer's + button now opens a doc-only picker and uploads selected files to the per-thread RAG pipeline (matching SharedComposer). Pending chips show Uploading -> Indexing -> Ready status; Send is blocked while any doc is in-flight. Previously these files were base64'd inline as native attachments, which bypassed RAG entirely.
no-torch-runtime.txt is only consumed in NO_TORCH (Intel Mac GGUF-only) mode, so qdrant-client / bm25s / pymupdf etc. were never installed in the normal install path. Split them into rag.txt and add a step to install_python_stack.py that installs it after studio deps, skipped only when NO_TORCH is set.
- chat-adapter pre-fetches retrieval on every turn when RAG is on, regardless of provider. Users no longer have to phrase queries as 'the document I attached' for retrieval to fire. Local tool models still get search_knowledge_base registered as a refinement path. - New per-thread ragMinScore slider (Min relevance, 0..1) gates retrieved hits by dense cosine similarity. Hits below the floor (and BM25-only hits with no dense signal) are dropped server-side so unrelated docs don't get injected when the user's query is off-topic from what's indexed. - Backend logs at search start (scope, top_k, min_score, query preview), after retrieval (retrieved vs met_threshold counts), and on return (final hit count) for both /api/rag/search and the search_knowledge_base tool path. - System-prompt nudge prepended when pre-fetch returns hits so the model knows to cite [1], [2] rather than paraphrase silently.
tsc -b caught the missing key after the runtime-store addition.
client.search() was removed/renamed to query_points() in qdrant-client 1.10+. Use the new API when available and fall back to search() for older pinned versions.
BGE-VL (multimodal) and nomic-embed-text-v1.5 (late chunking) both ship custom modeling code in their model repos; sentence-transformers refuses to import the referenced module (e.g. bge_vl_clip_transformer) without trust_remote_code=True. Safe to enable because the embedder matrix is config-pinned — users don't supply arbitrary names.
BGE-VL's custom modeling code imports sentence_transformers.base.modules.transformer, which doesn't exist in the 5.2.0 pin. Bump to >=5.3.0,<7 so the new Module package is available.
BGE-VL-base ships a custom Transformer subclass that's tightly coupled to a specific sentence-transformers internal API — it imports a module path missing in older ST and overrides forward() expecting a return shape that changed in newer ST. We can't pin ST to BGE-VL's exact version without risking the training/inference paths that use the same library, so swap the multimodal default to the canonical clip-ViT-B-32 which sentence-transformers wraps natively (no trust_remote_code, no shim, ST-version-independent). Same 512-d shared text+image space.
BGE-VL's sentence-transformers shim (bge_vl_clip_transformer.py) is coupled to specific ST internals and broke across both the 5.2 and 5.3 pin attempts. The canonical load path documented at bge-model.com is transformers.AutoModel with trust_remote_code + model.set_processor() + model.encode(text=/images=). - Wrap that path in _BGEVLAdapter exposing the slice of SentenceTransformer API the ingester uses (encode for text or PIL images, get_sentence_embedding_dimension, best-effort tokenize). - Restore BAAI/BGE-VL-base in RAG_EMBEDDER_MATRIX. - Revert sentence_transformers pin to 5.2.0 — no longer relevant since the multimodal path no longer touches ST.
BGE-VL inherits CLIP's 77-token text positional embedding table — longer chunks crash inside the text model with a shape mismatch. Pre-tokenize with truncation=True, max_length=77 and call get_text_features directly so the high-level encode() (which does not truncate) is bypassed. Log when truncation happens — text chunks beyond the cap are silently cut, so multimodal mode is lossy on the text channel. Image channel is unaffected.
Built on Qwen3 (not CLIP), so the 77-token text cap that bit BGE-VL-base is gone — long chunks embed losslessly. Loads via vanilla SentenceTransformer with trust_remote_code, no custom adapter needed. 2048-d shared text+image space. Adds qwen-vl-utils>=0.0.14 to rag.txt for image preprocessing, required by the Qwen3-VL embedder family.
Qwen3-VL-Embedding-2B's modules.json references sentence_transformers.base.modules, introduced after 5.2.0. Unlike BGE-VL, Qwen3-VL has no fragile custom forward subclass to break against the newer ST internals, so the bump should land cleanly for the multimodal path.
The query was always going through the default text embedder
(bge-small, 384-d) regardless of how the scope was ingested. A
multimodal thread indexed by Qwen3-VL (2048-d) crashed at cosine
similarity with 'shapes (104,2048) and (384,) not aligned'.
Resolve the scope's embedder at search time:
- kb_<id> -> rag_knowledge_bases.embedding_model column
- thread_<id> -> thread settings (with fallback to defaults +
RAG_EMBEDDER_MATRIX matrix lookup)
Pass it through retrieve_hybrid/retrieve_dense to embeddings.encode
so the query lands in the same vector space as the docs. Both the
/api/rag/search route and the search_knowledge_base tool use the
same resolver.
Shorten and condense comments across the RAG backend, frontend, and tests for readability. Comment text only; no code, strings, identifiers, or logic changed. License headers and lint/type pragmas are preserved.
Remove code with no live references, each confirmed dead via AST reference analysis (no production callers and no importers), not just text search: - chunk_belongs_to_document plus its dedicated tests and the now-orphaned _insert_chunk test helper. The preview-target route already does a single-query membership check and deliberately never called this helper. - ingestion-progress.tsx and use-ingestion-events.ts (its only importer). Superseded by the aggregate ingestion toast stack; zero importers. - Unreferenced tests/fixtures/rag-preview sample files and their generator. No behavior change. The only non-deletion edits reword two comments that referenced the removed helper.
Backend: - Deterministic SQLite connection cleanup. The RAG code used bare `with get_connection() as conn:`, which commits but never closes, leaning on GC to release handles (the rest of studio_db closes explicitly). Add a closing_connection() context manager that commits/rolls back like sqlite3's own manager and always closes, and route all 30 RAG call sites through it. - filter_by_min_score no longer drops BM25-only and figure-ref hits. min_score is a cosine floor, so it now gates only hits that carry a dense_score; lexical and figure-ref hits (dense_score is None) pass through instead of being silently discarded when the floor is raised. - Fix two tests that could not pass against the production code: the RRF fusion test asserted the wrong winner (c edges out b: 0.032266 vs 0.032258), and two tool-handler scope tests stubbed retrieve_hybrid without accepting the embedder_model kwarg the handler now passes (TypeError was swallowed, leaving captured["scope"] unset). Frontend: - Removing an in-flight upload chip now routes through the teardown thunk already registered for the aggregate-progress toast (abort, unsubscribe, release the index slot, delete the backend doc with the correct kb/thread scope key it closed over) and clears the toast entry. Deleting directly leaked the concurrency slot and hardcoded the thread scope, mis-targeting KB-scoped docs. Applied in both the composer hook and the compare-view composer; drop the now-vestigial chip-scope-key tracking and unused activeThreadId selectors. Add index-progress-store.remove(id).
Running the RAG suite surfaced three more test-only breakages (production
is correct):
- The scope tests patched `tool.__import__("core.rag.retrieval", ...)`, but a
module has no `__import__` attribute (AttributeError before the stub ran).
tool.py imports retrieval lazily, so patch core.rag.retrieval.retrieve_hybrid
at the source instead.
- test_format_hits_produces_fenced_chunks asserted a stale `score="..."`
attribute; the chunk tag emits chunk_index/tokens, not score.
- The execute_tool dispatch stub rejected the `mode` kwarg the handler passes.
Full RAG suite now: 101 passed, 5 skipped (server-gated model tests).
This was referenced May 31, 2026
- test_safetensors_tool_loop: FakeExecuteTool stub now accepts the tool_context kwarg the loop passes (production is correct). - test_desktop_auth: add rag_router to the health-check router stub so main.py's router import resolves. - test_rag_reingest / test_rag_multimodal: load routes/rag.py by file path instead of `from routes.rag import`, which runs routes/__init__ and eagerly imports the datasets router. On the GPU-less repo-cpu runner the unsloth bootstrap can leave `datasets` half-initialized, making that eager `from datasets import IterableDataset` raise.
# Conflicts: # studio/backend/core/inference/tools.py # studio/frontend/src/components/assistant-ui/sources.tsx # studio/frontend/src/components/assistant-ui/thread.tsx # studio/frontend/src/features/chat/api/chat-adapter.ts # studio/frontend/src/features/chat/chat-settings-sheet.tsx # studio/frontend/src/features/chat/shared-composer.tsx # studio/frontend/src/features/chat/stores/chat-runtime-store.ts
…ystem-prompt unshift)
…ll__ re-exports, unused pytest import
…Dependencies for npm ci
…ctor (single fixed chunker)
…ctor Matches #5910's text-only footprint. Removes image-vector embedding (encode_images, _stream_image_chunks, the _BGEVLAdapter CLIP shim), the multimodal `mode`/KBMode concept + VL embedders (single text embedder now), the mode selector UI across the KB dialogs + thread settings, the MM badges, the /images serving route, and the dead image rendering in the search tool card. Captioning (figure text spliced into markdown) stays — #5910 keeps it too. DB mode/image columns left dormant (no migration). RagDefaultsSection dropped (no controls left).
Drops backfill_document_locators + the /documents/{id}/locators/backfill
route and its response model, the BackfillResult dataclass and the
backfill-only helpers (_scope_for_document, _update_vector_payloads), the
frontend backfillDocumentLocators client, and the backfill/migration
tests. Live preview-highlight locators (pdf_regions_for_chunks, computed
at ingest) are untouched.
# Conflicts: # studio/backend/tests/test_desktop_auth.py # studio/frontend/package-lock.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What it does
bm25sfor the lexical index, sqlite for metadata. All persisted under~/.unsloth/studio/rag/.bge-small-en-v1.5) and multimodal (Qwen3-VL-Embedding-2B, shared text+image vector space). Picked per KB or per thread.(multimodal, late)is forbidden — no embedder supports both.search_knowledge_baseregistered as a tool and pre-fetched context every turn (tool is a refinement path).Uploading → Indexing → Readychips; Send is blocked while anything is in-flight.[1] filename (page X).Tests
tests/python/test_rag_parsers.py,test_rag_chunking.py,test_rag_bm25.py,test_rag_vector_store.py,test_rag_retrieval.py,test_rag_reranker.pytest_rag_late_chunking.py(synthetic-doc cross-validation between standard and late paths)test_rag_multimodal.py+test_rag_multimodal_integration.py(TestClient flow: create multimodal KB → upload PDF with figures → assert text + image chunks → search returns image hit)test_rag_reingest.py(Backfill action)test_rag_tool_handler.py(handler shape, dispatch viaexecute_tool, tool spec OpenAI-compatible, min_score plumbed through)What's NOT in this PR (deliberate exclusions / known limits)
mode = multimodal+chunking = latecombo is rejected — no public open-weight embedder supports both. Enforced in app code (returns 400 at KB-create and re-ingest), not via DB CHECK.RagSearchToolUI— the tool result currently renders through assistant-ui's genericToolFallback(collapsible "Used tool: search_knowledge_base"). A bespoke source-chips card with clickable filenames + jump-to-doc is a clear v2 polish; not blocking.search_knowledge_basecalls. The local-tool path supports refinement queries; external is single-shot pre-fetch._BGEVLAdapterinembeddings.pyis dead code at this point — kept after the Qwen3-VL pivot in case BGE-VL becomes a configurable lighter-weight option. Safe to delete in a follow-up; flagged in the file's docstring.tests/run_all.sh). Not regressing existing CI surface.Test plan
pytest tests/python/test_rag_*.py -vagainst the studio venv.bge-small-en-v1.5after the ST pin bump.Qwen/Qwen3-VL-Embedding-2Bon the HF model card./api/rag/images/{document_id}/{filename}(realpath containment underrag_uploads_root).