Skip to content

Studio: clean-room compact RAG (knowledge bases, hybrid search, fast indexing) - #5910

Merged
danielhanchen merged 165 commits into
mainfrom
studio-rag-clean
Jun 10, 2026
Merged

danielhanchen merged 165 commits into
mainfrom
studio-rag-clean

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jun 1, 2026 •

Copy link
Copy Markdown
Member

Studio RAG, clean-room and compact

A single, clean-room reimplementation of Studio RAG that delivers the union of #5759 (the full RAG
feature) and #5899 (fast indexing), branched fresh off main (which has no RAG today). It targets
roughly a quarter of #5759's line count by re-engineering rather than porting, with fast indexing
built in from day one.

Feature parity: knowledge bases, per-thread documents, many document types, hybrid retrieval, the
search_knowledge_base tool, a RAG composer toggle, citations with PDF region-highlight preview,
and multimodal image captioning. The only feature-level cuts are the off-by-default cross-encoder
reranker and late-chunking (RRF hybrid already covers retrieval quality).

Size

About 5,600 lines of hand-written code across 31 new files plus light wiring into existing files,
versus #5759's ~20.5K. Roughly 73 percent smaller, full user-facing parity.

Area Lines
RAG backend core (store, parsers, chunking, embeddings, retrieval, tool, ingestion, locators, captioner, routes) ~2,400
Backend chat wiring (tool registry + dispatch, rag_scope through both tool loops, nudge) ~250
Backend tests ~900
Frontend RAG feature + tool card + PDF viewer ~2,000
Frontend wiring (composer pill, runtime store, request builder) ~210

What works (all validated end to end in the real Studio UI with a local Unsloth GGUF)

  • Backend core: one rag.db holding documents, chunks, an FTS5 lexical index and a sqlite-vec
    dense index together. Multi-format parsing (PyMuPDF / docx / html / txt / md), token-aware
    chunking with per-page char spans, a warm embedder singleton, RRF hybrid retrieval, and the
    search_knowledge_base tool with a citation source-map.
  • Fast indexing, built in: in-process threaded ingestion reusing the warm embedder (no per-upload
    subprocess reload) and incremental FTS5 (the Nth upload costs O(its own chunks), no scope
    rebuild). Measured 1.6s warm to index the BERT paper in a running Studio.
  • HTTP API (/api/rag): KB CRUD, per-KB and per-thread upload, ingestion job status + SSE,
    document list/delete, and direct hybrid/lexical/dense search. Degrades to 503 if sqlite-vec is
    unavailable so ordinary chat is never affected.
  • Chat integration: an optional rag_scope on the chat request threads through both the GGUF
    (llama.cpp) and safetensors tool loops. The tool is dropped when no scope is present, and a
    RAG-specific system nudge makes the model reliably search attached documents (Qwen3.5-9B goes
    from 1/2 to 2/2 document questions calling the tool and citing the source).
  • Citations with PDF region-highlight preview: the tool surfaces a structured source-map to the
    UI (behind a sentinel, so the model only sees clean <chunk> text). Clicking a citation opens a
    shared side-panel viewer (react-pdf) at the cited page and paints the stored highlight
    rectangles. Regions are computed once at ingest by matching the chunk anchor against the page
    word list (get_text("words")), which is robust to ligatures and dehyphenation where a
    glyph-exact search_for is not. Region coverage on the BERT paper is 100 percent with correct
    placement, and the pdf.js worker resolves and renders inside the bundled app.
  • Multimodal image captioning (optional, RAG_CAPTION_IMAGES=1): when the loaded chat model is
    vision-capable, figure regions are detected (vector drawing clusters + raster placements),
    rendered to PNGs, captioned by the already-loaded model (thinking disabled so content is not
    empty), and the caption text is spliced into the page so the normal text path indexes it. No
    second model and no separate image vector space. Validated with Qwen3.5-9B: 4 BERT figures
    captioned and indexed in 4.2s, for example "This diagram illustrates the pre-training and
    fine-tuning stages of the BERT model".
  • Frontend: a "Docs" composer pill (local-model only), a knowledge-base manager dialog, a
    Retrieval settings section (source, mode, top_k), per-thread upload with SSE status chips, the
    search_knowledge_base tool card with clickable citations, and the lazy-loaded PDF viewer (the
    pdf.js chunk stays out of the main bundle until the first preview).

Design notes

  • add_chunks is incremental; bm25() sign is flipped; FTS5 MATCH returns only matching rows
    with porter stemming. The dense vec0 table is created lazily once the embedding dim is known.
  • The store / ingestion / tool layers are dependency-light and import lazily, so chat never
    depends on RAG and a missing sqlite-vec extension cannot break startup.
  • Scopes are simple strings (kb_<id> / thread_<id>); Studio is single-tenant, so auth gates
    access and there is no per-user data partition.
  • Signed, Range-capable file serving (per-process HMAC token) lets pdf.js issue 206 requests for
    the preview without a bearer.

Validation

  • Backend: 45 RAG unit tests pass (1 skipped, model-download gated). Covers chunking, the unified
    store + incremental FTS5, RRF retrieval and the tool source-map, threaded ingestion + SSE, the
    region locators (including ligature and mid-word anchor cases), the signed preview routes, and
    captioning (gating, grouping, page splice, retrievability).
  • Frontend: tsc -b and vite build are green; the pdf.js worker is emitted as an app asset.
  • End to end in a real Studio instance (Qwen3.5-9B GGUF): model loads in ~5s, the BERT paper
    indexes in 1.6s warm, the model calls search_knowledge_base and answers with citations,
    clicking a citation opens the PDF at the highlighted region, and figure captions are indexed and
    retrievable.

