diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py index f48144c39fbf..b2a9c535889c 100644 --- a/studio/backend/core/inference/llama_cpp.py +++ b/studio/backend/core/inference/llama_cpp.py @@ -1681,6 +1681,30 @@ def _branch_boundary(conversation: list[dict], branch: Optional[list[dict]]) -> return count +def _has_unpriced_media(messages: list[dict]) -> bool: + """Audio or video, which every fit leaves uncounted; images are priced.""" + from core.inference.context_window import _IMAGE_PART_TYPES, _UNPRICED_MEDIA_TYPES + + uncounted = _UNPRICED_MEDIA_TYPES - _IMAGE_PART_TYPES + return any( + isinstance(part, dict) and part.get("type") in uncounted + for message in messages + if isinstance(message.get("content"), list) + for part in message["content"] + ) + + +def _with_transcript_link(messages: list[dict], thread_id: Optional[str]) -> list[dict]: + """The prompt as `_archive_and_recall` will send it, with the transcript link it adds.""" + from core.inference import compaction_transcript + from core.rag import conversation_archive + + if not thread_id or not conversation_archive.enabled(): + return messages + path = compaction_transcript.path_for(thread_id) + return compaction_transcript.link_in_block(messages, path) if path else messages + + def _records_boundary(truncation: dict) -> bool: """Not the fits flag: a rescued fit still evicts, and skipping the save compacts silently. Saving is not replaying: sticky logic declines fits-false records.""" return bool(truncation.get("fits")) or bool(truncation.get("dropped_messages")) @@ -41632,13 +41656,12 @@ def _attach_internal_feedback_to_tool_result(feedback: str) -> bool: ) _auto = None if _skip_autoinject else build_rag_autoinject(conversation, rag_scope) if _auto: - for _ev in _auto["events"]: - yield _ev conversation.extend(_auto["messages"]) _auto_satisfies_forced_choice = bool(_auto) and ( tool_choice == "required" or forced_tool_name(tool_choice) == "search_knowledge_base" ) # After the message, so the tool block heading the cached prompt stays put; a forced tool keeps its first call. + _mcp_auto = None if ( mcp_match_exchange and mcp_match_exchange.get("messages") @@ -41648,9 +41671,31 @@ def _attach_internal_feedback_to_tool_result(feedback: str) -> bool: continue_final_message and trailing_assistant_resume_kind(conversation) is not None ) ): - for _ev in mcp_match_exchange["events"]: - yield _ev - conversation.extend(mcp_match_exchange["messages"]) + _mcp_auto = mcp_match_exchange + conversation.extend(_mcp_auto["messages"]) + + _initial_searches_sent = False + + def _initial_search_events(): + nonlocal _initial_searches_sent + if not _initial_searches_sent: + _initial_searches_sent = True + for exchange in (_auto, _mcp_auto): + if exchange: + yield from exchange["events"] + + _retry_whole_document = ( + not _skip_autoinject + and context_overflow == "truncate_oldest" + and bool(self._effective_context_length) + and rag_scope + and rag_scope.get("thread_id") + and not rag_scope.get("kb_id") + and rag_scope.get("whole_doc") is not False + and (not (_auto and _auto.get("whole_document")) or _mcp_auto) + ) + if not _retry_whole_document: + yield from _initial_search_events() _accumulated_completion_tokens = 0 _accumulated_predicted_ms = 0.0 @@ -42133,6 +42178,7 @@ def _count() -> None: except Exception: # accounting must never break a run in progress logger.debug("tool loop recost failed", exc_info = True) if iteration >= max_tool_iterations + _extra + _continuation_credits: + yield from _initial_search_events() break if cancel_event is not None and cancel_event.is_set(): return @@ -42144,6 +42190,7 @@ def _count() -> None: active_tools = tool_controller.active_tools() if not active_tools: + yield from _initial_search_events() _append_budget_exhausted_nudge = False break from core.inference.chat_template_helpers import neutralize_tool_descriptions @@ -42221,6 +42268,93 @@ def _count() -> None: # Accounted for in this request now, whatever the fit decided. _sticky_boundary_applied = True _loop_cut = _loop_cut or bool(truncation and truncation.get("dropped_messages")) + _fit_recall_cap = float("inf") + if ( + _retry_whole_document + and not _initial_searches_sent + and truncation + and truncation.get("fits") + and truncation.get("dropped_messages") + and not _has_unpriced_media(conversation) + ): + try: + old_ids = {id(message) for message in (_auto or {}).get("messages", ())} + live_ids = {id(message) for message in conversation} + if not (_auto and _auto.get("whole_document") and old_ids <= live_ids): + base = [ + message + for message in conversation + if id(message) not in old_ids + ] + refreshed = build_rag_autoinject( + base, rag_scope, whole_document_only = True + ) + if refreshed: + # Keep the document search before the MCP search in the prompt and stream. + mcp_ids = { + id(message) + for message in (_mcp_auto or {}).get("messages", ()) + } + at = next( + ( + i + for i, message in enumerate(base) + if id(message) in mcp_ids + ), + len(base), + ) + candidate = base[:at] + refreshed["messages"] + base[at:] + measured = _fit_count_tokens( + candidate, safe_tools, _reasoning_kw + ) + # The ceilings bound what is sent, which carries the transcript link the fit leaves uncounted. + linked = _with_transcript_link(candidate, thread_id) + sent_tokens = ( + measured + if linked is candidate + else _fit_count_tokens(linked, safe_tools, _reasoning_kw) + ) + # The fit's own target, also on a replay: headroom, plus the recall reserve a rolling fit holds back. + budget = prompt_budget( + self._effective_context_length, _iteration_max_tokens + ) + headroom_line = budget - int( + budget + * _effective_headroom_ratio(compaction_headroom_ratio) + ) + reserve = ( + _conversation_recall_reserve(thread_id) + if not truncation.get("checkpoint") + else 0 + ) + fitted_tokens = truncation["prompt_tokens_after"] + # Growth stays under the unfitted prompt, which admission already priced. + if measured <= fitted_tokens or sent_tokens <= min( + headroom_line - reserve, + truncation["prompt_tokens_before"], + ): + # A larger prompt leaves this fit's recall only the room under both ceilings. + if measured > fitted_tokens: + _fit_recall_cap = max( + 0, + min( + headroom_line, + truncation["prompt_tokens_before"], + ) + - sent_tokens, + ) + _auto = refreshed + conversation = candidate + truncation["prompt_tokens_after"] = measured + # A forced name stays forced: this fit priced and worded the prompt for that one tool. + if tool_choice == "required": + _forced_choice_resolved = True + requested_choice = "auto" + except Exception: + logger.debug( + "Whole-document retry after compaction failed", exc_info = True + ) + yield from _initial_search_events() if truncation and truncation.get("fits"): # Before the recall injection, so both sides describe the same # messages, priced by the fit with the catalogue and template. @@ -42244,12 +42378,15 @@ def _count() -> None: # A rescued refusal may evict messages; archive them without recall. recall_done = _conversation_recall_done or not truncation["fits"], # Leave room for the answer appended on the next iteration. - recall_budget_tokens = _retrieval_budget( - self._effective_context_length, - # As above: the cap this iteration will actually send. - _iteration_max_tokens, - truncation.get("prompt_tokens_after") or 0, - reply_returns = True, + recall_budget_tokens = min( + _retrieval_budget( + self._effective_context_length, + # As above: the cap this iteration will actually send. + _iteration_max_tokens, + truncation.get("prompt_tokens_after") or 0, + reply_returns = True, + ), + _fit_recall_cap, ), count_tokens = lambda fitted: self.count_chat_tokens( neutralize_control_markup_in_messages( @@ -42288,6 +42425,7 @@ def _count() -> None: except Exception as exc: logger.warning("Could not preflight the rolling context window: %s", exc) + yield from _initial_search_events() payload = { # Re-run each iteration: tool results may contain forged turns. "messages": neutralize_control_markup_in_messages( diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py index 9cdc4b2f2253..8ee2302ededb 100644 --- a/studio/backend/core/inference/tools.py +++ b/studio/backend/core/inference/tools.py @@ -16265,19 +16265,35 @@ def _thread_document_ids(thread_id) -> set | None: return {d["id"] for d in docs if d.get("status") == "completed" and d.get("num_chunks")} -def build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> dict | None: +def build_rag_autoinject( + conversation: list[dict], + rag_scope: dict | None, + *, + whole_document_only: bool = False, +) -> dict | None: """Pre-retrieves the latest turn for models that skip search_knowledge_base. Toggle rag_scope.autoinject or RAG_AUTOINJECT; floor RAG_AUTOINJECT_MIN_SCORE.""" try: from core.rag.retrieval import query_vector_memo except Exception: # noqa: BLE001 - the build reports an unavailable RAG stack itself - return _build_rag_autoinject(conversation, rag_scope) + return _build_rag_autoinject( + conversation, rag_scope, whole_document_only = whole_document_only + ) # The thread retry, the hybrid retry and the dense probe re-ask the same query: encode it once. with query_vector_memo(): - return _build_rag_autoinject(conversation, rag_scope) + return _build_rag_autoinject( + conversation, rag_scope, whole_document_only = whole_document_only + ) -def _build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> dict | None: +def _build_rag_autoinject( + conversation: list[dict], + rag_scope: dict | None, + *, + whole_document_only: bool = False, +) -> dict | None: enabled, whole_doc_requested = rag_autoinject_reaches_retrieval(conversation, rag_scope) + if whole_document_only and not whole_doc_requested: + return None if not enabled and not whole_doc_requested: return None thread_id = rag_scope.get("thread_id") @@ -16305,6 +16321,7 @@ def _build_rag_autoinject(conversation: list[dict], rag_scope: dict | None) -> d # Zero or below is no limit to the search, which then returns its own default count. top_k = min(sidebar_k, lean_k) if sidebar_k is not None and sidebar_k > 0 else lean_k budget: int | None = None + whole_document = False # Only trust 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 @@ -16343,6 +16360,7 @@ def _trim( logger.warning("RAG whole-document context failed: %s", exc) whole = None if whole is not None: + whole_document = True text, sources = whole project_id = rag_scope.get("project_id") if project_id: @@ -16365,6 +16383,9 @@ def _trim( text, sources = trimmed logger.info("RAG auto-inject: whole-document context (%d chunk(s))", len(sources)) + if whole_document_only and not whole_document: + return 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 @@ -16501,6 +16522,7 @@ def _strong_thread_match() -> bool: sources = sources, ) logger.info("RAG auto-inject: %d passage(s)", len(sources)) + built["whole_document"] = whole_document return built diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.py index 850533912193..219b175f927c 100644 --- a/studio/backend/tests/test_llama_cpp_tool_loop.py +++ b/studio/backend/tests/test_llama_cpp_tool_loop.py @@ -7652,18 +7652,24 @@ def _mcp_match_exchange(names = ()): @pytest.mark.parametrize( - "tool_choice, injected", + "tool_choice, injected, docs", [ - (None, True), - ("none", False), - ({"type": "function", "function": {"name": "render_html"}}, False), + (None, True, False), + (None, True, True), + ("none", False, False), + ({"type": "function", "function": {"name": "render_html"}}, False, False), ], ) -def test_mcp_matches_arrive_as_a_search_after_the_message(monkeypatch, tool_choice, injected): +def test_mcp_matches_arrive_as_a_search_after_the_message(monkeypatch, tool_choice, injected, docs): + from core.inference import tools + stream = [_sse({"content": "done"}), _done()] backend, payloads = _backend_and_payloads(monkeypatch, [stream]) exchange = _mcp_match_exchange() user = {"role": "user", "content": "move it"} + # Docs on with no attachment: the card waits for a fit that never compacts. + monkeypatch.setattr(tools, "build_rag_autoinject", lambda *_a, **_kw: None) + backend._effective_context_length = 100_000 events = _run_tool_loop( backend, @@ -7671,6 +7677,8 @@ def test_mcp_matches_arrive_as_a_search_after_the_message(monkeypatch, tool_choi _render_html_tools(), mcp_match_exchange = exchange, tool_choice = tool_choice, + context_overflow = "truncate_oldest", + rag_scope = {"thread_id": "t1", "context_length": 100_000} if docs else None, ) sent = payloads[0]["messages"] @@ -7711,3 +7719,248 @@ def test_a_python_call_runs_with_the_analysis_its_classification_made(monkeypatc assert len(seen) == 1 assert isinstance(seen[0], tools_mod.PythonCallAnalyses) assert list(seen[0]._by_source) == ["print(1)"] + + +@pytest.mark.parametrize( + "policy, tool_choice, whole_doc, sticky, reserve, audio, manual, complete, expected_passage", + [ + ("checkpoint", None, True, 0, 0, False, False, "Complete document", "Complete document"), + ( + "checkpoint", + "required", + True, + 0, + 0, + False, + False, + "Complete document", + "Complete document", + ), + ( + "checkpoint", + {"type": "function", "function": {"name": "search_knowledge_base"}}, + True, + 0, + 0, + False, + False, + "Complete document", + "Complete document", + ), + ("rolling", None, True, 0, 0, False, False, "Complete document", "Complete document"), + ("rolling", None, True, 0, 0, False, False, "Large document " * 50, "Partial passage"), + ("checkpoint", None, True, 2, 0, False, False, "Complete document", "Complete document"), + ("checkpoint", None, True, 2, 0, False, False, "Medium document " * 45, "Partial passage"), + ("rolling", None, True, 2, 0, False, False, "Medium document " * 45, "Partial passage"), + ( + "rolling", + None, + True, + 2, + 0, + False, + False, + "Medium document " * 25, + "Medium document " * 25, + ), + ("rolling", None, True, 2, 300, False, False, "Medium document " * 25, "Partial passage"), + ( + "rolling", + None, + True, + 2, + 100, + False, + False, + "Medium document " * 25, + "Medium document " * 25, + ), + ( + "checkpoint", + None, + True, + 0, + 300, + False, + False, + "Medium document " * 25, + "Medium document " * 25, + ), + ("checkpoint", None, True, 0, 0, False, False, "Large document " * 50, "Partial passage"), + ("checkpoint", None, True, 0, 0, True, False, "Complete document", "Partial passage"), + ("checkpoint", None, True, 2, 0, False, True, "Medium document " * 25, "Partial passage"), + ( + "checkpoint", + None, + True, + 2, + 0, + False, + True, + "Small whole document", + "Small whole document", + ), + ( + "checkpoint", + None, + True, + 2, + 0, + False, + True, + "Small whole document " * 2, + "Partial passage", + ), + ("checkpoint", None, False, 0, 0, False, False, "", None), + ], +) +def test_first_context_fit_retries_whole_document_in_prompt_order( + monkeypatch, + policy, + tool_choice, + whole_doc, + sticky, + reserve, + audio, + manual, + complete, + expected_passage, +): + from core.inference import tools + + backend, payloads = _backend_and_payloads(monkeypatch, [[_sse({"content": "OK"}), _done()]]) + backend._effective_context_length = 1000 + monkeypatch.setattr( + backend, + "count_chat_tokens", + lambda messages, *_a, **_kw: sum(len(str(m.get("content", ""))) for m in messages), + ) + monkeypatch.setattr(llama_cpp, "_can_reset_epoch", lambda *_a, **_kw: True) + monkeypatch.setattr( + llama_cpp, "_keeps_compaction_boundary", lambda thread_id: thread_id == "t1" + ) + recall_budgets = [] + from core.inference import compaction_transcript + from core.rag import conversation_archive + + monkeypatch.setattr(conversation_archive, "enabled", lambda: True) + monkeypatch.setattr(compaction_transcript, "path_for", lambda _thread_id: "/chat/transcript.md") + link = " Transcript at /chat/transcript.md." + + def link_in_block(messages, _path): + system = messages[0] + if system["role"] != "system" or system["content"].endswith(link): + return messages + return [{**system, "content": system["content"] + link}, *messages[1:]] + + monkeypatch.setattr(compaction_transcript, "link_in_block", link_in_block) + + def archive_and_recall(conversation, *_a, recall_budget_tokens, **_kw): + recall_budgets.append(recall_budget_tokens) + if _kw["thread_id"]: + conversation = compaction_transcript.link_in_block(conversation, "/chat/transcript.md") + return dict(conversation = conversation, counts = {}, recalled = False) + + monkeypatch.setattr(llama_cpp, "_archive_and_recall", archive_and_recall) + monkeypatch.setattr(llama_cpp, "_archive_is_degraded", lambda: False) + monkeypatch.setattr( + llama_cpp, "_sticky_compaction_details", lambda *_a, **_kw: (sticky, True, manual) + ) + monkeypatch.setattr(llama_cpp, "_conversation_recall_reserve", lambda _thread_id: reserve) + if manual: + from core.inference import checkpoint + + # No carried-forward block, so the replay leaves the prompt smaller than it was. + monkeypatch.setattr(checkpoint, "MAX_TOKENS", 0) + + def exchange(name, prefix, text): + return tools.build_synthetic_search_exchange( + tool_name = name, + call_prefix = prefix, + status_label = name, + query = "Summarize the document", + text = text, + sources = None, + ) + + def inject( + messages, + scope, + *, + whole_document_only = False, + ): + if not scope["whole_doc"]: + return None + if whole_document_only: + assert not any( + "ancient" in str(message.get("content")) + for message in messages + if message["role"] != "system" + ) + assert not any(message.get("content") == "Partial passage" for message in messages) + text = complete + elif tool_choice is not None: + return None + else: + text = "Partial passage" + return { + **exchange("search_knowledge_base", "rag_auto_", text), + "whole_document": whole_document_only, + } + + monkeypatch.setattr(tools, "build_rag_autoinject", inject) + audio_part = [{"type": "input_audio", "input_audio": {"data": "", "format": "wav"}}] * audio + mcp = exchange(tools.MCP_TOOL_SEARCH_NAME, "mcp_auto_", "Matching MCP tools") + catalog = [ + {"type": "function", "function": {"name": name}} + for name in ["search_knowledge_base", tools.MCP_TOOL_SEARCH_NAME] + ] + events = list( + backend.generate_chat_completion_with_tools( + messages = [ + {"role": "system", "content": "Be brief."}, + {"role": "user", "content": "ancient " * (5 if manual else 250)}, + {"role": "assistant", "content": "Prior answer"}, + { + "role": "user", + "content": [{"type": "text", "text": "Summarize the document"}, *audio_part], + }, + ], + tools = catalog, + mcp_match_exchange = {**mcp, "names": []}, + context_overflow = "truncate_oldest", + context_policy = policy, + compaction_headroom_ratio = 0.25, + thread_id = "t1" if policy == "rolling" else "t2", + max_tokens = 80, + max_tool_iterations = 2, + tool_choice = tool_choice, + rag_scope = {"thread_id": "t1", "context_length": 1000, "whole_doc": whole_doc}, + ) + ) + + sent = [m.get("content") for m in payloads[0]["messages"] if m["role"] == "tool"] + expected = [expected_passage] if expected_passage else [] + if not isinstance(tool_choice, dict): + expected.append("Matching MCP tools") + assert sent == expected + assert payloads[0]["tool_choice"] == ("required" if isinstance(tool_choice, dict) else "auto") + assert [e["result"] for e in events if e["type"] == "tool_end"] == sent + truncation = next(e for e in events if e["type"] == "context_truncated") + assert truncation["fits"] and truncation["dropped_messages"] == 2 + sent_size = sum(len(str(m.get("content", ""))) for m in payloads[0]["messages"]) + if not audio: + # The fit's count leaves the transcript link out, as before. + assert truncation["prompt_tokens_after"] == sent_size - len(link) + from core.inference.context_window import prompt_budget, retrieval_budget + + prompt = truncation["prompt_tokens_after"] + recall = retrieval_budget(1000, 80, prompt, reply_returns = True) + if expected_passage == complete: + target = prompt_budget(1000, 80) + ceiling = min(target - int(target * 0.25), truncation["prompt_tokens_before"]) + recall = min(recall, ceiling - sent_size) + assert recall_budgets[0] == recall + if isinstance(tool_choice, dict): + assert [t["function"]["name"] for t in payloads[0]["tools"]] == ["search_knowledge_base"] + assert bool(truncation.get("checkpoint_started")) is (policy == "checkpoint" and not sticky) diff --git a/studio/backend/tests/test_rag_whole_document.py b/studio/backend/tests/test_rag_whole_document.py index 6a836d6a2b96..93458d594ebf 100644 --- a/studio/backend/tests/test_rag_whole_document.py +++ b/studio/backend/tests/test_rag_whole_document.py @@ -457,6 +457,25 @@ def test_build_rag_autoinject_large_model_auto_falls_back_over_budget(rag_conn, assert _injected_text(result) == "TOPK_LARGE_MODEL_FALLBACK" +def test_build_rag_autoinject_whole_document_only_follows_the_history_budget(rag_conn, monkeypatch): + _add_doc( + rag_conn, store.thread_scope("t1"), "d1", "doc.pdf", "h1", ["whole body"], tokens = [600] + ) + scope = {"thread_id": "t1", "context_length": 4000} + long_history = [{"role": "user", "content": "x" * 10_000}, *_convo()] + sentinel = ("TOPK_TEXT", [{"citationId": 1, "filename": "doc.pdf", "text": "x"}]) + searches = [] + monkeypatch.setattr(tool, "search_for_autoinject", lambda **kw: searches.append(kw) or sentinel) + excerpts = inf_tools.build_rag_autoinject(long_history, scope) + assert _injected_text(excerpts) == "TOPK_TEXT" and excerpts["whole_document"] is False + + searches.clear() + assert inf_tools.build_rag_autoinject(long_history, scope, whole_document_only = True) is None + assert searches == [] + whole = inf_tools.build_rag_autoinject(_convo(), scope, whole_document_only = True) + assert "whole body" in _injected_text(whole) and whole["whole_document"] is True + + def test_build_rag_autoinject_fallback_is_thread_first_and_budgeted(rag_conn, monkeypatch): monkeypatch.setattr(tool, "whole_document_context", lambda **kw: None) monkeypatch.setattr(inf_tools, "_thread_document_ids", lambda thread_id: None)