Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Fix RAG fallback for oversized chat attachments (#9630)
Maxim Supersynergyf3e41f4eb6ef
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex f22423605ef..7027be2ad6a 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -10996,6 +10996,12 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> dilean_k = _autoinject_top_k()sidebar_k = _opt_int(rag_scope.get("default_top_k"))top_k = min(sidebar_k, lean_k) if sidebar_k is not None else lean_k+ budget: int | None = None+ # The window the budget was sized against, so `_text_token_cost` only trusts+ # a GGUF actually serving this same window.+ ctx_tokens = (+ _opt_int(rag_scope.get("context_length") or rag_scope.get("max_context_tokens")) or 0+ )# Whole-document mode: a thread-attached file under budget is injected in# full. A KB selection is exclusive so whole-doc never preempts it; project@@ -11004,11 +11010,7 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> diif whole_doc_requested:try:budget = _whole_doc_budget(rag_scope, conversation)-- whole = whole_document_context(- scope_thread_id = thread_id,- max_tokens = budget,- )+ whole = whole_document_context(scope_thread_id = thread_id, max_tokens = budget)except Exception as exc: # noqa: BLE001logger.warning("RAG whole-document context failed: %s", exc)whole = None@@ -11035,22 +11037,87 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> ditext = merged_textlogger.info("RAG auto-inject: whole-document context (%d chunk(s))", len(sources))- if text is None and enabled:+ def _fits(candidate_text, max_tokens) -> bool:+ # None means the estimate itself failed, so there is nothing to enforce.+ # Zero is the opposite: a measured "no room left".+ if max_tokens is None:+ return True+ if max_tokens <= 0:+ return False+ # Priced by the serving GGUF when it can, doubled when it cannot. The+ # doubling is what stops dense ASCII (source, minified JSON, hashes, all+ # nearer two characters per token) being charged the English four.+ return _text_token_cost(candidate_text, ctx_tokens) <= max_tokens++ def _trim(hit_text, hit_sources, max_tokens):+ """Drop passages from the tail until the rendered block fits, else None.++ Re-renders only when something is dropped, so an untrimmed result comes+ back exactly as retrieval built it.++ None when not even the top passage fits: the block joins the current+ turn, which the window may not evict, so an overflowing injection fails+ the request rather than degrading the answer. Losing the attachment is+ what this branch exists to prevent, but main already loses it here, and+ that beats an error instead of an answer.+ """+ kept, rendered = list(hit_sources), hit_text+ while len(kept) > 1 and not _fits(rendered, max_tokens):+ kept = kept[:-1]+ rendered = render_sources(kept)+ return (rendered, kept) if _fits(rendered, max_tokens) else None++ def retrieve(*, max_tokens = None, **scope):+ found = search_for_autoinject(query = query, top_k = top_k, **scope)+ return _trim(found[0], found[1], max_tokens) if found else None++ # An oversized thread attachment is mandatory grounding: with auto-injection+ # off, search it alone, without the optional-auto relevance floor, then add+ # project context if the combination still fits. The budget binds on that+ # path only -- with auto-injection on this stays the single combined+ # unbudgeted search, so a small context cannot silently switch RAG off.+ if text is None and (enabled or whole_doc_requested):try:- found = search_for_autoinject(- query = query,- scope_kb_id = rag_scope.get("kb_id"),- scope_thread_id = rag_scope.get("thread_id"),- scope_project_id = rag_scope.get("project_id"),- top_k = top_k,- min_dense_score = floor,- **_scope_retrieval_kwargs(rag_scope),- )+ if whole_doc_requested and not enabled:+ found = retrieve(+ max_tokens = budget,+ scope_thread_id = thread_id,+ min_dense_score = None,+ **_scope_retrieval_kwargs(rag_scope),+ )+ project_id = rag_scope.get("project_id")+ if found and project_id:+ # Isolated like the whole-document companion above: an+ # unavailable project index must not send the shared handler+ # below into discarding thread grounding already in hand.+ try:+ proj = retrieve(+ scope_project_id = project_id,+ min_dense_score = floor,+ **_scope_retrieval_kwargs(rag_scope),+ )+ except Exception as exc: # noqa: BLE001+ logger.warning("RAG project retrieval (fallback companion) failed: %s", exc)+ proj = None+ if proj:+ # Trim the combination, not the project alone, which was+ # never entitled to the whole budget. The tail is all+ # project, so what fits beside the thread result survives.+ merged = found[1] + proj[1]+ found = _trim(render_sources(merged), merged, budget) or found+ else:+ found = retrieve(+ scope_kb_id = rag_scope.get("kb_id"),+ scope_thread_id = thread_id,+ scope_project_id = rag_scope.get("project_id"),+ min_dense_score = floor,+ **_scope_retrieval_kwargs(rag_scope),+ )except Exception as exc: # noqa: BLE001logger.warning("RAG auto-inject retrieval failed: %s", exc)return Noneif not found:- logger.info("RAG auto-inject: no passage >= %.2f; skipping", floor)+ logger.info("RAG auto-inject: no matching passage; skipping")return Nonetext, sources = foundif text is None:diff --git a/studio/backend/core/rag/tool.py b/studio/backend/core/rag/tool.pyindex e4494f0c1fa..671ea3847ef 100644--- a/studio/backend/core/rag/tool.py+++ b/studio/backend/core/rag/tool.py@@ -264,16 +264,16 @@ def search_for_autoinject(scope_thread_id: str | None = None,scope_project_id: str | None = None,top_k: int | None = None,- min_dense_score: float = 0.70,+ min_dense_score: float | None = 0.70,model_name: str | None = None,mode: str = "hybrid",) -> tuple[str, list[dict]] | None:"""Forced-retrieval variant for auto-injection.Returns ``(rendered_text, sources)`` only if some hit's cosine clears- ``min_dense_score``, else ``None`` (inject nothing). The dense gate keeps- weak/off-topic matches out of answers. In ``lexical`` mode hits carry no- cosine, so the gate falls back to a dense 1-NN probe.+ ``min_dense_score``, else ``None`` (inject nothing). ``None`` keeps the+ retrieved top-K without the optional-auto relevance gate. In ``lexical``+ mode gated hits fall back to a dense 1-NN probe."""if not query or not query.strip():return None@@ -291,10 +291,14 @@ def search_for_autoinject(model_name = model_name,mode = mode,)- strong = [- h for h in hits if h.dense_score is not None and h.dense_score >= min_dense_score- ][:k]- if not strong and hits and mode == "lexical":+ strong = (+ hits[:k]+ if min_dense_score is None+ else [+ h for h in hits if h.dense_score is not None and h.dense_score >= min_dense_score+ ][:k]+ )+ if min_dense_score is not None and not strong and hits and mode == "lexical":probe = retrieval.retrieve_dense(conn, scope, query, 1, model_name = model_name)if (probediff --git a/studio/backend/tests/test_rag_retrieval.py b/studio/backend/tests/test_rag_retrieval.pyindex d302848df9b..a2b8ffb7313 100644--- a/studio/backend/tests/test_rag_retrieval.py+++ b/studio/backend/tests/test_rag_retrieval.py@@ -511,6 +511,13 @@ def test_build_rag_autoinject_scope_overrides_env(monkeypatch):assert seen["min_dense_score"] == 0.8assert seen["mode"] == "dense"- # Explicit False disables even with the env default on.+ # The UI's explicit Off sends both flags. autoinject=False on its own is also+ # used by large-model Auto and must still allow thread-document grounding.monkeypatch.setenv("RAG_AUTOINJECT", "1")- assert tools.build_rag_autoinject(conv, {"thread_id": "t1", "autoinject": False}) is None+ assert (+ tools.build_rag_autoinject(+ conv,+ {"thread_id": "t1", "autoinject": False, "whole_doc": False},+ )+ is None+ )diff --git a/studio/backend/tests/test_rag_whole_document.py b/studio/backend/tests/test_rag_whole_document.pyindex 545d731fd27..22cea564d42 100644--- a/studio/backend/tests/test_rag_whole_document.py+++ b/studio/backend/tests/test_rag_whole_document.py@@ -263,6 +263,275 @@ def test_build_rag_autoinject_falls_back_over_budget(rag_conn, monkeypatch):assert _injected_text(result) == "TOPK_FALLBACK_TEXT"+def test_build_rag_autoinject_large_model_auto_falls_back_over_budget(rag_conn, monkeypatch):+ # The frontend resolves Auto to autoinject=False for models over 9B. Thread+ # attachments still request whole-doc context, so an oversized document must+ # fall back to top-K instead of disappearing from the model request.+ scope = store.thread_scope("t1")+ _add_doc(rag_conn, scope, "d1", "big.pdf", "h1", ["overflow"], tokens = [50_000])++ sentinel = (+ "TOPK_LARGE_MODEL_FALLBACK",+ [{"citationId": 1, "filename": "big.pdf", "text": "x"}],+ )+ monkeypatch.setattr(tool, "search_for_autoinject", lambda **kw: sentinel)++ result = inf_tools.build_rag_autoinject(_convo(), {"thread_id": "t1", "autoinject": False})+ assert result is not None+ assert _injected_text(result) == "TOPK_LARGE_MODEL_FALLBACK"+++def test_build_rag_autoinject_fallback_is_thread_first_and_budgeted(rag_conn, monkeypatch):+ monkeypatch.setattr(tool, "whole_document_context", lambda **kw: None)+ calls = []++ def fake_search(**kw):+ calls.append(kw)+ if kw.get("scope_thread_id"):+ if kw.get("scope_project_id") or kw.get("min_dense_score") is not None:+ return None+ sources = [+ {"citationId": i, "filename": "thread.txt", "text": "x" * 1600}+ for i in range(1, kw["top_k"] + 1)+ ]+ else:+ sources = [{"citationId": 1, "filename": "project.txt", "text": "project"}]+ return tool.render_sources(sources), sources++ monkeypatch.setattr(tool, "search_for_autoinject", fake_search)+ result = inf_tools.build_rag_autoinject(+ _convo("summarize the attached document"),+ {+ "thread_id": "t1",+ "project_id": "p1",+ "autoinject": False,+ "context_length": 3000,+ "response_headroom": 1024,+ },+ )++ injected = _injected_text(result)+ assert "x" * 1600 in injected and "project" in injected+ # The thread is searched alone and ungated, then the project once: one query+ # embedding per scope, with the over-budget passages trimmed from the result+ # rather than re-searched at a smaller top_k.+ assert [(c.get("scope_thread_id"), c.get("scope_project_id")) for c in calls] == [+ ("t1", None),+ (None, "p1"),+ ]+ assert calls[0]["min_dense_score"] is None+ assert calls[0]["top_k"] == 4+ # 3000 context - 1024 headroom - prompt - 512 overhead leaves room for one+ # 1600-char passage plus the project hit, not for all four.+ assert injected.count("x" * 1600) == 1+++def test_build_rag_autoinject_zero_budget_still_grounds(rag_conn, monkeypatch):+ # With auto-injection ON the fallback is unbudgeted, so a context too small+ # to leave any whole-doc budget must not silently drop the attachment.+ _add_doc(+ rag_conn, store.thread_scope("t1"), "d1", "big.pdf", "h1", ["overflow"], tokens = [50_000]+ )+ sentinel = ("TOPK_ZERO_BUDGET", [{"citationId": 1, "filename": "big.pdf", "text": "x"}])+ monkeypatch.setattr(tool, "search_for_autoinject", lambda **kw: sentinel)++ for scope in (+ # A context smaller than headroom + overhead.+ {"thread_id": "t1", "autoinject": True, "context_length": 1200},+ {"thread_id": "t1", "autoinject": True, "context_length": 512},+ # Headroom at or above the whole context: same zero budget.+ {"thread_id": "t1", "autoinject": True, "context_length": 8192, "response_headroom": 8192},+ {+ "thread_id": "t1",+ "autoinject": True,+ "context_length": 2048,+ "response_headroom": 999_999,+ },+ # A sidebar top-K of 0 must not be read as "already at the minimum".+ {"thread_id": "t1", "autoinject": True, "context_length": 2048, "default_top_k": 0},+ ):+ result = inf_tools.build_rag_autoinject(_convo(), scope)+ assert result is not None, scope+ assert _injected_text(result) == "TOPK_ZERO_BUDGET", scope+++def test_build_rag_autoinject_refuses_when_not_even_one_passage_fits(rag_conn, monkeypatch):+ # The block joins the current turn, which the rolling window may not evict, so+ # admitting a passage that does not fit fails the whole request instead of+ # degrading the answer. When nothing fits, inject nothing, which is what main+ # does on this path anyway.+ _add_doc(+ rag_conn, store.thread_scope("t1"), "d1", "big.pdf", "h1", ["overflow"], tokens = [50_000]+ )++ def fake_search(**kw):+ sources = [+ {"citationId": 0, "filename": "thread.txt", "text": "T" * 2000}+ for _ in range(kw["top_k"] or 4)+ ]+ return tool.render_sources(sources), sources++ monkeypatch.setattr(tool, "search_for_autoinject", fake_search)+ scope = {"thread_id": "t1", "autoinject": False, "context_length": 1200}+ assert inf_tools._whole_doc_budget(scope, _convo()) == 0+ assert inf_tools.build_rag_autoinject(_convo(), scope) is None+ # Auto-injection ON is the pre-existing unbudgeted path and is unaffected.+ assert (+ inf_tools.build_rag_autoinject(+ _convo(), {"thread_id": "t1", "autoinject": True, "context_length": 1200}+ )+ is not None+ )+++def test_build_rag_autoinject_enabled_path_stays_unbudgeted(rag_conn, monkeypatch):+ # With auto-injection ON the fallback is the pre-existing one: a single+ # combined search, no whole-doc budget clamp. A long thread or a small+ # context must not shrink or cancel it.+ _add_doc(+ rag_conn, store.thread_scope("t1"), "d1", "big.pdf", "h1", ["overflow"], tokens = [50_000]+ )+ calls = []++ def fake_search(**kw):+ calls.append(kw)+ sources = [+ {"citationId": i, "filename": "thread.txt", "text": "y" * 6000}+ for i in range(1, (kw["top_k"] or 4) + 1)+ ]+ return tool.render_sources(sources), sources++ monkeypatch.setattr(tool, "search_for_autoinject", fake_search)+ long_thread = [+ {"role": "user", "content": "x " * 6000},+ {"role": "assistant", "content": "ok"},+ {"role": "user", "content": "summarize the attached document"},+ ]+ result = inf_tools.build_rag_autoinject(+ long_thread, {"thread_id": "t1", "autoinject": True, "context_length": 8192}+ )+ assert result is not None+ assert _injected_text(result).count("y" * 6000) == 4+ assert len(calls) == 1+ assert calls[0]["min_dense_score"] == inf_tools._autoinject_floor()+++def test_build_rag_autoinject_off_does_not_inject_project_alone(rag_conn, monkeypatch):+ # The fallback exists to rescue the thread attachment. With auto-injection+ # off and nothing found in the thread, project context is not a substitute:+ # injecting it would be grounding the user never asked for.+ _add_doc(+ rag_conn, store.thread_scope("t1"), "d1", "big.pdf", "h1", ["overflow"], tokens = [50_000]+ )++ def fake_search(**kw):+ if kw.get("scope_thread_id"):+ return None+ sources = [{"citationId": 1, "filename": "project.txt", "text": "project"}]+ return tool.render_sources(sources), sources++ monkeypatch.setattr(tool, "search_for_autoinject", fake_search)+ assert (+ inf_tools.build_rag_autoinject(+ _convo(), {"thread_id": "t1", "project_id": "p1", "autoinject": False}+ )+ is None+ )+++def test_build_rag_autoinject_keeps_thread_hits_when_project_retrieval_raises(+ rag_conn, monkeypatch+):+ # The project lookup is an optional companion. An unavailable project index+ # must not discard the thread grounding already in hand, which would put the+ # attachment right back where this fallback found it.+ _add_doc(+ rag_conn, store.thread_scope("t1"), "d1", "big.pdf", "h1", ["overflow"], tokens = [50_000]+ )++ def fake_search(**kw):+ if kw.get("scope_project_id"):+ raise RuntimeError("project index unavailable")+ sources = [{"citationId": 1, "filename": "thread.txt", "text": "THREAD_GROUNDING"}]+ return tool.render_sources(sources), sources++ monkeypatch.setattr(tool, "search_for_autoinject", fake_search)+ result = inf_tools.build_rag_autoinject(+ _convo(), {"thread_id": "t1", "project_id": "p1", "autoinject": False}+ )+ assert result is not None+ assert "THREAD_GROUNDING" in _injected_text(result)+++def test_build_rag_autoinject_keeps_the_project_hits_that_fit(rag_conn, monkeypatch):+ # Trimming the combination, not the project alone: when thread plus all of the+ # project overflows, the passages that do fit beside the thread result are kept+ # instead of every project passage being dropped.+ _add_doc(+ rag_conn, store.thread_scope("t1"), "d1", "big.pdf", "h1", ["overflow"], tokens = [50_000]+ )++ def fake_search(**kw):+ if kw.get("scope_project_id"):+ sources = [+ {"citationId": 0, "filename": "project.txt", "text": "P" * 2000} for _ in range(4)+ ]+ else:+ sources = [{"citationId": 0, "filename": "thread.txt", "text": "T" * 8000}]+ return tool.render_sources(sources), sources++ monkeypatch.setattr(tool, "search_for_autoinject", fake_search)+ injected = _injected_text(+ inf_tools.build_rag_autoinject(+ _convo(),+ {+ "thread_id": "t1",+ "project_id": "p1",+ "autoinject": False,+ "context_length": 8192,+ "response_headroom": 1024,+ },+ )+ )+ assert "T" * 8000 in injected+ # Some project passages survive beside the thread result, but not all four.+ assert 1 <= injected.count("P" * 2000) < 4+++def test_build_rag_autoinject_budget_charges_multibyte_text_more(rag_conn, monkeypatch):+ # A CJK character is about one token where ASCII runs four to one, so the same+ # character count costs several times more and far less of it fits.+ _add_doc(+ rag_conn, store.thread_scope("t1"), "d1", "big.pdf", "h1", ["overflow"], tokens = [50_000]+ )++ def make_search(body):+ def fake_search(**kw):+ sources = [{"citationId": 0, "filename": "thread.txt", "text": body} for _ in range(4)]+ return tool.render_sources(sources), sources++ return fake_search++ scope = {+ "thread_id": "t1",+ "autoinject": False,+ "context_length": 4096,+ "response_headroom": 1024,+ }++ # Same character count either way; only the per-character token cost differs.+ def _chunks(body):+ monkeypatch.setattr(tool, "search_for_autoinject", make_search(body))+ result = inf_tools.build_rag_autoinject(_convo(), scope)+ # None means not even one passage fit, which is zero chunks admitted.+ return _injected_text(result).count('<chunk id="') if result else 0++ ascii_chunks = _chunks("a" * 2000)+ cjk_chunks = _chunks("漢" * 2000)+ assert ascii_chunks >= 1+ assert cjk_chunks < ascii_chunks++def test_build_rag_autoinject_context_budget_falls_back(rag_conn, monkeypatch):# Runtime context can be smaller than RAG_WHOLE_DOC_MAX_TOKENS; cap whole-doc to# the active context and fall back to retrieval when it would overflow.