Dependencies added

sqlite-vec, pymupdf, python-docx (backend); react-pdf (frontend). All optional paths are
lazy so the base app is unaffected when they are absent.

Closes the goal of one clean PR that does what #5759 and #5899 do together, without the 20K lines.

shimmyshimmer and others added 3 commits June 1, 2026 01:22
…rieval, tool, fast in-process ingestion)

Clean-room compact RAG core for Studio (branched off main, which has no RAG):

- storage/rag_db.py: rag.db connection factory cloning the providers_db pattern
  (WAL, lazy schema, per-call connections), loading sqlite-vec per connection and
  degrading to RAG_AVAILABLE=False with a clear error if the extension is missing.
- core/rag/store.py: one db holds documents, chunks, knowledge_bases, jobs, an FTS5
  lexical index and a sqlite-vec dense index. add_chunks is incremental (per document,
  no scope-wide rebuild); delete_document cleans chunks+fts+vec in one path.
- core/rag/{parsers,chunking,embeddings,retrieval,tool,ingestion}.py: PyMuPDF/docx/html/
  txt/md parsing (with optional image extraction), token-aware overlap chunking carrying
  page spans for later region locators, a warm SentenceTransformer singleton, RRF hybrid
  retrieval (FTS5 lexical + vec0 dense), the search_knowledge_base tool with a citation
  source-map, and in-process threaded ingestion with SSE job progress (reuses the warm
  embedder, no per-upload subprocess reload).
- rag_root/rag_db_path/rag_uploads_root path helpers; sqlite-vec/pymupdf/python-docx deps.

Tests: 30 passed, 1 skipped (optional real-embedder). Fast indexing is built in from the
start: incremental FTS5 and a reused warm embedder.
- routes/rag.py: /api/rag surface - knowledge-base CRUD, per-KB and per-thread
  document upload, ingestion job status + SSE events, document list/delete, and a
  direct hybrid/lexical/dense search endpoint. All authenticated via
  get_current_subject; returns 503 cleanly when sqlite-vec is unavailable so
  ordinary chat is unaffected.
- register rag_router at /api/rag in main.py + routes/__init__.py.
- lifespan: warm the RAG embedder in a daemon thread next to the GGUF precache,
  so the first upload does not pay the cold model load (non-fatal, gated on
  RAG_AVAILABLE).

End-to-end API smoke (TestClient): create KB, upload, index in ~8s cold, search
in all three modes, delete document and KB - all pass. Full app imports with 12
RAG routes mounted.
yield "data: [DONE]\n\n"

return StreamingResponse(
gen(),

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a comprehensive Retrieval-Augmented Generation (RAG) engine for Unsloth Studio, featuring document parsing, recursive-separator chunking, dense embedding generation, hybrid retrieval using Reciprocal Rank Fusion (RRF), and a unified SQLite store with FTS5 and sqlite-vec. Key feedback highlights critical issues and optimization opportunities, including potential duplicate index entries on document re-ingestion, event loop blocking in FastAPI from synchronous SSE streaming and non-awaited async endpoints, redundant tokenization calls during chunk merging, an N+1 query pattern in document deletion, and potential database locking due to a low SQLite busy timeout.

Comment on lines +190 to +191
"INSERT OR REPLACE INTO chunks("
"id, document_id, scope, chunk_index, text, page_number, "

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

If a document is re-ingested or updated, the chunks table is updated correctly due to INSERT OR REPLACE, but chunks_fts and chunks_vec do not have unique constraints and will accumulate duplicate rows for the same chunk_id. This will pollute search results with duplicate hits. We should perform a bulk delete of any existing chunks for the document before inserting the new ones.

    if len(vectors):
        rag_db.ensure_vec(conn, len(vectors[0]))
    # Bulk delete any existing chunks for this document to prevent duplicate index entries
    conn.execute("DELETE FROM chunks WHERE document_id=?", (document_id,))
    conn.execute("DELETE FROM chunks_fts WHERE chunk_id LIKE ?", (f"{document_id}:%",))
    if rag_db.vec_table_exists(conn):
        conn.execute("DELETE FROM chunks_vec WHERE chunk_id LIKE ?", (f"{document_id}:%",))

Comment on lines +295 to +311
"error": row.get("error"),
}


@router.get("/jobs/{job_id}/events")
def job_events(
job_id: str, subject: str = Depends(get_current_subject)
) -> StreamingResponse:
_require_rag()

def gen():
try:
for event in ingestion.job_events(job_id):
yield f"data: {json.dumps(event)}\n\n"
except Exception as exc: # noqa: BLE001
yield f"data: {json.dumps({'type': 'error', 'error': str(exc)})}\n\n"
yield "data: [DONE]\n\n"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The job_events route is defined as a synchronous def function, but it returns a StreamingResponse with a synchronous generator gen() that blocks on ingestion.job_events(job_id) (which in turn blocks on q.get()). This will completely freeze the entire FastAPI event loop for all users during long-running SSE streams. We should change this to an async def route and use anyio.to_thread.run_sync to run the blocking generator in a thread pool.

