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
Clamp Deep Research max_tokens to loaded context window (#7985)
Souravrajvi01229fc55a91a
diff --git a/studio/backend/core/research_runs.py b/studio/backend/core/research_runs.pyindex 406819d33af..ebee6dbfa16 100644--- a/studio/backend/core/research_runs.py+++ b/studio/backend/core/research_runs.py@@ -711,6 +711,88 @@ def _loaded_context_length() -> int | None:return None+def _estimate_prompt_tokens(messages: list[dict]) -> int:+ """Conservative prompt token estimate for max_tokens clamping.++ Uses the same chars-per-token heuristic as synthesis evidence budgeting so+ Deep Research sizes output against the same context window it already probes.+ """+ chars = 0+ for message in messages:+ content = message.get("content")+ if isinstance(content, str):+ chars += len(content)+ continue+ if isinstance(content, list):+ for part in content:+ if isinstance(part, dict):+ text = part.get("text")+ if isinstance(text, str):+ chars += len(text)+ return max(1, int(chars / _SYNTHESIS_EVIDENCE_CHARS_PER_TOKEN) + len(messages) * 4)+++def _clamp_max_tokens_for_context(+ requested: int,+ messages: list[dict],+ *,+ context_length: int | None = None,+) -> int:+ ctx = context_length if context_length is not None else _loaded_context_length()+ if not ctx:+ return requested+ available = max(1, ctx - _estimate_prompt_tokens(messages))+ return max(1, min(requested, available))+++def _resolve_max_tokens(+ max_tokens: int | None, inference: dict[str, Any], messages: list[dict]+) -> int:+ requested = int(max_tokens or inference.get("maxTokens") or 4096)+ ceiling = 16384 if max_tokens is not None else 8192+ capped = min(requested, ceiling)+ return _clamp_max_tokens_for_context(capped, messages)+++def _normalize_completion_usage(raw: Any) -> dict[str, int] | None:+ if not isinstance(raw, dict):+ return None+ usage: dict[str, int] = {}+ for key in ("prompt_tokens", "completion_tokens", "total_tokens"):+ value = raw.get(key)+ if isinstance(value, (int, float)):+ usage[key] = int(value)+ return usage or None+++def _completion_hit_context_wall(+ usage: dict[str, int] | None,+ *,+ requested_max_tokens: int,+ context_length: int | None = None,+) -> bool:+ if not usage:+ return False+ prompt_tokens = int(usage.get("prompt_tokens") or 0)+ completion_tokens = int(usage.get("completion_tokens") or 0)+ total_tokens = int(usage.get("total_tokens") or prompt_tokens + completion_tokens)+ ctx = context_length if context_length is not None else _loaded_context_length()+ if ctx is not None and total_tokens >= ctx:+ return True+ return completion_tokens < requested_max_tokens+++def _synthesis_length_limit_error(+ usage: dict[str, int] | None, *, requested_max_tokens: int+) -> str:+ if _completion_hit_context_wall(usage, requested_max_tokens = requested_max_tokens):+ return (+ "Local model report hit the loaded context window before completion. "+ "Increase Context Length in chat settings or reduce the research evidence size."+ )+ return "Local model report reached its output limit before completion"++async def _model_unloaded(response: httpx.Response) -> bool:"""Whether the local endpoint refused because no model is loaded (routes.inference). That istransient for a durable run -- the model can be loaded again -- unlike any other 400."""@@ -1552,7 +1634,6 @@ class ResearchSupervisor:"messages": messages,"stream": False,"temperature": inference.get("temperature", 0.2),- "max_tokens": min(int(inference.get("maxTokens") or 4096), 8192),}if inference.get("topP") is not None:payload["top_p"] = inference["topP"]@@ -1569,6 +1650,7 @@ class ResearchSupervisor:model_waits = 0while True:await self._check_active(run["id"])+ payload["max_tokens"] = _resolve_max_tokens(None, inference, messages)try:post_task = asyncio.create_task(client.post(@@ -1741,7 +1823,7 @@ class ResearchSupervisor:step_position: int | None = None,max_tokens: int | None = None,enable_thinking: bool | None = None,- ) -> tuple[str, str, str | None]:+ ) -> tuple[str, str, str | None, dict[str, int] | None]:call_id = uuid.uuid4().hexexpires = (datetime.now(timezone.utc) + timedelta(hours = 2)).isoformat()token, key = await asyncio.to_thread(@@ -1757,11 +1839,8 @@ class ResearchSupervisor:"model": inference.get("model") or config.get("model") or "","messages": messages,"stream": True,+ "stream_options": {"include_usage": True},"temperature": inference.get("temperature", 0.2),- "max_tokens": min(- int(max_tokens or inference.get("maxTokens") or 4096),- 16384 if max_tokens is not None else 8192,- ),}if inference.get("topP") is not None:payload["top_p"] = inference["topP"]@@ -1782,6 +1861,7 @@ class ResearchSupervisor:pending_reasoning_offset = 0last_progress_flush = asyncio.get_running_loop().time()finish_reason: str | None = None+ usage: dict[str, int] | None = Nonesemantic_output_at: float | None = Nonefirst_output_deadline: float | None = None@@ -1877,6 +1957,11 @@ class ResearchSupervisor:attempt = 0try:while True:+ payload["max_tokens"] = _resolve_max_tokens(+ max_tokens,+ inference,+ messages,+ )request = client.build_request("POST",self._endpoint(),@@ -1952,6 +2037,11 @@ class ResearchSupervisor:chunk = json.loads(data)if isinstance(chunk, dict) and "error" in chunk:raise RuntimeError("Local model stream failed")+ normalized_usage = _normalize_completion_usage(+ chunk.get("usage") if isinstance(chunk, dict) else None+ )+ if normalized_usage is not None:+ usage = normalized_usagechoice = chunk.get("choices", [{}])[0]delta = choice.get("delta", {})if isinstance(choice.get("finish_reason"), str):@@ -2004,7 +2094,7 @@ class ResearchSupervisor:exc_info = True,)await flush_progress()- return report, reasoning, finish_reason+ return report, reasoning, finish_reason, usageexcept (TimeoutError, asyncio.TimeoutError) as exc:raise ModelWallClockTimeout("Local model request exceeded its wall-clock timeout"@@ -2139,7 +2229,7 @@ class ResearchSupervisor:planning_total, len(planner_system) + len(planning_question), _MAX_CONTEXT_CHARS)]- response, planning_reasoning, _finish_reason = await self._stream_completion(+ response, planning_reasoning, _finish_reason, _usage = await self._stream_completion(run,[{@@ -2359,7 +2449,7 @@ class ResearchSupervisor:decision_total, decision_scaffold + evidence_chars, _MAX_CONTEXT_CHARS)]- decision, decision_reasoning, _finish_reason = await self._stream_completion(+ decision, decision_reasoning, _finish_reason, _usage = await self._stream_completion(run,[{@@ -2681,7 +2771,12 @@ class ResearchSupervisor:_MAX_CONTEXT_CHARS,)]- audit_response, audit_reasoning, _audit_finish_reason = await self._stream_completion(+ (+ audit_response,+ audit_reasoning,+ _audit_finish_reason,+ _audit_usage,+ ) = await self._stream_completion(run,[{@@ -2787,7 +2882,12 @@ class ResearchSupervisor:),},]- report, synthesis_reasoning, synthesis_finish_reason = await self._stream_completion(+ (+ report,+ synthesis_reasoning,+ synthesis_finish_reason,+ synthesis_usage,+ ) = await self._stream_completion(run,synthesis_messages,phase = "synthesis",@@ -2807,10 +2907,16 @@ class ResearchSupervisor:},synthesis_messages[1],]+ recovery_max_tokens = _resolve_max_tokens(+ 16384,+ run["config"].get("inferenceRequest") or {},+ recovery_messages,+ )(recovered_report,recovery_reasoning,recovery_finish_reason,+ recovery_usage,) = await self._stream_completion(run,recovery_messages,@@ -2821,9 +2927,15 @@ class ResearchSupervisor:synthesis_reasoning += recovery_reasoningreport = recovered_reportsynthesis_finish_reason = recovery_finish_reason+ synthesis_usage = recovery_usageawait self._check_active(run["id"])if synthesis_finish_reason == "length":- raise ValueError("Local model report reached its output limit before completion")+ raise ValueError(+ _synthesis_length_limit_error(+ synthesis_usage,+ requested_max_tokens = recovery_max_tokens,+ )+ )if not report.strip():report = _recover_report_from_reasoning(synthesis_reasoning)if not report:diff --git a/studio/backend/tests/test_research_runs_hardening.py b/studio/backend/tests/test_research_runs_hardening.pyindex 75198e493c6..bea261c23cd 100644--- a/studio/backend/tests/test_research_runs_hardening.py+++ b/studio/backend/tests/test_research_runs_hardening.py@@ -18,9 +18,13 @@ from core.research_runs import (ResearchSupervisor,RunCancelled,_citation_title,+ _completion_hit_context_wall,_escape_link_destination,+ _estimate_prompt_tokens,+ _resolve_max_tokens,_sanitize_public_query,_shield_untrusted,+ _synthesis_length_limit_error,_validate_report_document_sources,_validate_report_sources,)@@ -230,6 +234,48 @@ def test_prompt_budget_counts_the_whole_prompt(monkeypatch):assert research_runs._trimmable_budget(total, total + 5_000, 1_000) == 0+def test_resolve_max_tokens_clamps_to_loaded_context(monkeypatch):+ monkeypatch.setattr(research_runs, "_loaded_context_length", lambda: 12_288)+ messages = [{"role": "user", "content": "x" * 33_000}]+ prompt_tokens = _estimate_prompt_tokens(messages)+ resolved = _resolve_max_tokens(16_384, {}, messages)+ assert resolved == 12_288 - prompt_tokens+ assert resolved < 16_384+++def test_completion_hit_context_wall_matches_live_probe():+ usage = {+ "prompt_tokens": 11_032,+ "completion_tokens": 1_256,+ "total_tokens": 12_288,+ }+ assert _completion_hit_context_wall(+ usage,+ requested_max_tokens = 16_384,+ context_length = 12_288,+ )+ assert not _completion_hit_context_wall(+ {+ "prompt_tokens": 1_000,+ "completion_tokens": 16_384,+ "total_tokens": 17_384,+ },+ requested_max_tokens = 16_384,+ context_length = 32_768,+ )+++def test_synthesis_length_limit_error_names_context_window():+ usage = {+ "prompt_tokens": 11_032,+ "completion_tokens": 1_256,+ "total_tokens": 12_288,+ }+ message = _synthesis_length_limit_error(usage, requested_max_tokens = 16_384)+ assert "context window" in message.lower()+ assert "Increase Context Length" in message++def test_every_research_prompt_path_is_budgeted():# Planning, decision and synthesis all build prompts from unbounded inputs (a pasted# question, up to 12k of history, a 40-source catalog). Each must measure its trimmable@@ -687,10 +733,10 @@ def test_stream_completion_retries_after_the_model_is_loaded_again(monkeypatch):return Nonesupervisor = _make_supervisor(_check_active)- report, reasoning, finish_reason = asyncio.run(+ report, reasoning, finish_reason, usage = asyncio.run(supervisor._stream_completion(_waiting_run(30.0), [{"role": "user"}], report_progress = False))- assert (report, reasoning, finish_reason) == ("report", "", "stop")+ assert (report, reasoning, finish_reason, usage) == ("report", "", "stop", None)assert len(sent) == 2@@ -738,7 +784,7 @@ def test_stream_completion_retries_a_transport_error_before_any_bytes_stream(mon[httpx.ConnectError(_TRANSPORT_BLIP), _response(200, body = _stream_body())],)supervisor = _make_supervisor(_noop_check_active)- assert _run_stream(supervisor) == ("report", "", "stop")+ assert _run_stream(supervisor) == ("report", "", "stop", None)assert len(sent) == 2assert delays == [1]@@ -750,7 +796,7 @@ def test_stream_completion_retries_a_transient_server_error(monkeypatch):[_response(503, body = "overloaded"), _response(200, body = _stream_body())],)supervisor = _make_supervisor(_noop_check_active)- assert _run_stream(supervisor) == ("report", "", "stop")+ assert _run_stream(supervisor) == ("report", "", "stop", None)assert len(sent) == 2assert delays == [1]@@ -1425,7 +1471,7 @@ def test_stream_completion_semantic_output_resets_the_idle_timeout(monkeypatch):_install_fake_client(monkeypatch, [_ProgressStream()])supervisor = _make_supervisor(_noop_check_active)- assert _run_stream(supervisor, timeout_seconds = 1.0) == ("report", "thinking", "stop")+ assert _run_stream(supervisor, timeout_seconds = 1.0) == ("report", "thinking", "stop", None)def test_stream_completion_allows_output_before_first_output_timeout(monkeypatch):@@ -1453,7 +1499,7 @@ def test_stream_completion_allows_output_before_first_output_timeout(monkeypatch_install_fake_client(monkeypatch, [_SlowPrefillStream()])supervisor = _make_supervisor(_noop_check_active)- assert _run_stream(supervisor, timeout_seconds = 1.0) == ("report", "", "stop")+ assert _run_stream(supervisor, timeout_seconds = 1.0) == ("report", "", "stop", None)def test_first_output_deadline_disarms_once_output_starts(monkeypatch):@@ -1554,7 +1600,7 @@ def test_stream_completion_counts_whitespace_tokens_as_output(monkeypatch):_install_fake_client(monkeypatch, [_WhitespaceStream()])supervisor = _make_supervisor(_noop_check_active)- assert _run_stream(supervisor, timeout_seconds = 1.0) == (" \n\treport", "", "stop")+ assert _run_stream(supervisor, timeout_seconds = 1.0) == (" \n\treport", "", "stop", None)def test_stream_completion_stops_at_done_even_if_socket_stays_open(monkeypatch):@@ -1581,7 +1627,7 @@ def test_stream_completion_stops_at_done_even_if_socket_stays_open(monkeypatch):_install_fake_client(monkeypatch, [_OpenSocketAfterDone()])supervisor = _make_supervisor(_noop_check_active)- assert _run_stream(supervisor, timeout_seconds = 1.0) == ("report", "", "stop")+ assert _run_stream(supervisor, timeout_seconds = 1.0) == ("report", "", "stop", None)assert state == {"iteratorClosed": True, "responseClosed": True}diff --git a/studio/backend/tests/test_research_runs_storage.py b/studio/backend/tests/test_research_runs_storage.pyindex 8d1be54f330..f4458d7b574 100644--- a/studio/backend/tests/test_research_runs_storage.py+++ b/studio/backend/tests/test_research_runs_storage.py@@ -412,7 +412,7 @@ def test_streamed_reasoning_is_batched_before_database_writes(research_home, mon)supervisor = worker.ResearchSupervisor(SimpleNamespace(state = SimpleNamespace(server_port = 1)))- report, reasoning, finish_reason = asyncio.run(+ report, reasoning, finish_reason, _usage = asyncio.run(supervisor._stream_completion(run,[{"role": "user", "content": "question"}],@@ -1433,7 +1433,7 @@ def test_planner_prompt_shields_untrusted_conversation(research_home, monkeypatc**kwargs,):captured["planner"] = messages[1]["content"]- return json.dumps(_plan()), "Planned.", "stop"+ return json.dumps(_plan()), "Planned.", "stop", Nonemonkeypatch.setattr(supervisor, "_stream_completion", fake_stream_completion)@@ -1545,9 +1545,14 @@ def test_supervisor_planning_and_research_are_durable_with_mocked_io(research_hoassert "We were discussing OpenAI." in promptassert "Compare that with Anthropic." in promptif "rigorous web research plan" in system:- return json.dumps(_plan()), "Planned several lines of inquiry.", "stop"+ return json.dumps(_plan()), "Planned several lines of inquiry.", "stop", Noneif "iterative research process" in system:- return next(decisions), "Evaluated the evidence and selected the next action.", "stop"+ return (+ next(decisions),+ "Evaluated the evidence and selected the next action.",+ "stop",+ None,+ )assert "<document_source_catalog>" in promptassert "private.pdf" in promptif kwargs.get("phase") == "synthesis_audit":@@ -1567,12 +1572,13 @@ def test_supervisor_planning_and_research_are_durable_with_mocked_io(research_ho),"Audited document evidence.","stop",+ None,)if kwargs.get("phase") == "synthesis":- return "", "Repeated a truncated source URL.", "length"+ return "", "Repeated a truncated source URL.", "length", Nonereport = report_responseresearch_db.set_report_progress(run["id"], report)- return report, "Checked the available evidence.", "stop"+ return report, "Checked the available evidence.", "stop", Nonetool_calls = []@@ -1772,9 +1778,9 @@ def _run_search_then_finish():system = messages[0]["content"]if "rigorous web research plan" in system:- return json.dumps(_plan()), "planned", "stop"+ return json.dumps(_plan()), "planned", "stop", Noneif "iterative research process" in system:- return next(decisions), "decided", "stop"+ return next(decisions), "decided", "stop", Nonesynthesis_prompts.append(messages[1]["content"])if "evidence-to-claim audit" in system:return (@@ -1797,9 +1803,10 @@ def _run_search_then_finish(),"audited","stop",+ None,)research_db.set_report_progress(run["id"], report)- return report, "synthesized", "stop"+ return report, "synthesized", "stop", Nonemonkeypatch.setattr(supervisor, "_stream_completion", fake_stream_completion)monkeypatch.setattr(worker, "execute_tool", fake_tool)@@ -2021,12 +2028,12 @@ def test_synthesis_pass_runs_at_synthesis_phase(research_home, monkeypatch):):system = messages[0]["content"]if "rigorous web research plan" in system:- return json.dumps(_plan()), "p", "stop"+ return json.dumps(_plan()), "p", "stop", Noneif "iterative research process" in system:- return next(decisions), "d", "stop"+ return next(decisions), "d", "stop", Nonecaptured.update(kwargs)research_db.set_report_progress(run["id"], "# Report\n\nGrounded text.")- return "# Report\n\nGrounded text.", "s", "stop"+ return "# Report\n\nGrounded text.", "s", "stop", Nonedef fake_tool(name, arguments, *a, **k):return "page body" if arguments.get("url") else _two_source_search()@@ -2258,6 +2265,7 @@ def test_recovered_running_research_resumes_durable_progress(research_home, monk),"","stop",+ None,)assert "Saved durable snippet" in promptassert "Private durable evidence" in prompt@@ -2268,6 +2276,7 @@ def test_recovered_running_research_resumes_durable_progress(research_home, monk"# Resumed report\n\nSaved finding [Saved source](https://saved.example/source).","","stop",+ None,)def unexpected_tool(*args, **kwargs):@@ -2316,12 +2325,12 @@ def test_knowledge_base_evidence_beyond_the_source_cap_is_not_synthesized(async def fake_stream_completion(run, messages, **kwargs):system = messages[0]["content"]if "rigorous web research plan" in system:- return json.dumps(_plan()), "planned", "stop"+ return json.dumps(_plan()), "planned", "stop", Noneif "iterative research process" in system:- return next(decisions), "decided", "stop"+ return next(decisions), "decided", "stop", Nonesynthesis_prompts.append(messages[1]["content"])research_db.set_report_progress(run["id"], report)- return report, "synthesized", "stop"+ return report, "synthesized", "stop", Nonelabels = iter(("kept", "capped"))diff --git a/studio/frontend/package-lock.json b/studio/frontend/package-lock.jsonindex 4395b644e7c..bb8d6aa7855 100644--- a/studio/frontend/package-lock.json+++ b/studio/frontend/package-lock.json@@ -1708,6 +1708,7 @@"os": ["android"],+ "peer": true,"engines": {"node": ">= 10"},@@ -1728,6 +1729,7 @@"os": ["darwin"],+ "peer": true,"engines": {"node": ">= 10"},@@ -1748,6 +1750,7 @@"os": ["darwin"],+ "peer": true,"engines": {"node": ">= 10"},@@ -1768,6 +1771,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">= 10"},@@ -1788,6 +1792,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">= 10"},@@ -1808,6 +1813,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">= 10"},@@ -1828,6 +1834,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">= 10"},@@ -1848,6 +1855,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">= 10"},@@ -1868,6 +1876,7 @@"os": ["linux"],+ "peer": true,"engines": {"node": ">= 10"},@@ -1888,6 +1897,7 @@"os": ["win32"],+ "peer": true,"engines": {"node": ">= 10"},@@ -1908,6 +1918,7 @@"os": ["win32"],+ "peer": true,"engines": {"node": ">= 10"},@@ -6491,7 +6502,6 @@"version": "2.4.9","resolved": "https://registry.npmjs.org/@tauri-apps/plugin-deep-link/-/plugin-deep-link-2.4.9.tgz","integrity": "sha512-u0SKOUHnJ1wqeqXsDFq2+kASCBj9xxbG0g9XZWPy9SOmU4wXtp6b/wiYpm6oH6/5fBTQsLqnLhIvqLBRpgHJlA==",- "license": "MIT OR Apache-2.0","dependencies": {"@tauri-apps/api": "^2.11.0"}