Skip to content

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.

Studio: measure the real size of attached documents instead of guessing (#10318)

Nilay2089a259510c
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 7b509013039..ba7f93c11b3 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -11239,6 +11239,37 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> di
_opt_int(rag_scope.get("context_length") or rag_scope.get("max_context_tokens")) or 0
)
+ def _fits(candidate_text, max_tokens) -> bool:
+ # None means the estimate itself failed; zero is 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, so dense
+ # ASCII is not charged the English four characters per token.
+ return _text_token_cost(candidate_text, ctx_tokens) <= max_tokens
+
+ def _trim(
+ hit_text,
+ hit_sources,
+ max_tokens,
+ keep_first = 1,
+ ):
+ """Drop passages from the tail until the rendered block fits, else None.
+
+ Re-renders only when something is dropped. None when not even the first
+ ``keep_first`` passages fit: the block joins the current turn, which the
+ window may not evict, so it fails the request rather than degrading it.
+ ``keep_first`` is the floor of the tail: one for ranked retrieval, but a
+ whole document must never be eaten into.
+ """
+ floor = max(1, keep_first)
+ kept, rendered = list(hit_sources), hit_text
+ while len(kept) > floor and not _fits(rendered, max_tokens):
+ kept = kept[:-1]
+ rendered = render_sources(kept)
+ return (rendered, kept) if _fits(rendered, max_tokens) else None
+
# 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
# sources are still retrieved top-K and appended under one citation
@@ -11266,43 +11297,15 @@ def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> di
logger.warning("RAG project retrieval (whole-doc companion) failed: %s", exc)
proj = None
if proj is not None:
+ # Trim into the project tail only: the document was admitted whole
+ # and stays whole, so a combination that will not fit falls back
+ # to the document alone.
merged = sources + proj[1]
- merged_text = render_sources(merged)
- if max(1, len(merged_text) // 4) <= budget:
- sources = merged
- text = merged_text
+ trimmed = _trim(render_sources(merged), merged, budget, keep_first = len(sources))
+ if trimmed is not None:
+ text, sources = trimmed
logger.info("RAG auto-inject: whole-document context (%d chunk(s))", len(sources))
- 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
diff --git a/studio/backend/tests/test_rag_whole_document.py b/studio/backend/tests/test_rag_whole_document.py
index 22cea564d42..a5c084c6f95 100644
--- a/studio/backend/tests/test_rag_whole_document.py
+++ b/studio/backend/tests/test_rag_whole_document.py
@@ -498,6 +498,73 @@ def test_build_rag_autoinject_keeps_the_project_hits_that_fit(rag_conn, monkeypa
assert 1 <= injected.count("P" * 2000) < 4
+def test_build_rag_autoinject_whole_doc_merge_is_priced_in_tokens(rag_conn, monkeypatch):
+ # The merged block was admitted on the flat len(text) // 4; a CJK character is
+ # about one token, not four.
+ _add_doc(rag_conn, store.thread_scope("t1"), "d1", "doc.pdf", "h1", ["THREAD_DOC"])
+
+ def fake_search(**kw):
+ sources = [
+ {"citationId": 0, "filename": "project.txt", "text": "漢" * 2000} for _ in range(4)
+ ]
+ 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 "THREAD_DOC" in injected
+ # Trimmed to what fits beside the document, not admitted or discarded whole.
+ assert 1 <= injected.count("漢" * 2000) < 4
+
+
+def test_build_rag_autoinject_whole_doc_merge_never_truncates_the_document(rag_conn, monkeypatch):
+ # Trimming the merge touches only the project tail: an overlarge combination gives
+ # the document back whole, never a prefix of it.
+ body = ["SECTION%02d " % i + "word " * 398 for i in range(8)]
+ _add_doc(
+ rag_conn,
+ store.thread_scope("t1"),
+ "d1",
+ "report.pdf",
+ "h1",
+ body,
+ tokens = [500] * len(body),
+ )
+
+ def fake_search(**kw):
+ sources = [{"citationId": 0, "filename": "notes.txt", "text": "PROJECT_HIT " + "x" * 500}]
+ 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 [i for i in range(len(body)) if "SECTION%02d" % i in injected] == list(range(len(body)))
+ # The companion is what does not fit, so the companion is what goes.
+ assert "PROJECT_HIT" not in injected
+
+
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.