@router.get("/jobs/{job_id}/events")
async def job_events(job_id: str, subject: str = Depends(get_current_subject)) -> StreamingResponse:
    _require_rag()
    import anyio

    async def gen():
        iterator = ingestion.job_events(job_id)
        if iterator is None:
            yield "data: [DONE]\n\n"
            return
        try:
            while True:
                event = await anyio.to_thread.run_sync(next, iterator, None)
                if event is None:
                    break
                yield f"data: {json.dumps(event)}\n\n"
        except Exception as exc:  # noqa: BLE001
            yield f"data: {json.dumps({'type': 'error', 'error': str(exc)})}\n\n"
        yield "data: [DONE]\n\n"

    return StreamingResponse(
        gen(),
        media_type="text/event-stream",
        headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
    )

Comment on lines +74 to +104
"""Greedy-merge pieces into <= max_tokens chunks with token overlap.

``starts[i]`` is the char offset of ``pieces[i]`` in the page text. Returns a
list of ``(chunk_text, char_start, char_end)`` where the span covers the raw
(pre-strip) extent of the merged pieces in the source page.
"""
chunks: list[tuple[str, int, int]] = []
buf: list[str] = []
buf_starts: list[int] = []
buf_tok = 0

def _flush() -> None:
raw = "".join(buf)
stripped = raw.strip()
if not stripped:
return
lead = len(raw) - len(raw.lstrip())
trail = len(raw) - len(raw.rstrip())
start = buf_starts[0] + lead
end = buf_starts[0] + len(raw) - trail
chunks.append((stripped, start, end))

for piece, start in zip(pieces, starts):
pt = count(piece)
if buf and buf_tok + pt > max_tokens:
_flush()
carry, carry_starts, run = [], [], 0
for prev, prev_start in zip(reversed(buf), reversed(buf_starts)):
if run + count(prev) > overlap:
break
carry.insert(0, prev)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

In _merge, the token count of each previous piece in the buffer is re-evaluated by calling count(prev) repeatedly during flushes. This results in redundant tokenization calls, which can significantly slow down document ingestion. We can optimize this by caching the token counts in a parallel list buf_toks.

    chunks: list[tuple[str, int, int]] = []
    buf: list[str] = []
    buf_starts: list[int] = []
    buf_toks: list[int] = []
    buf_tok = 0

    def _flush() -> None:
        raw = "".join(buf)
        stripped = raw.strip()
        if not stripped:
            return
        lead = len(raw) - len(raw.lstrip())
        trail = len(raw) - len(raw.rstrip())
        start = buf_starts[0] + lead
        end = buf_starts[0] + len(raw) - trail
        chunks.append((stripped, start, end))

    for piece, start in zip(pieces, starts):
        pt = count(piece)
        if buf and buf_tok + pt > max_tokens:
            _flush()
            carry, carry_starts, carry_toks, run = [], [], [], 0
            for prev, prev_start, prev_tok in zip(reversed(buf), reversed(buf_starts), reversed(buf_toks)):
                if run + prev_tok > overlap:
                    break
                carry.insert(0, prev)
                carry_starts.insert(0, prev_start)
                carry_toks.insert(0, prev_tok)
                run += prev_tok
            buf, buf_starts, buf_toks, buf_tok = carry, carry_starts, carry_toks, run
        buf.append(piece)
        buf_starts.append(start)
        buf_toks.append(pt)
        buf_tok += pt

Comment thread studio/backend/core/rag/store.py Outdated
Comment on lines +223 to +237
"SELECT id FROM chunks WHERE document_id=?", (document_id,)
).fetchall()
]
has_vec = rag_db.vec_table_exists(conn)
for chunk_id in ids:
conn.execute("DELETE FROM chunks_fts WHERE chunk_id=?", (chunk_id,))
if has_vec:
conn.execute("DELETE FROM chunks_vec WHERE chunk_id=?", (chunk_id,))
conn.execute("DELETE FROM chunks WHERE document_id=?", (document_id,))
conn.execute("DELETE FROM documents WHERE id=?", (document_id,))
conn.commit()


# --------------------------------------------------------------------------
# Retrieval primitives

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Executing individual DELETE statements in a loop for each chunk is highly inefficient and acts as an N+1 query pattern. We can optimize delete_document to use a bulk DELETE ... WHERE chunk_id IN (...) query, chunked into batches of 999 to respect SQLite's parameter limit.

Suggested change
"SELECT id FROM chunks WHERE document_id=?", (document_id,)
).fetchall()
]
has_vec = rag_db.vec_table_exists(conn)
for chunk_id in ids:
conn.execute("DELETE FROM chunks_fts WHERE chunk_id=?", (chunk_id,))
if has_vec:
conn.execute("DELETE FROM chunks_vec WHERE chunk_id=?", (chunk_id,))
conn.execute("DELETE FROM chunks WHERE document_id=?", (document_id,))
conn.execute("DELETE FROM documents WHERE id=?", (document_id,))
conn.commit()
# --------------------------------------------------------------------------
# Retrieval primitives
def delete_document(conn: sqlite3.Connection, document_id: str) -> None:
"""Remove a document and all of its chunks (+ fts + vec rows) in one path."""
ids = [
r["id"] for r in conn.execute(
"SELECT id FROM chunks WHERE document_id=?", (document_id,)
).fetchall()
]
has_vec = rag_db.vec_table_exists(conn)
if ids:
limit = 999
for i in range(0, len(ids), limit):
batch = ids[i : i + limit]
placeholders = ",".join("?" * len(batch))
conn.execute(f"DELETE FROM chunks_fts WHERE chunk_id IN ({placeholders})", batch)
if has_vec:
conn.execute(f"DELETE FROM chunks_vec WHERE chunk_id IN ({placeholders})", batch)
conn.execute("DELETE FROM chunks WHERE document_id=?", (document_id,))
conn.execute("DELETE FROM documents WHERE id=?", (document_id,))
conn.commit()

Comment thread studio/backend/routes/rag.py Outdated
Comment on lines +205 to +206
# Documents (KB + per-thread)
# ---------------------------------------------------------------------------

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Defining this endpoint as async def when it only performs synchronous file saving and database operations can block the main event loop. Since there are no await calls inside the function, defining it as a standard synchronous def will instruct FastAPI to run it in an external thread pool, preventing event loop starvation.

Suggested change
# Documents (KB + per-thread)
# ---------------------------------------------------------------------------
@router.post("/knowledge-bases/{kb_id}/documents")
def upload_kb_document(

Comment on lines +236 to +237


Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Defining this endpoint as async def when it only performs synchronous file saving and database operations can block the main event loop. Since there are no await calls inside the function, defining it as a standard synchronous def will instruct FastAPI to run it in an external thread pool, preventing event loop starvation.

Suggested change
@router.post("/threads/{thread_id}/documents")
def upload_thread_document(


db_path = rag_db_path()
ensure_dir(db_path.parent)
conn = sqlite3.connect(str(db_path))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

By default, sqlite3.connect has a very short busy timeout. Under concurrent write/read loads (e.g., multiple concurrent uploads or search + upload), this can easily lead to sqlite3.OperationalError: database is locked errors. It is highly recommended to set a longer busy timeout (e.g., timeout=30.0) to allow SQLite to wait for locks to be released.

Suggested change
conn = sqlite3.connect(str(db_path))
conn = sqlite3.connect(str(db_path), timeout=30.0)

shimmyshimmer and others added 15 commits June 1, 2026 01:45
- register SEARCH_KNOWLEDGE_BASE_TOOL in ALL_TOOLS and dispatch it in execute_tool;
  the spec is duplicated in tools.py (not imported from core.rag) so the tool
  registry never depends on the RAG stack, and execution imports core.rag lazily
  and degrades to a friendly message when sqlite-vec is unavailable.
- add an optional rag_scope ({kb_id?, thread_id?, default_top_k?, min_score?})
  to ChatCompletionRequest; the model only supplies query/top_k, the server
  resolves which documents to search.
- thread rag_scope from the route through both tool loops: the GGUF
  generate_chat_completion_with_tools (llama_cpp) and the safetensors loop
  (inference.py / orchestrator.py -> run_safetensors_tool_loop).
- drop search_knowledge_base from the offered tools when the request carries no
  rag_scope, so the model is never asked to search over nothing.

Verified: with a scope, execute_tool retrieves and returns cited <chunk> blocks;
full app imports with the tool registered.
- core/rag/locators.py: compute per-chunk highlight rectangles once at ingest -
  take a unique anchor phrase from the chunk's page span, confirm it occurs
  exactly once on the rendered PDF page, and map PyMuPDF search_for rects to
  normalized 0..1 coordinates. Conservative: no anchor / non-unique match / no
  PyMuPDF yields an empty region list (never a guessed highlight). This is only
  the live region math; the heavy backfill subsystem from the original PR is
  intentionally dropped (a clean-room branch has no pre-region chunks).
- store: persist regions as pdf_regions_json per chunk; documents carry their
  stored_path for source-file serving.
- ingestion: locate regions for PDFs after embedding and store them.
- routes/rag.py: GET /documents/{id}/preview-target?chunk_id (filename, page,
  regions), /documents/{id}/file-url (short-lived HMAC-signed URL), and
  /documents/{id}/file-signed (token-gated, no bearer, Starlette FileResponse
  handles HTTP Range/206 for pdf.js).

Verified on a real PDF (BERT): chunks carry regions, preview-target returns
page+regions, signed file serving works with Range, bad tokens rejected. 30
unit tests still pass.
Generates a small PDF in-memory with PyMuPDF, ingests it through the real
threaded pipeline (stubbed embeddings), and asserts chunks carry normalized
highlight regions, preview-target returns page + regions, the signed file URL
serves the PDF with HTTP Range, and bad/expired tokens are rejected.
…ations

- features/rag: typed /api/rag client (rag-api.ts) + SSE job stream, a
  per-scope document hook with optimistic pending rows and SSE-driven status, a
  knowledge-base manager dialog (create/list/rename/delete + per-KB upload/list/
  delete with status chips), a Retrieval settings section (source + hybrid/
  lexical/dense mode + top_k), a per-thread upload bar, and a status chip.
- assistant-ui/tool-ui-knowledge-base.tsx: a collapsible search_knowledge_base
  tool card rendering citations as badges with filename/page/snippet popovers
  (the PDF region-highlight viewer is a later phase).
- chat wiring: ragEnabled/ragSource/ragMode/ragTopK runtime state; a 'Docs'
  composer pill (local-model only); chat-adapter pushes search_knowledge_base
  first into enabled_tools and emits rag_scope; the tool card is registered in
  the message part registry; types extended with rag_scope.

~1,635 LoC; vite build green, tsc clean. Reuses existing Studio primitives
(Dialog, Sheet, Select, Slider, Badge, HoverCard, the composer pill pattern).
When a request carries a rag_scope and the search_knowledge_base tool
survives selection, append a RAG-specific instruction to the tool-use
system prompt so the model retrieves from the attached documents and
cites them instead of answering from memory. Mirrored across the GGUF
and safetensors tool loops. End-to-end check with Qwen3.5-9B now calls
the tool on 2/2 document questions (was 1/2).
search_knowledge_base now appends its citation source-map (chunkId,
documentId, filename, page, text, score) after a __RAG_SOURCES__ sentinel.
Both the GGUF and safetensors tool loops strip everything from the
sentinel onward before feeding the result back to the model (mirrors the
existing __IMAGES__ convention), so the model only ever sees the clean
<chunk> text while the frontend can render clickable, region-linked
citations. Adds dispatcher tests for the sentinel split.
Citation badges in the knowledge-base tool card are now clickable: clicking
one opens a shared side-panel viewer that renders the source PDF at the cited
page and overlays the stored highlight regions (normalized rects computed at
ingest). Non-PDF sources fall back to the chunk text.

- preview-store: tiny zustand store driving the single shared viewer.
- document-preview-sheet: react-pdf Document/Page + percentage-positioned
  region overlay, page nav, width-aware scaling; text/annotation layers off.
- document-preview-mount: lazy-loads the pdf.js chunk on first open so the
  ~0.5 MB gzip viewer stays out of the main bundle.
- rag-api: getPreviewTarget / getDocumentFileUrl (signed, Range-capable).
- tool card: parse the __RAG_SOURCES__ source-map into clickable citations.

Adds react-pdf 10.4.1 (pdfjs-dist 5). tsc + vite build green; pdf.worker
asset emitted via new URL(import.meta.url).
The previous locator anchored chunks with page.search_for, which does
glyph-exact matching: it misses ligatures (significant -> fi) and
dehyphenated words, so only ~48% of chunks on a real paper got highlight
regions. Match the chunk's leading anchor against page.get_text("words")
instead -- the same extraction source as the chunk text -- with NFKC
normalization folding ligatures on both sides, dropping boundary-sliced
first/last tokens, and shrinking the anchor to recover a unique match.
Matched words union per line into rectangles. Coverage on BERT 1810.04805
goes from 48% to 100% with correct placement. Adds ligature + mid-word
anchor unit tests.
Adds optional image captioning: when RAG_CAPTION_IMAGES=1 and the loaded
chat model is vision-capable, figure regions are detected (vector drawing
clusters + raster placements via PyMuPDF), rendered to PNGs, captioned by
the already-loaded model, and the caption text is spliced into the page so
the normal FTS5 + dense path indexes it. No separate image vector space and
no second model.

- captioner.py: vision-endpoint discovery off the loaded GGUF backend,
  OpenAI-compatible caption call with thinking disabled (thinking models
  otherwise return empty content), page-grouped captions, splice helper.
- parsers.render_pdf_figures: detect + render figure regions (academic
  figures are vector, so raw raster extraction yields fragments).
- ingestion: caption hook, gated + capped; degrades to a no-op with no
  vision model. Off by default to keep indexing fast.

Validated with Qwen3.5-9B: 4 BERT figures captioned + indexed in 4.2s,
e.g. 'This diagram illustrates the pre-training and fine-tuning stages of
BERT...'. Adds caption gating/grouping/splice + figure-render tests.
The scope-aware import-hoist verifier (scripts/verify_import_hoist.py) flags
newly added re-export imports in modified __init__.py files as unused: __all__
string membership is not a name load, and the verifier only auto-grandfathers
re-exports already present on the base branch. Bind the new rag re-exports
once at module scope so they count as used. No behavior change.
Four fixes for failures the RAG integration introduced:
- inference.py: the Anthropic /v1/messages passthrough read payload.rag_scope,
  but AnthropicMessagesRequest has no such field. Use getattr default None
  (RAG is local-model only).
- test_safetensors_tool_loop: FakeExecuteTool now accepts the rag_scope kwarg
  the loop threads into execute_tool.
- test_rag_retrieval: stub retrieve_hybrid in the no-hits dispatcher test so it
  never reaches the real embedder (runnable without sentence-transformers).
- test_desktop_auth: add rag_router to the routes module stub main.py imports.

All previously failing tests pass; full RAG suite green with
sentence-transformers absent.
Condense multi-line comments and docstrings across the RAG backend, the
inference integration points, and the frontend RAG modules to one or two
clear lines each. No code changes: Python code tokens are identical and the
frontend type-checks and builds unchanged.
@danielhanchen

Copy link
Copy Markdown
Member Author

Live UI validation: clean-room Studio RAG, end to end

Drove this branch's running Studio in a real headless Chromium (Playwright): uploaded documents, toggled the Docs/RAG pill, asked questions, and clicked citations to open the PDF region-highlight preview. Every flow was recorded (video + screenshots). Model: unsloth/Qwen3.5-9B-GGUF (Q4_K_M, vision-capable) served locally via llama-server; 1500x950 viewport.

Results

Flow What it checks Result
Positive (knowledge base) Ask for the renewable-capacity breakdown by technology against an IRENA + EIA energy KB Cites both energy docs; answer gives Solar 1,419 GW / Hydro 1,268 GW / Wind 1,017 GW; clicking the citation opens the IRENA PDF at the cited page with the region highlighted.
Negative (per-thread doc) Upload a USDA agriculture doc, then ask "What is the capital of France?" and "Build an HTML Pacman game with a sloth sprite" Answers correctly (Paris; full HTML game) with zero citations to the agriculture doc - retrieval does not pollute unrelated answers. The model answered France directly ("Thought for 0 seconds").
Multi-doc (KB, 22 docs) Ingest 22 authoritative docs (PDF / DOCX / XLSX / HTML: IRENA, IPCC, USDA, World Bank, arXiv) and route 5 document-specific questions Correct source routing: energy to IRENA/EIA/DOCX, agriculture to the USDA DOCX, energy-access to the HTML, climate to the IPCC PDF (with region highlight). Multi-format retrieval (PDF + DOCX + HTML) all cited.
Figures / charts Ask about chart / infographic content Covered by the IRENA infographic (positive) and the IPCC figure pages (multi-doc): the cited preview opens on the chart page. Image captioning (RAG_CAPTION_IMAGES) is available opt-in; figure detection verified (8 figures found in a sample PDF).

Indexing stayed fast (warm embedder + in-process threaded ingestion + incremental FTS5): about 1.9s for 2 docs and about 28s for the full 22-doc corpus (which includes a 164-page, 31 MB PDF).

Old (#5759) vs new (#5910)

Same query ("renewable capacity breakdown by technology ... cite the source") on both implementations: both retrieve and cite the IRENA document with the same figures. The new build adds the citation to PDF region-highlight preview.

OLD #5759 (feature/rag) NEW #5910 (studio-rag-clean)
Diff vs main +20,520 / 115 files +5,840 / 65 files (about 72% less)
Lexical search bm25s (rebuild per document) SQLite FTS5 (incremental BM25)
Vector store separate store sqlite-vec, in the same rag.db
Extra subsystems cross-encoder reranker, late-chunking, locator backfill none (dropped; RRF hybrid already hits the gold set)
Citation region highlight yes yes (clean-room word-list locator)
Image captioning yes yes (opt-in)
Fast indexing added later in #5899 baked in from day one

Same user-facing feature set, roughly 73% less code, and a simpler single-rag.db architecture (FTS5 + sqlite-vec together).

GIF recordings and screenshots were captured for each flow (positive citation to region preview, negative no-citation, multi-doc routing, and the old-vs-new side by side).

@danielhanchen

Copy link
Copy Markdown
Member Author

Recordings

Real-browser (Playwright) recordings of the flows from the validation above. Model: unsloth/Qwen3.5-9B-GGUF (Q4_K_M) served locally; 1500x950 viewport.

Positive: citation to PDF region-highlight preview

Ask the renewable-capacity breakdown against an IRENA + EIA knowledge base, then click the citation to open the source PDF at the cited page with the region highlighted.

Positive RAG: citation to region preview

Negative: no grounding in an irrelevant document

A USDA agriculture doc is attached to the thread, then "What is the capital of France?" and "Build an HTML Pacman game with a sloth sprite". Both answer correctly with zero citations to the agriculture doc.

Negative RAG: no false citations

Multi-doc routing across 22 documents

A 22-document knowledge base (PDF, DOCX, XLSX, HTML) with document-specific questions routed to the right sources (energy to IRENA/EIA, agriculture to the USDA DOCX, energy-access to the HTML, climate to the IPCC PDF with a region highlight).

Multi-doc routing

Old #5759 vs new #5910 (same query)

Both retrieve and cite the IRENA document with the same figures; the new build adds the citation to region-highlight preview, at about 72% less code.

Old vs new side by side

…icate UX

- Auto-inject retrieved passages before generation when Docs is on and a
  rag_scope is present, gated on a cosine floor (RAG_AUTOINJECT_MIN_SCORE,
  default 0.55; set RAG_AUTOINJECT=0 to disable). Reuses the tool-call
  citation pipeline so the source card and region preview still render.
  This stops web search from hijacking questions answerable from the
  attached documents; web search stays a fallback when the docs lack the
  answer and the Search pill is on.
- De-conflict the tool-use nudge: a RAG-aware action nudge replaces the
  "call web_search for any factual question" line when documents are
  attached (GGUF and safetensors paths).
- Add docs is now clickable on a fresh chat: materialize the thread id via
  threadListItem().initialize() so uploads attach before the first message
  and the conversation reuses the same id.
- Cap the thread document strip height and pin the Add docs button so a
  large document set scrolls instead of covering the conversation.
- Skip duplicate uploads by filename and drop the optimistic chip when the
  backend content-hash dedups, so the same file no longer shows twice.
- Tests for search_for_autoinject and build_rag_autoinject.
On a fresh chat, Add docs materialized the thread id in parallel with opening
the file picker, so a fast first selection could upload into a null scope and
silently attach nothing (especially with multiple files at once). Await the
thread id before opening the picker so the upload scope is always live when
onChange fires; de-dupe the in-flight initialize via a ref.
Identical re-selections are now skipped before any upload or chip (no "Failed"
chip), with a "<file> is already indexed - skipping" toast. Dedup keys on
filename + size + last-modified so an edited file with the same name still
uploads. The backend content-hash dedup remains the authoritative cross-session
check and drops the optimistic chip instead of showing a duplicate.
…eight

The composer is a floating dock over the message viewport, and the viewport
reserved a fixed 160px slack at the bottom. When the document strip makes the
composer taller, the last message slid behind it. Measure the dock height with
a ResizeObserver, expose it as --aui-dock-h, and drive both the bottom spacer
and the scroll-to-bottom offset from it so the conversation always clears the
composer regardless of how many documents are attached.
A document whose ingestion failed (e.g. an unreadable PDF) left a persistent
red "Failed" chip in the attach strip. Remove it instead and surface a
"Couldn't index <file>" toast; also filter failed documents out of the listed
set so a prior-session failure does not reappear on reload. Genuine failures
are still communicated, just not as clutter in the strip.
Multi-file uploads ingest on concurrent daemon threads that share one embedder
singleton. The HuggingFace fast tokenizer uses interior mutability and is not
thread-safe, so concurrent encode/token-count calls panic with
RuntimeError: Already borrowed and the affected files silently fail to index.
Guard encode() and token_counter() with a compute lock so tokenizer access is
serialized. The lock is uncontended for a single document (~0.2% overhead,
output unchanged) and the tokenizer keeps its intra-batch rayon parallelism,
so this is a correctness fix with no measurable slowdown. Adds a concurrency
test that fails without the lock.
Keep TOKENIZERS_PARALLELISM at an explicit "false" at rest (which also silences
the fast tokenizer's forked-after-parallelism warning) and flip it to "true"
only for the duration of a batch encode, where rayon batch-tokenization is a
large speedup. The toggle runs inside the existing compute lock, so it is
serialized and thread-safe. token_counter stays at the default since rayon does
not parallelize a single sequence. Adds a test asserting parallelism is on
during the encode and restored afterward.
Resolve conflicts by keeping both features side by side:
- tools.py: register render_html and search_knowledge_base tools, dispatch both
- routes/inference.py: fold the RAG action nudge into _tool_action_nudge so the
  artifact suffix and RAG-aware base compose
- thread.tsx: keep both KnowledgeBase and RenderHtml tool UIs plus the Docs and
  Artifacts composer toggles
- shared-composer.tsx: keep both Docs and Artifacts pills
- chat-adapter.ts: union the tool-enable guard over RAG and render_html
Reformat the RAG backend modules to the line-length-100 house style
introduced on main, so the branch carries no formatting drift against
the reformatted base.
# Conflicts:
#	studio/backend/core/inference/llama_cpp.py
#	studio/backend/core/inference/tools.py
#	studio/backend/routes/inference.py
#	studio/frontend/src/components/assistant-ui/model-selector/pickers.tsx
#	studio/frontend/src/components/assistant-ui/thread.tsx
#	studio/frontend/src/features/chat/shared-composer.tsx
…rash

A float top_k (from the model tool-call arguments or the sidebar
default_top_k) reached _rrf and broke the result slice with
"slice indices must be integers". Coerce at the source in
_search_knowledge_base via _opt_int, and defensively in
retrieve_hybrid so every caller passes an int.
@danielhanchen

Copy link
Copy Markdown
Member Author

Fixed a crash in search_knowledge_base: a float top_k (from the model
tool-call arguments or the sidebar default_top_k) reached the RRF stage, so
the result slice failed with TypeError: slice indices must be integers.

Coerced top_k to int in two places:

  • _search_knowledge_base (tools.py): resolve via _opt_int, matching the auto-inject path.
  • retrieve_hybrid (retrieval.py): int(k) before any retrieval, so every caller (tool call, auto-inject, /api/rag/search) is covered.

Replace the post-load .half() with model_kwargs={"torch_dtype": "float16"} on
the SentenceTransformer constructor, and load in fp16 on CPU as well as GPU.
Filter the RAG embedder (EMBEDDING_MODEL / EMBED_GGUF_REPO basenames, GGUF and
non-GGUF) out of the local, cached-gguf, and cached-models endpoints so it does
not appear in the Select model / Downloaded lists.
When llama-server fails because the model's chat template raised (e.g. the
Llama 3.x "This model only supports single tool-calls at once!" guard), append
that message to "An internal error occurred:" -- but only when it appears
verbatim in the loaded model's chat template, so arbitrary llama-server text is
never surfaced.
Switch the clip button from text-muted-foreground/90 to text-foreground/80 so
the "Attach documents for retrieval" control reads with more contrast instead of
a faint gray.
Add a left-edge drag handle to the RAG document preview so it can be widened
(it is right-anchored, so dragging left enlarges it). Width is clamped between
24rem and 95vw, persisted in localStorage, and double-click resets to the
default 44rem.
Rename the citation header from "Sources" to "Document Sources" and update the
knowledge-base tool summary's cross-reference to match.
Serve the F16 embedder from the unsloth-hosted repo (weight-identical to the
prior CompendiumLabs F16) by default. Override with RAG_EMBED_GGUF_REPO.
…bedder tests torch-free

thread.tsx / shared-composer.tsx: show Compare chat as a top-level tools-menu
item instead of nesting it under More, so it stays one click away and the chat
UI smoke test finds it.

test_rag_embed_llama_server: stub the sentence-transformers load in the
backend-selection tests so they assert which backend is picked without importing
sentence-transformers, which the torch-free backend CI does not install.
Resolve tool-loop conflicts by adopting main's ToolLoopController (#5962) and
re-layering the RAG-specific pieces on top: the per-turn knowledge-base search
cap, rag_scope passthrough to execute_tool, the forced first-pass RAG
autoinject, and stripping the __RAG_SOURCES__ sentinel before the model sees a
result. Drop the now-redundant inline duplicate/render_html nudges and the
obsolete test they covered (the scenario stays covered by main's tests).
Keep-both for the tool-loop signature/call sites: RAG's rag_scope alongside
main's new seed and disable_parallel_tool_use (#6010, #6115).
…thread starts

The lifespan hook starts the RAG embedder warm-up via threading.Thread,
but after the recent merge the only 'import threading' was local to a
different helper, leaving threading undefined in the lifespan scope. That
raised NameError on every server boot and failed application startup. Move
the import to module scope so the warm-up thread starts cleanly.
When only search_knowledge_base is enabled, _build_tool_action_nudge
returns an empty string, so the RAG nudge falls back to prefixing the
current date. The merge dropped the _date_line/_sf_date_line definitions
while keeping their use, leaving them undefined in openai_chat_completions.
Restore both definitions next to their use.
@danielhanchen
danielhanchen marked this pull request as ready for review June 10, 2026 04:16
@danielhanchen
danielhanchen merged commit 8848a31 into main Jun 10, 2026
46 of 47 checks passed
@danielhanchen
danielhanchen deleted the studio-rag-clean branch June 10, 2026 04:17

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b16a743e52

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/main.py
Comment on lines +759 to +763
app.include_router(prompts_router, prefix = "/api/prompts", tags = ["prompts"])
app.include_router(datasets_router, prefix = "/api/datasets", tags = ["datasets"])
app.include_router(data_recipe_router, prefix = "/api/data-recipe", tags = ["data-recipe"])
app.include_router(export_router, prefix = "/api/export", tags = ["export"])
app.include_router(rag_router, prefix = "/api/rag", tags = ["rag"])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Add new APIs to the body-size middleware

These new /api/prompts and /api/rag routers add POST/PATCH endpoints, including multipart RAG document uploads, but MaxBodyMiddleware only runs for paths in _BODY_PROTECTED_PREFIXES and these prefixes are not added there (nor is the RAG upload path added to the upload passthrough list). In that configuration, large prompt imports or document uploads bypass the configured request caps and can stream arbitrary data into memory/disk; add these prefixes and a RAG upload passthrough cap when mounting the routers.

Useful? React with 👍 / 👎.

Comment on lines +168 to +174
if existing is not None:
job_id = _new_job(conn, existing, scope, status = "completed", progress = 1.0)
with _jobs_lock:
_jobs[job_id] = queue.Queue()
_emit(job_id, {"type": "complete", "num_chunks": 0, "deduped": True})
_emit(job_id, None)
return existing, job_id

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Remove duplicate uploads after dedupe

When a user uploads content that is already indexed in the same scope, _save_upload() has already written the new file to a fresh stored_path, but this dedupe branch returns the existing document without deleting that just-written file. Repeated duplicate uploads therefore leave full orphaned copies under the RAG uploads directory; unlink stored_path before returning from this branch.

Useful? React with 👍 / 👎.

Comment on lines +210 to +216
_qStoreUnsub = useChatRuntimeStore.subscribe((state) => {
if (!_qIsRunning) { _qStopSubscription(); return; }
const isRunning = Object.keys(state.runningByThreadId).length > 0;
const wasRunning = _qPrevStoreRunning;
_qPrevStoreRunning = isRunning;
if (wasRunning && !isRunning) {
_qAdvance();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Track the queued thread instead of global runs

The prompt queue advances when the global runningByThreadId map transitions from non-empty to empty, not when the queued prompt's own thread finishes. If another chat/compare pane is running while a prompt list is started, that unrelated run can keep the map non-empty after the queued run ends (stalling the queue) or can finish before the queued run starts (advancing early); store the queued thread id and watch that key instead of Object.keys(...).length.

Useful? React with 👍 / 👎.

Comment on lines +771 to +777
top_k = _opt_int((arguments or {}).get("top_k") or scope.get("default_top_k"))
text, sources = search_knowledge_base_with_sources(
query = str(query),
scope_kb_id = scope.get("kb_id"),
scope_thread_id = scope.get("thread_id"),
top_k = top_k,
**_scope_retrieval_kwargs(scope),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Clamp model-supplied top_k before retrieval

The model controls top_k in the search_knowledge_base tool call, and this value is forwarded without the 1..50 API cap or the UI's 1..20 cap. In dense or lexical retrieval mode it becomes the SQLite LIMIT, so a malformed/negative or very large tool argument can return far more passages than intended and bloat the next prompt; clamp invalid values back to the scoped/default limit before calling retrieval.

Useful? React with 👍 / 👎.

Comment on lines +36 to +40
def _require_rag() -> None:
if not rag_db.RAG_AVAILABLE:
raise HTTPException(
status_code = 503,
detail = "RAG is unavailable: the sqlite-vec extension could not be loaded.",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Return 503 when sqlite-vec fails to load

_require_rag() only checks whether sqlite_vec imported, but every endpoint then calls rag_db.get_connection(), which can still raise when sqlite_vec.load(conn) fails for the installed wheel/platform. In that case these routes return an unhandled 500 instead of the documented 503/unavailable response, so catch the connection-load failure here or map get_connection() failures to the same HTTPException.

Useful? React with 👍 / 👎.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants