AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(backend): raise the LLM request timeout to 600s and make it configurable (#14206)
Reinier van der Leer50bf1b6934c0
diff --git a/autogpt_platform/backend/backend/blocks/ai_condition.py b/autogpt_platform/backend/backend/blocks/ai_condition.pyindex 153f630857..cb9e8f82a6 100644--- a/autogpt_platform/backend/backend/blocks/ai_condition.py+++ b/autogpt_platform/backend/backend/blocks/ai_condition.py@@ -1,5 +1,9 @@import re-from typing import Any+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ # Runtime import would cycle: data.execution imports backend.blocks.+ from backend.data.execution import ExecutionContextfrom backend.blocks._base import (BlockCategory,@@ -137,6 +141,7 @@ class AIConditionBlock(AIBlockBase):llm_model: LLMModel,prompt: list,max_tokens: int,+ execution_context: "ExecutionContext | None" = None,) -> LLMResponse:"""Wrapper method for llm_call to enable mocking in tests."""return await llm_call(@@ -145,6 +150,7 @@ class AIConditionBlock(AIBlockBase):prompt=prompt,force_json_output=False,max_tokens=max_tokens,+ execution_context=execution_context,)async def run(@@ -195,6 +201,7 @@ class AIConditionBlock(AIBlockBase):llm_model=input_data.model,prompt=prompt,max_tokens=MIN_LLM_OUTPUT_TOKENS,+ execution_context=kwargs.get("execution_context"),)# Extract the boolean result from the responsediff --git a/autogpt_platform/backend/backend/blocks/llm.py b/autogpt_platform/backend/backend/blocks/llm.pyindex 067dacaac4..04fab34438 100644--- a/autogpt_platform/backend/backend/blocks/llm.py+++ b/autogpt_platform/backend/backend/blocks/llm.py@@ -5,10 +5,11 @@ import loggingimport mathimport reimport secrets+import timefrom abc import ABCfrom enum import Enumfrom json import JSONDecodeError-from typing import Any, Iterable, List, Literal, Optional, cast+from typing import TYPE_CHECKING, Any, Iterable, List, Literal, Optional, castimport anthropicimport openai@@ -47,11 +48,17 @@ from backend.util import json# them here so existing ``from backend.blocks.llm import# ToolContentBlock`` imports keep working.from backend.util.llm.conversions import ToolCall, ToolContentBlock+from backend.util.llm.providers import timeout_error+from backend.util.llm.saturation import track_llm_callfrom backend.util.logging import TruncatedLoggerfrom backend.util.prompt import compress_context, estimate_token_countfrom backend.util.settings import Settingsfrom backend.util.text import TextFormatter+if TYPE_CHECKING:+ # Runtime import would cycle: data.execution imports backend.blocks.+ from backend.data.execution import ExecutionContext+settings = Settings()logger = TruncatedLogger(logging.getLogger(__name__), "[LLM-Block]")fmt = TextFormatter(autoescape=False)@@ -59,13 +66,17 @@ fmt = TextFormatter(autoescape=False)# HTTP status codes for user-caused errors that should not be reported to Sentry.USER_ERROR_STATUS_CODES = (401, 403, 429)-# Hard cap on a single provider HTTP request. Healthy non-streaming Responses /-# Messages calls finish in seconds; anything past this is almost certainly a-# stalled socket (server keeping connection alive but starving response bytes,-# which the SDK's read-timeout doesn't reliably detect on its own). Lower than-# the SDK defaults (typically 600s) so retries-on-timeout don't compound into-# multi-hour worst cases when a block makes many sequential calls.-LLM_REQUEST_TIMEOUT_SECONDS = 120+# Non-streaming calls emit no bytes until the completion is done, so this+# budget has to span the entire generation, not time-to-first-byte.+LLM_REQUEST_TIMEOUT_SECONDS: int = settings.config.llm_request_timeout_seconds++# Only a cutoff that ate most of the budget was mid-inference; a fast fail burns+# nothing, and paging on those during an outage would bury the ones that cost.+_SPEND_BURNED_ELAPSED_FRACTION = 0.9++# Stable, greppable Sentry title — never interpolate into it (see #14292).+SPEND_BURNED_ALERT = "LLM call cut off mid-inference — provider billed, user refunded"+_spend_alert_logger = logging.getLogger(__name__)LLMProviderName = Literal[ProviderName.AIML_API,@@ -233,29 +244,56 @@ async def llm_call(ollama_host: str = "localhost:11434",parallel_tool_calls=None,compress_prompt_to_fit: bool = True,+ execution_context: "ExecutionContext | None" = None,) -> LLMResponse:- """Public LLM-call entry point. Wraps the provider dispatch in a hard timeout- so that no single request can park an executor thread indefinitely."""- try:- return await asyncio.wait_for(- _llm_call(- credentials=credentials,+ """Block-side LLM entry point. Wraps the provider dispatch in a hard timeout+ so that no single request can park an executor thread indefinitely.++ Every block path funnels through here, so this is where a timed-out call is+ classified for spend alerting (#14292), including callers that never reach+ the block retry loop. Copilot and dream call the provider layer directly and+ raise no spend alert; they carry no execution context to attribute one to.+ """+ started = time.monotonic()+ with track_llm_call(+ graph_exec_id=execution_context.graph_exec_id if execution_context else None,+ provider=llm_model.metadata.provider,+ now=started,+ ):+ try:+ return await asyncio.wait_for(+ _llm_call(+ credentials=credentials,+ llm_model=llm_model,+ prompt=prompt,+ max_tokens=max_tokens,+ force_json_output=force_json_output,+ tools=tools,+ ollama_host=ollama_host,+ parallel_tool_calls=parallel_tool_calls,+ compress_prompt_to_fit=compress_prompt_to_fit,+ ),+ # Same budget as the provider layer, but this one starts before+ # prompt compression, so it always fires first for block callers;+ # the provider deadline is there for callers that skip this seam.+ timeout=LLM_REQUEST_TIMEOUT_SECONDS,+ )+ # SDK-native timeouts never reach the wait_for, so both are caught here+ # to keep this the single place that reports burned spend.+ except (+ asyncio.TimeoutError,+ openai.APITimeoutError,+ anthropic.APITimeoutError,+ ) as e:+ _log_timeout_outcome(+ elapsed=time.monotonic() - started,llm_model=llm_model,- prompt=prompt,- max_tokens=max_tokens,- force_json_output=force_json_output,- tools=tools,- ollama_host=ollama_host,- parallel_tool_calls=parallel_tool_calls,- compress_prompt_to_fit=compress_prompt_to_fit,- ),- timeout=LLM_REQUEST_TIMEOUT_SECONDS,- )- except asyncio.TimeoutError as e:- raise TimeoutError(- f"LLM request to {llm_model.metadata.provider}/{llm_model.value} "- f"exceeded {LLM_REQUEST_TIMEOUT_SECONDS}s and was cancelled."- ) from e+ execution_context=execution_context,+ error=e,+ )+ if isinstance(e, asyncio.TimeoutError):+ raise _block_timeout_error(llm_model, max_tokens) from e+ raiseasync def _llm_call(@@ -513,6 +551,7 @@ class AIStructuredResponseGeneratorBlock(AIBlockBase):compress_prompt_to_fit: bool = True,tools: list[dict] | None = None,ollama_host: str = "localhost:11434",+ execution_context: "ExecutionContext | None" = None,) -> LLMResponse:"""Test mocks work only on class functions, this wraps the llm_call function@@ -528,6 +567,7 @@ class AIStructuredResponseGeneratorBlock(AIBlockBase):tools=tools,ollama_host=ollama_host,compress_prompt_to_fit=compress_prompt_to_fit,+ execution_context=execution_context,)async def run(@@ -590,6 +630,7 @@ class AIStructuredResponseGeneratorBlock(AIBlockBase):),ollama_host=input_data.ollama_host,max_tokens=input_data.max_tokens,+ execution_context=kwargs.get("execution_context"),)response_text = llm_response.response# Accumulate token counts and provider_cost for every attempt@@ -717,12 +758,18 @@ class AIStructuredResponseGeneratorBlock(AIBlockBase):logger.warning(f"Error calling LLM: {e}")error_feedback_message = f"Error calling LLM: {e}"break- if isinstance(e, TimeoutError):+ # The SDKs' own timeout types do NOT subclass builtin+ # TimeoutError, so they must be named explicitly or a+ # connect/read timeout burns the full retry budget.+ if isinstance(+ e,+ (TimeoutError, openai.APITimeoutError, anthropic.APITimeoutError),+ ):+ # Already classified and logged at the llm_call seam.# A request that hung once will most likely hang again on# retry — the underlying issue (server-side starvation,# network partition, etc.) doesn't clear on a fresh socket.# Skip retries to avoid the N×timeout wait cascade.- logger.warning(f"LLM call timed out, not retrying: {e}")error_feedback_message = f"Error calling LLM: {e}"breaklogger.exception(f"Error calling LLM: {e}")@@ -874,6 +921,62 @@ def trim_prompt(s: str) -> str:return "\n".join([line.strip().lstrip("|") for line in lines])+def _log_timeout_outcome(+ *,+ elapsed: float,+ llm_model: LLMModel,+ execution_context: "ExecutionContext | None",+ error: BaseException,+) -> None:+ """Classify a timed-out LLM call: burned provider spend, or a fast fail.++ The alert branch is ERROR so Sentry raises an event (LoggingIntegration+ ships event_level=ERROR); ids go in json_fields rather than the message so+ a provider incident aggregates into one issue instead of thousands. Sentry+ is the only surface — see #14292 for the paging decision.+ """+ budget = LLM_REQUEST_TIMEOUT_SECONDS+ if elapsed < budget * _SPEND_BURNED_ELAPSED_FRACTION:+ logger.warning(+ f"LLM call timed out after {elapsed:.1f}s, below the "+ f"mid-inference alert threshold, not retrying: {error}"+ )+ return++ ctx = execution_context+ # Plain stdlib logger: TruncatedLogger appends str(extra) to the message+ # text, which would re-fragment Sentry grouping by the very ids below.+ _spend_alert_logger.error(+ SPEND_BURNED_ALERT,+ extra={+ "json_fields": {+ "elapsed_seconds": round(elapsed, 1),+ "configured_timeout_seconds": budget,+ "provider": llm_model.metadata.provider,+ "model": llm_model.value,+ # A bare asyncio.TimeoutError stringifies to "", which would+ # land in Sentry as error:"" — the one field naming the cause.+ "error": str(error) or repr(error),+ "user_id": ctx.user_id if ctx else None,+ "graph_id": ctx.graph_id if ctx else None,+ "graph_exec_id": ctx.graph_exec_id if ctx else None,+ "node_id": ctx.node_id if ctx else None,+ "node_exec_id": ctx.node_exec_id if ctx else None,+ }+ },+ )+++def _block_timeout_error(llm_model: LLMModel, max_tokens: int | None) -> TimeoutError:+ """Provider-agnostic timeout text plus the one remedy only blocks expose."""+ budget = max_tokens or llm_model.max_output_tokens+ hint = f" (currently {budget})" if budget else ""+ return TimeoutError(+ f"{timeout_error(f'{llm_model.metadata.provider}/{llm_model.value}', LLM_REQUEST_TIMEOUT_SECONDS)}"+ f" You can also lower the advanced Max Tokens setting{hint}."+ )++class AITextGeneratorBlock(AIBlockBase):class Input(BlockSchemaInput):prompt: str = SchemaField(@@ -942,9 +1045,15 @@ class AITextGeneratorBlock(AIBlockBase):self,input_data: AIStructuredResponseGeneratorBlock.Input,credentials: APIKeyCredentials,+ execution_context: "ExecutionContext | None" = None,) -> dict:block = AIStructuredResponseGeneratorBlock()- response = await block.run_once(input_data, "response", credentials=credentials)+ response = await block.run_once(+ input_data,+ "response",+ credentials=credentials,+ execution_context=execution_context,+ )self.merge_llm_stats(block)return response["response"]@@ -958,7 +1067,9 @@ class AITextGeneratorBlock(AIBlockBase):},expected_format={},)- response = await self.llm_call(object_input_data, credentials)+ response = await self.llm_call(+ object_input_data, credentials, kwargs.get("execution_context")+ )yield "response", responseyield "prompt", self.prompt@@ -1032,7 +1143,7 @@ class AITextSummarizerBlock(AIBlockBase):("prompt", list),],test_mock={- "llm_call": lambda input_data, credentials: (+ "llm_call": lambda input_data, credentials, *_, **__: ({"final_summary": "Final summary of a long text"}if "final_summary" in input_data.expected_formatelse {"summary": "Summary of a chunk of text"}@@ -1043,11 +1154,16 @@ class AITextSummarizerBlock(AIBlockBase):async def run(self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs) -> BlockOutput:- async for output_name, output_data in self._run(input_data, credentials):+ async for output_name, output_data in self._run(+ input_data, credentials, kwargs.get("execution_context")+ ):yield output_name, output_dataasync def _run(- self, input_data: Input, credentials: APIKeyCredentials+ self,+ input_data: Input,+ credentials: APIKeyCredentials,+ execution_context: "ExecutionContext | None" = None,) -> BlockOutput:chunks = self._split_text(input_data.text, input_data.max_tokens, input_data.chunk_overlap@@ -1055,11 +1171,13 @@ class AITextSummarizerBlock(AIBlockBase):summaries = []for chunk in chunks:- chunk_summary = await self._summarize_chunk(chunk, input_data, credentials)+ chunk_summary = await self._summarize_chunk(+ chunk, input_data, credentials, execution_context+ )summaries.append(chunk_summary)final_summary = await self._combine_summaries(- summaries, input_data, credentials+ summaries, input_data, credentials, execution_context)yield "summary", final_summaryyield "prompt", self.prompt@@ -1096,14 +1214,24 @@ class AITextSummarizerBlock(AIBlockBase):self,input_data: AIStructuredResponseGeneratorBlock.Input,credentials: APIKeyCredentials,+ execution_context: "ExecutionContext | None" = None,) -> dict:block = AIStructuredResponseGeneratorBlock()- response = await block.run_once(input_data, "response", credentials=credentials)+ response = await block.run_once(+ input_data,+ "response",+ credentials=credentials,+ execution_context=execution_context,+ )self.merge_llm_stats(block)return responseasync def _summarize_chunk(- self, chunk: str, input_data: Input, credentials: APIKeyCredentials+ self,+ chunk: str,+ input_data: Input,+ credentials: APIKeyCredentials,+ execution_context: "ExecutionContext | None" = None,) -> str:prompt = f"Summarize the following text in a {input_data.style} form. Focus your summary on the topic of `{input_data.focus}` if present, otherwise just provide a general summary:\n\n```{chunk}```"@@ -1115,6 +1243,7 @@ class AITextSummarizerBlock(AIBlockBase):expected_format={"summary": "The summary of the given text."},),credentials=credentials,+ execution_context=execution_context,)summary = llm_response["summary"]@@ -1133,7 +1262,11 @@ class AITextSummarizerBlock(AIBlockBase):return summaryasync def _combine_summaries(- self, summaries: list[str], input_data: Input, credentials: APIKeyCredentials+ self,+ summaries: list[str],+ input_data: Input,+ credentials: APIKeyCredentials,+ execution_context: "ExecutionContext | None" = None,) -> str:combined_text = "\n\n".join(summaries)@@ -1150,6 +1283,7 @@ class AITextSummarizerBlock(AIBlockBase):},),credentials=credentials,+ execution_context=execution_context,)final_summary = llm_response["final_summary"]@@ -1178,6 +1312,7 @@ class AITextSummarizerBlock(AIBlockBase):chunk_overlap=input_data.chunk_overlap,),"summary",+ execution_context=execution_context,credentials=credentials,)@@ -1255,9 +1390,15 @@ class AIConversationBlock(AIBlockBase):self,input_data: AIStructuredResponseGeneratorBlock.Input,credentials: APIKeyCredentials,+ execution_context: "ExecutionContext | None" = None,) -> dict:block = AIStructuredResponseGeneratorBlock()- response = await block.run_once(input_data, "response", credentials=credentials)+ response = await block.run_once(+ input_data,+ "response",+ credentials=credentials,+ execution_context=execution_context,+ )self.merge_llm_stats(block)return response@@ -1288,6 +1429,7 @@ class AIConversationBlock(AIBlockBase):ollama_host=input_data.ollama_host,),credentials=credentials,+ execution_context=kwargs.get("execution_context"),)yield "response", response["response"]yield "prompt", self.prompt@@ -1385,7 +1527,7 @@ class AIListGeneratorBlock(AIBlockBase):("list_item", "Draknos"),],test_mock={- "llm_call": lambda input_data, credentials: {+ "llm_call": lambda input_data, credentials, *_, **__: {"list": ["Zylora Prime","Kharon-9",@@ -1401,10 +1543,14 @@ class AIListGeneratorBlock(AIBlockBase):self,input_data: AIStructuredResponseGeneratorBlock.Input,credentials: APIKeyCredentials,+ execution_context: "ExecutionContext | None" = None,) -> dict[str, Any]:llm_block = AIStructuredResponseGeneratorBlock()response = await llm_block.run_once(- input_data, "response", credentials=credentials+ input_data,+ "response",+ credentials=credentials,+ execution_context=execution_context,)self.merge_llm_stats(llm_block)return response@@ -1457,6 +1603,7 @@ class AIListGeneratorBlock(AIBlockBase):ollama_host=input_data.ollama_host,),credentials=credentials,+ execution_context=kwargs.get("execution_context"),)logger.debug(f"Response object: {response_obj}")diff --git a/autogpt_platform/backend/backend/blocks/orchestrator.py b/autogpt_platform/backend/backend/blocks/orchestrator.pyindex 74377d84de..8bcb0a4d8a 100644--- a/autogpt_platform/backend/backend/blocks/orchestrator.py+++ b/autogpt_platform/backend/backend/blocks/orchestrator.py@@ -882,6 +882,7 @@ class OrchestratorBlock(Block):input_data: Input,current_prompt: list[dict[str, Any]],tool_functions: list[dict[str, Any]],+ execution_context: "ExecutionContext | None" = None,) -> Any:"""Attempt a single LLM call with tool validation.@@ -891,6 +892,7 @@ class OrchestratorBlock(Block):resp = await llm.llm_call(compress_prompt_to_fit=input_data.conversation_compaction,credentials=credentials,+ execution_context=execution_context,llm_model=input_data.model,prompt=current_prompt,max_tokens=input_data.max_tokens,@@ -2159,7 +2161,11 @@ class OrchestratorBlock(Block):for _ in range(max_attempts):try:response = await self._attempt_llm_call_with_validation(- credentials, input_data, current_prompt, tool_functions+ credentials,+ input_data,+ current_prompt,+ tool_functions,+ execution_context,)breakdiff --git a/autogpt_platform/backend/backend/blocks/test/test_llm.py b/autogpt_platform/backend/backend/blocks/test/test_llm.pyindex 46a5333008..5921256b03 100644--- a/autogpt_platform/backend/backend/blocks/test/test_llm.py+++ b/autogpt_platform/backend/backend/blocks/test/test_llm.py@@ -1,4 +1,6 @@import asyncio+import contextlib+import loggingimport refrom typing import Any, castfrom unittest.mock import AsyncMock, MagicMock, patch@@ -9,7 +11,12 @@ import openaiimport pytestimport backend.blocks.llm as llm+from backend.blocks._base import DEFAULT_BLOCK_EXECUTION_TIMEOUT_SECONDS+from backend.data.execution import ExecutionContextfrom backend.data.model import NodeExecutionStats+from backend.util.llm import saturation+from backend.util.llm.providers import FAST_FAIL_TIMEOUT_SECONDS+from backend.util.settings import Config# TEST_CREDENTIALS_INPUT is a plain dict that satisfies AICredentials at runtime# but not at the type level. Cast once here to avoid per-test suppressors.@@ -154,7 +161,7 @@ class TestLLMStatsTracking:block = llm.AITextGeneratorBlock()# Mock the underlying structured response block- async def mock_llm_call(input_data, credentials):+ async def mock_llm_call(input_data, credentials, *_, **__):# Simulate the structured block setting statsblock.execution_stats = NodeExecutionStats(input_token_count=30,@@ -393,7 +400,7 @@ class TestLLMStatsTracking:# Track calls to simulate multiple chunkscall_count = 0- async def mock_llm_call(input_data, credentials):+ async def mock_llm_call(input_data, credentials, *_, **__):nonlocal call_countcall_count += 1@@ -508,7 +515,7 @@ class TestLLMStatsTracking:block = llm.AIConversationBlock()# Mock the llm_call method- async def mock_llm_call(input_data, credentials):+ async def mock_llm_call(input_data, credentials, *_, **__):block.execution_stats = NodeExecutionStats(input_token_count=100,output_token_count=50,@@ -551,7 +558,7 @@ class TestLLMStatsTracking:block = llm.AIListGeneratorBlock()# Mock the llm_call to return a structured response- async def mock_llm_call(input_data, credentials):+ async def mock_llm_call(input_data, credentials, *_, **__):# Update stats to simulate LLM callblock.execution_stats = NodeExecutionStats(input_token_count=50,@@ -696,7 +703,7 @@ class TestAIConversationBlockValidation:"""Empty messages but a non-empty prompt should proceed without error."""block = llm.AIConversationBlock()- async def mock_llm_call(input_data, credentials):+ async def mock_llm_call(input_data, credentials, *_, **__):return {"response": "OK"}with patch.object(block, "llm_call", new=AsyncMock(side_effect=mock_llm_call)):@@ -720,7 +727,7 @@ class TestAIConversationBlockValidation:"""Non-empty messages with no prompt should proceed without error."""block = llm.AIConversationBlock()- async def mock_llm_call(input_data, credentials):+ async def mock_llm_call(input_data, credentials, *_, **__):return {"response": "response from conversation"}with patch.object(block, "llm_call", new=AsyncMock(side_effect=mock_llm_call)):@@ -831,7 +838,7 @@ class TestAITextSummarizerValidation:block = llm.AITextSummarizerBlock()# Mock llm_call to return a list instead of a string- async def mock_llm_call(input_data, credentials):+ async def mock_llm_call(input_data, credentials, *_, **__):# Simulate LLM returning a list when it should return a stringreturn {"summary": ["bullet point 1", "bullet point 2", "bullet point 3"]}@@ -866,7 +873,7 @@ class TestAITextSummarizerValidation:block = llm.AITextSummarizerBlock()# Mock llm_call to return a list instead of a string- async def mock_llm_call(input_data, credentials):+ async def mock_llm_call(input_data, credentials, *_, **__):# Check if this is the final summary callif "final_summary" in input_data.expected_format:# Simulate LLM returning a list when it should return a string@@ -912,7 +919,7 @@ class TestAITextSummarizerValidation:block = llm.AITextSummarizerBlock()# Mock llm_call to return a valid string- async def mock_llm_call(input_data, credentials):+ async def mock_llm_call(input_data, credentials, *_, **__):return {"summary": "This is a valid string summary"}block.llm_call = mock_llm_call # type: ignore@@ -942,7 +949,7 @@ class TestAITextSummarizerValidation:block = llm.AITextSummarizerBlock()# Mock llm_call to return a valid string- async def mock_llm_call(input_data, credentials):+ async def mock_llm_call(input_data, credentials, *_, **__):return {"final_summary": "This is a valid final summary string"}block.llm_call = mock_llm_call # type: ignore@@ -973,7 +980,7 @@ class TestAITextSummarizerValidation:block = llm.AITextSummarizerBlock()# Mock llm_call to return a dict instead of a string- async def mock_llm_call(input_data, credentials):+ async def mock_llm_call(input_data, credentials, *_, **__):return {"summary": {"nested": "object", "with": "data"}}block.llm_call = mock_llm_call # type: ignore@@ -1463,6 +1470,23 @@ class TestAnthropicCacheControl:class TestLLMRequestTimeout:"""Test that llm_call enforces a hard request timeout regardless of provider."""+ def test_configurable_ceiling_stays_under_the_node_cap(self):+ # Asserted on the schema bound, not the live constant: the constant is+ # env-derived, so checking it would pass or fail on the runner's+ # environment instead of on the code, and would leave a misconfigured+ # deployment unguarded. Past the node cap the node timeout fires first+ # and replaces the provider/model error with a generic one.+ bound = next(+ (+ m.le+ for m in Config.model_fields["llm_request_timeout_seconds"].metadata+ if getattr(m, "le", None) is not None+ ),+ None,+ )+ assert bound is not None, "llm_request_timeout_seconds lost its upper bound"+ assert bound < DEFAULT_BLOCK_EXECUTION_TIMEOUT_SECONDS+@pytest.mark.asyncioasync def test_llm_call_times_out_when_provider_hangs(self, monkeypatch):"""A hanging provider call must not park the caller indefinitely."""@@ -1485,7 +1509,10 @@ class TestLLMRequestTimeout:max_tokens=100,)- assert "0.2s" in str(exc_info.value) or "exceeded" in str(exc_info.value)+ msg = str(exc_info.value)+ assert "0.2s" in msg and "exceeded" in msg+ # The remediation hint is the user-visible half of this error.+ assert "shorten the prompt" in msg@pytest.mark.asyncioasync def test_llm_call_passes_timeout_to_openai_sdk(self):@@ -1514,7 +1541,289 @@ class TestLLMRequestTimeout:max_tokens=100,)- assert captured_kwargs.get("timeout") == llm.LLM_REQUEST_TIMEOUT_SECONDS+ # The generation budget lands on the read phase; connect stays short so+ # a blackholed SYN can't park a worker for the whole deadline.+ sdk_timeout = captured_kwargs["timeout"]+ assert isinstance(sdk_timeout, httpx.Timeout)+ assert sdk_timeout.read == llm.LLM_REQUEST_TIMEOUT_SECONDS+ assert sdk_timeout.connect == FAST_FAIL_TIMEOUT_SECONDS++ @pytest.mark.parametrize(+ "exc_factory",+ [+ pytest.param(lambda: TimeoutError("builtin"), id="builtin"),+ pytest.param(+ lambda: openai.APITimeoutError(+ request=httpx.Request("POST", "http://x")+ ),+ id="openai-sdk",+ ),+ pytest.param(+ lambda: anthropic.APITimeoutError(+ request=httpx.Request("POST", "http://x")+ ),+ id="anthropic-sdk",+ ),+ ],+ )+ @pytest.mark.asyncio+ async def test_sdk_timeouts_also_break_the_retry_loop(self, exc_factory):+ """The SDK timeout types do NOT subclass builtin TimeoutError, so a+ connect/read timeout would otherwise burn the whole retry budget with a+ retry-prompt appended — the opposite of the no-retry-on-timeout rule."""+ calls = {"n": 0}++ async def always_timeout(*args, **kwargs):+ calls["n"] += 1+ raise exc_factory()++ with patch("openai.AsyncOpenAI") as mock_openai:+ mock_client = AsyncMock()+ mock_openai.return_value = mock_client+ mock_client.responses.create = AsyncMock(side_effect=always_timeout)++ block = llm.AIStructuredResponseGeneratorBlock()+ input_data = llm.AIStructuredResponseGeneratorBlock.Input(+ prompt="Hello",+ expected_format={"key": "value"},+ model=llm.DEFAULT_LLM_MODEL,+ credentials=llm.TEST_CREDENTIALS_INPUT, # type: ignore+ retry=5,+ )+ with pytest.raises(RuntimeError):+ async for _ in block.run(input_data, credentials=llm.TEST_CREDENTIALS):+ pass++ assert calls["n"] == 1, f"timeout was retried {calls['n']}x instead of breaking"++ async def _run_block_expecting_failure(self, side_effect, retry=3, ctx=None):+ with patch("openai.AsyncOpenAI") as mock_openai:+ mock_client = AsyncMock()+ mock_openai.return_value = mock_client+ mock_client.responses.create = AsyncMock(side_effect=side_effect)+ block = llm.AIStructuredResponseGeneratorBlock()+ input_data = llm.AIStructuredResponseGeneratorBlock.Input(+ prompt="Hello",+ expected_format={"key": "value"},+ model=llm.DEFAULT_LLM_MODEL,+ credentials=llm.TEST_CREDENTIALS_INPUT, # type: ignore+ retry=retry,+ )+ extra = {"execution_context": ctx} if ctx is not None else {}+ with pytest.raises(RuntimeError):+ async for _ in block.run(+ input_data, credentials=llm.TEST_CREDENTIALS, **extra+ ):+ pass++ @staticmethod+ @contextlib.contextmanager+ def _captured_logs():+ """Attach to the module logger directly. Going through caplog's root+ handler silently captured nothing under the app's logging config, which+ is how a batch of assert-absence tests passed without ever running."""+ records: list[logging.LogRecord] = []++ class _Collect(logging.Handler):+ def emit(self, record):+ records.append(record)++ target = llm.logger.logger+ handler = _Collect(level=logging.DEBUG)+ target.addHandler(handler)+ previous = target.level+ target.setLevel(logging.DEBUG)+ try:+ yield records+ finally:+ target.removeHandler(handler)+ target.setLevel(previous)++ @staticmethod+ def _alerts(records):+ # Containment, not equality: the app's log config wraps record.msg in+ # ANSI colour codes, so an == match silently finds nothing.+ return [r for r in records if llm.SPEND_BURNED_ALERT in r.getMessage()]++ @pytest.mark.parametrize(+ "elapsed, budget, alerts",+ [+ (0.5, 100, False), # fast fail: nothing was generated+ (89.0, 100, False), # just under the threshold+ (91.0, 100, True), # just over: inference ran, provider billed+ (100.0, 100, True), # the full budget+ ],+ )+ def test_burn_threshold_classifies_by_elapsed_fraction(+ self, monkeypatch, elapsed, budget, alerts+ ):+ """The 0.9 threshold is the new business logic, so pin it either side.+ Both degenerate budgets (0 / 3600) leave it free to be any value."""+ monkeypatch.setattr(llm, "LLM_REQUEST_TIMEOUT_SECONDS", budget)+ with self._captured_logs() as records:+ llm._log_timeout_outcome(+ elapsed=elapsed,+ llm_model=llm.DEFAULT_LLM_MODEL,+ execution_context=None,+ error=TimeoutError("x"),+ )+ assert bool(self._alerts(records)) is alerts++ def test_a_bare_timeout_still_names_its_cause(self, monkeypatch):+ """``str(asyncio.TimeoutError())`` is "", and ``error`` is the only field+ in the alert that says what went wrong."""+ monkeypatch.setattr(llm, "LLM_REQUEST_TIMEOUT_SECONDS", 100)+ with self._captured_logs() as records:+ llm._log_timeout_outcome(+ elapsed=99.0,+ llm_model=llm.DEFAULT_LLM_MODEL,+ execution_context=None,+ error=asyncio.TimeoutError(),+ )+ assert self._alerts(records)[0].json_fields["error"] == "TimeoutError()"++ @pytest.mark.asyncio+ async def test_real_cutoff_alerts_once_with_searchable_ids(self, monkeypatch):+ """End-to-end through the seam: a provider that never answers, cut off by+ a real (small, non-zero) budget — 2s, not 0.2s: block setup and prompt+ compression take ~0.3s locally and longer on CI, and a budget that races+ them means the provider mock is never entered and the test proves+ nothing. The ids are what an on-call needs to find+ the run that burned money — they live in json_fields, not the message, so+ Sentry aggregates a provider incident into one issue."""+ monkeypatch.setattr(llm, "LLM_REQUEST_TIMEOUT_SECONDS", 2.0)+ provider_calls = {"n": 0}++ async def never_answers(**kwargs):+ provider_calls["n"] += 1+ await asyncio.sleep(30)++ ctx = ExecutionContext(+ user_id="u-1",+ graph_id="g-1",+ graph_exec_id="ge-1",+ node_id="n-1",+ node_exec_id="ne-1",+ )+ with self._captured_logs() as records:+ await self._run_block_expecting_failure(never_answers, ctx=ctx)++ assert provider_calls["n"] == 1, "the provider mock was never actually called"+ alerts = self._alerts(records)+ assert len(alerts) == 1, f"expected exactly 1 alert, got {len(alerts)}"+ assert alerts[0].levelno == logging.ERROR, "must be ERROR so Sentry raises it"+ fields = alerts[0].json_fields+ assert fields["user_id"] == "u-1"+ assert fields["graph_id"] == "g-1"+ assert fields["graph_exec_id"] == "ge-1"+ assert fields["node_id"] == "n-1"+ assert fields["node_exec_id"] == "ne-1"+ assert fields["provider"] == "openai"+ assert fields["configured_timeout_seconds"] == 2.0++ @pytest.mark.asyncio+ async def test_ids_survive_the_run_once_delegation(self, monkeypatch):+ """AITextGeneratorBlock reaches the structured block through run_once,+ which forwards only what it is handed. An alert with every id None is+ useless to the on-call it wakes."""+ monkeypatch.setattr(llm, "LLM_REQUEST_TIMEOUT_SECONDS", 2.0)++ async def never_answers(**kwargs):+ await asyncio.sleep(30)++ ctx = ExecutionContext(+ user_id="u-2",+ graph_id="g-2",+ graph_exec_id="ge-2",+ node_id="n-2",+ node_exec_id="ne-2",+ )+ with self._captured_logs() as records:+ with patch("openai.AsyncOpenAI") as mock_openai:+ mock_client = AsyncMock()+ mock_openai.return_value = mock_client+ mock_client.responses.create = AsyncMock(side_effect=never_answers)+ block = llm.AITextGeneratorBlock()+ input_data = llm.AITextGeneratorBlock.Input(+ prompt="Hello",+ model=llm.DEFAULT_LLM_MODEL,+ credentials=llm.TEST_CREDENTIALS_INPUT, # type: ignore+ )+ with pytest.raises(RuntimeError):+ async for _ in block.run(+ input_data,+ credentials=llm.TEST_CREDENTIALS,+ execution_context=ctx,+ ):+ pass++ alerts = self._alerts(records)+ assert len(alerts) == 1, f"expected exactly 1 alert, got {len(alerts)}"+ assert alerts[0].json_fields["user_id"] == "u-2"+ assert alerts[0].json_fields["node_exec_id"] == "ne-2"++ @pytest.mark.asyncio+ async def test_fast_failure_warns_instead_of_alerting(self, monkeypatch):+ """A connect-phase failure burns no provider spend; paging on it during an+ outage would bury the cutoffs that cost money. Asserts the warning is+ actually emitted — absence alone would pass against a no-op helper."""+ monkeypatch.setattr(llm, "LLM_REQUEST_TIMEOUT_SECONDS", 3600)++ with self._captured_logs() as records:+ await self._run_block_expecting_failure(+ openai.APITimeoutError(request=httpx.Request("POST", "http://x"))+ )++ assert not self._alerts(records)+ assert [+ r+ for r in records+ if r.levelno == logging.WARNING+ and "below the mid-inference alert threshold" in r.getMessage()+ ], "the sub-threshold branch must still say what happened"++ @pytest.mark.asyncio+ async def test_the_seam_registers_the_call_for_saturation(self):+ """Wiring guard: the saturation warning is only as good as this. Read+ from the real registry while the provider call is in flight."""+ seen: dict = {}++ async def observe(**kwargs):+ seen["runs"] = [c.graph_exec_id for c in saturation._in_flight.values()]+ seen["providers"] = [c.provider for c in saturation._in_flight.values()]+ response = MagicMock()+ response.output_text = '{"key": "value"}'+ response.output = []+ response.usage = MagicMock(input_tokens=1, output_tokens=1)+ return response++ ctx = ExecutionContext(+ user_id="u-1",+ graph_id="g-1",+ graph_exec_id="ge-1",+ node_id="n-1",+ node_exec_id="ne-1",+ )+ with patch("openai.AsyncOpenAI") as mock_openai:+ mock_client = AsyncMock()+ mock_openai.return_value = mock_client+ mock_client.responses.create = AsyncMock(side_effect=observe)+ block = llm.AIStructuredResponseGeneratorBlock()+ input_data = llm.AIStructuredResponseGeneratorBlock.Input(+ prompt="Hello",+ expected_format={"key": "value"},+ model=llm.DEFAULT_LLM_MODEL,+ credentials=llm.TEST_CREDENTIALS_INPUT, # type: ignore+ force_json_output=True,+ )+ async for _ in block.run(+ input_data, credentials=llm.TEST_CREDENTIALS, execution_context=ctx+ ):+ pass++ assert seen["runs"] == ["ge-1"], "the seam did not register the in-flight call"+ assert seen["providers"] == ["openai"]+ assert not saturation._in_flight, "the call must be released on the way out"@pytest.mark.asyncioasync def test_structured_block_does_not_retry_on_timeout(self, monkeypatch):diff --git a/autogpt_platform/backend/backend/copilot/dream/llm.py b/autogpt_platform/backend/backend/copilot/dream/llm.pyindex 0cd8e2b545..b5f208c4c3 100644--- a/autogpt_platform/backend/backend/copilot/dream/llm.py+++ b/autogpt_platform/backend/backend/copilot/dream/llm.py@@ -40,12 +40,7 @@ from typing import Generic, TypeVarfrom pydantic import BaseModel, ValidationErrorfrom backend.copilot.transport_routing import routing_kwargs_for_chat_transport-from backend.util.llm.providers import (- DEFAULT_REQUEST_TIMEOUT_SECONDS,- ProviderLiteral,- ProviderResponse,- call_provider,-)+from backend.util.llm.providers import ProviderLiteral, ProviderResponse, call_providerlogger = logging.getLogger(__name__)@@ -98,7 +93,7 @@ async def structured_completion(response_model: type[T],temperature: float = 0.2,max_output_tokens: int = 4096,- timeout_seconds: float = DEFAULT_REQUEST_TIMEOUT_SECONDS,+ timeout_seconds: float | None = None,) -> StructuredCompletion[T]:"""Call the LLM in JSON mode and parse into ``response_model``.@@ -107,11 +102,10 @@ async def structured_completion(token counts + cost up into a ``DreamPassUsage``.``timeout_seconds`` is the wall-clock budget for the provider call.- The shared 120s default is sized for short chat completions; dream- phases with large ``max_output_tokens`` budgets (recombine/sanitize- at 16384) must pass their own ceiling — see the per-phase- ``*_TIMEOUT_SECONDS`` constants in ``orchestrator.py`` — or real- long responses die on TimeoutError before they finish decoding.+ The shared default is a generic block-call budget; dream phases are+ sized against the pass's own scheduler/lock envelope and must pass+ their own ceiling — see the per-phase ``*_TIMEOUT_SECONDS`` constants+ in ``orchestrator.py`` — rather than inherit it.Raises ``DreamLLMError`` if the response is empty, unparseable, orfails Pydantic validation. Callers should treat that as "thisdiff --git a/autogpt_platform/backend/backend/copilot/dream/llm_test.py b/autogpt_platform/backend/backend/copilot/dream/llm_test.pyindex 5c3de24ecc..329cfd2ce7 100644--- a/autogpt_platform/backend/backend/copilot/dream/llm_test.py+++ b/autogpt_platform/backend/backend/copilot/dream/llm_test.py@@ -15,7 +15,7 @@ import pytestfrom pydantic import BaseModelfrom backend.copilot.transport_routing import ProviderRoutingKwargs-from backend.util.llm.providers import DEFAULT_REQUEST_TIMEOUT_SECONDS, ProviderResponse+from backend.util.llm.providers import ProviderResponsefrom .llm import (DreamLLMError,@@ -261,7 +261,7 @@ class TestStructuredCompletionDelegation:assert call_provider_mock.call_args.kwargs["timeout_seconds"] == 600@pytest.mark.asyncio- async def test_omitted_timeout_falls_back_to_shared_default(self):+ async def test_omitted_timeout_defers_to_call_provider(self):"""Callers that don't pass a phase budget (none in-tree, but thesignature allows it) keep the conservative shared default ratherthan an unbounded request."""@@ -282,10 +282,10 @@ class TestStructuredCompletionDelegation:response_model=_SampleOutput,)- assert (- call_provider_mock.call_args.kwargs["timeout_seconds"]- == DEFAULT_REQUEST_TIMEOUT_SECONDS- )+ # Forwards the sentinel rather than a def-time snapshot of the setting,+ # so call_provider resolves the live value — same contract as every+ # other entry point.+ assert call_provider_mock.call_args.kwargs["timeout_seconds"] is None@pytest.mark.asyncioasync def test_routes_to_ollama_under_local_transport(self):diff --git a/autogpt_platform/backend/backend/copilot/dream/orchestrator.py b/autogpt_platform/backend/backend/copilot/dream/orchestrator.pyindex 4eeb594814..b74d3eae1c 100644--- a/autogpt_platform/backend/backend/copilot/dream/orchestrator.py+++ b/autogpt_platform/backend/backend/copilot/dream/orchestrator.py@@ -93,12 +93,12 @@ RECOMBINE_MAX_TOKENS = 16384SANITIZE_MAX_TOKENS = 16384# Per-phase LLM wall-clock ceilings, passed through structured_completion-# → call_provider. The shared DEFAULT_REQUEST_TIMEOUT_SECONDS (120s) is-# sized for short chat completions; recombine/sanitize carry 16384-token-# output budgets precisely because real responses exceed 8192 tokens, and-# at real decode speeds (Opus-class ~40-60 tok/s via OpenRouter) an 8-16K-# response takes 150-400s — the 120s wall killed exactly the responses-# the token-cap raise above was meant to save.+# → call_provider. These exist because a single shared default can't fit+# every phase: recombine/sanitize carry 16384-token output budgets precisely+# because real responses exceed 8192 tokens, and at real decode speeds+# (Opus-class ~40-60 tok/s via OpenRouter) an 8-16K response takes 150-400s,+# so a ceiling under that truncates exactly the responses the token-cap+# budgets above exist to produce.## A conservative ~20 tok/s decode floor would ask for max_output_tokens/20# ≈ 205s / 819s / 819s per phase, but that sums to 1843s of LLM budgetdiff --git a/autogpt_platform/backend/backend/copilot/dream/orchestrator_test.py b/autogpt_platform/backend/backend/copilot/dream/orchestrator_test.pyindex f1c8c5d5fa..068e5f33b7 100644--- a/autogpt_platform/backend/backend/copilot/dream/orchestrator_test.py+++ b/autogpt_platform/backend/backend/copilot/dream/orchestrator_test.py@@ -15,7 +15,6 @@ from unittest.mock import AsyncMock, MagicMockimport pytestfrom backend.executor.scheduler import SCHEDULER_DREAM_OPERATION_TIMEOUT_SECONDS-from backend.util.llm.providers import DEFAULT_REQUEST_TIMEOUT_SECONDSfrom . import orchestrator as orchestrator_modfrom .apply import INGESTION_DRAIN_TIMEOUT_SECONDS, LOCK_DRAIN_RENEWAL_SECONDS@@ -452,17 +451,19 @@ async def test_each_phase_threads_its_own_llm_timeout_into_structured_completion]-def test_long_output_phase_timeouts_exceed_the_shared_request_default():- """Regression pin: every phase used to run on the shared 120s- ``DEFAULT_REQUEST_TIMEOUT_SECONDS``, which cannot decode the 16384- output tokens recombine/sanitize are budgeted for. If these ever- drop back to (or below) the default, the token-cap raise becomes- dead letter again."""- assert orchestrator_mod.RECOMBINE_TIMEOUT_SECONDS > DEFAULT_REQUEST_TIMEOUT_SECONDS- assert orchestrator_mod.SANITIZE_TIMEOUT_SECONDS > DEFAULT_REQUEST_TIMEOUT_SECONDS- assert (- orchestrator_mod.CONSOLIDATE_TIMEOUT_SECONDS >= DEFAULT_REQUEST_TIMEOUT_SECONDS- )+# A 120s ceiling truncates a 16384-token decode. Pinned as a literal, not+# imported from `DEFAULT_REQUEST_TIMEOUT_SECONDS`: that setting sizes generic+# block calls and is free to move independently of this budget.+_TRUNCATING_TIMEOUT_SECONDS = 120+++def test_long_output_phase_timeouts_clear_the_120s_truncation_threshold():+ """Regression pin: at 120s the phases cannot decode the 16384 output+ tokens recombine/sanitize are budgeted for. If these ever drop to (or+ below) that, the token-cap raise becomes dead letter again."""+ assert orchestrator_mod.RECOMBINE_TIMEOUT_SECONDS > _TRUNCATING_TIMEOUT_SECONDS+ assert orchestrator_mod.SANITIZE_TIMEOUT_SECONDS > _TRUNCATING_TIMEOUT_SECONDS+ assert orchestrator_mod.CONSOLIDATE_TIMEOUT_SECONDS >= _TRUNCATING_TIMEOUT_SECONDSdef test_phase_timeouts_plus_headroom_fit_scheduler_and_lock_envelope():diff --git a/autogpt_platform/backend/backend/copilot/service.py b/autogpt_platform/backend/backend/copilot/service.pyindex a27a594429..6044a2ec51 100644--- a/autogpt_platform/backend/backend/copilot/service.py+++ b/autogpt_platform/backend/backend/copilot/service.py@@ -49,6 +49,9 @@ _TITLE_MAX_WORDS = 6_TITLE_MAX_CHARS = 50_TITLE_ELLIPSIS = "..."_TITLE_TRUNCATED_MAX_CHARS = _TITLE_MAX_CHARS - len(_TITLE_ELLIPSIS)+# A 20-token title must not inherit the block-sized LLM default; it runs in a+# background task holding a slot in the shared aux-client pool.+_TITLE_TIMEOUT_SECONDS = 30def resolve_chat_model(tier: CopilotLLMModel | None) -> str:@@ -864,6 +867,7 @@ async def _generate_session_title(},],max_tokens=20,+ timeout_seconds=_TITLE_TIMEOUT_SECONDS,extra_body=extra_body or None,)except Exception as e:diff --git a/autogpt_platform/backend/backend/copilot/service_unit_test.py b/autogpt_platform/backend/backend/copilot/service_unit_test.pyindex 9b87bc771b..23e3877987 100644--- a/autogpt_platform/backend/backend/copilot/service_unit_test.py+++ b/autogpt_platform/backend/backend/copilot/service_unit_test.py@@ -22,12 +22,14 @@ from openai.types.chat.chat_completion_message import ChatCompletionMessagefrom openai.types.completion_usage import CompletionUsagefrom backend.copilot.service import (+ _TITLE_TIMEOUT_SECONDS,_fallback_title_from_message,_generate_session_title,_record_title_generation_cost,_title_usage_from_response,_update_title_async,)+from backend.util.settings import Configdef _build_completion(@@ -545,6 +547,15 @@ class TestGenerateSessionTitle:)assert title == "Clean Me"assert response is resp+ # A 20-token title must not inherit the block-sized LLM default: it+ # runs in a background task holding a slot in the shared aux pool.+ assert helper.await_args.kwargs["timeout_seconds"] == _TITLE_TIMEOUT_SECONDS+ # Against the shipped default, not the running config: 30 is a legal+ # LLM_REQUEST_TIMEOUT_SECONDS (ge=30) and would make this compare equal.+ assert (+ _TITLE_TIMEOUT_SECONDS+ < Config.model_fields["llm_request_timeout_seconds"].default+ )@pytest.mark.asyncioasync def test_long_title_truncated_with_ellipsis(self):diff --git a/autogpt_platform/backend/backend/executor/manager.py b/autogpt_platform/backend/backend/executor/manager.pyindex 7134592466..3f7139b96b 100644--- a/autogpt_platform/backend/backend/executor/manager.py+++ b/autogpt_platform/backend/backend/executor/manager.py@@ -74,6 +74,7 @@ from backend.util.exceptions import (get_execution_failure_reason,)from backend.util.file import clean_exec_files+from backend.util.llm.saturation import set_executor_idfrom backend.util.logging import TruncatedLogger, configure_loggingfrom backend.util.process import AppProcess, set_service_namefrom backend.util.retry import (@@ -1591,6 +1592,7 @@ class ExecutionManager(AppProcess):logger.info(f"[{self.service_name}] ⏳ Spawn max-{self.pool_size} workers...")pool_size_gauge.set(self.pool_size)+ set_executor_id(self.executor_id)self._update_prompt_metrics()# Deliberate reuse of pyro_host: despite the legacy name it is the# bind address for every service's internal listener (seediff --git a/autogpt_platform/backend/backend/util/llm/providers.py b/autogpt_platform/backend/backend/util/llm/providers.pyindex 509131aa66..2b1f935f75 100644--- a/autogpt_platform/backend/backend/util/llm/providers.py+++ b/autogpt_platform/backend/backend/util/llm/providers.py@@ -38,6 +38,7 @@ from datetime import datetime, timezonefrom typing import Any, Literal, castimport anthropic+import httpximport ollamaimport openaifrom openai.types.chat import ChatCompletionMessageParam, ChatCompletionToolParam@@ -73,13 +74,30 @@ settings = Settings()logger = logging.getLogger(__name__)-# Hard cap on a single provider HTTP request. Mirrors-# ``backend/blocks/llm.py::LLM_REQUEST_TIMEOUT_SECONDS``. Healthy-# non-streaming Messages / Responses calls finish in seconds; anything-# past 120s is almost certainly a stalled socket and retries-on-timeout-# would compound into multi-hour worst cases. Batch and flex paths-# override this where appropriate.-DEFAULT_REQUEST_TIMEOUT_SECONDS = 120+# Non-streaming calls emit no bytes until the completion is done, so this+# budget has to span the entire generation, not time-to-first-byte.+DEFAULT_REQUEST_TIMEOUT_SECONDS: int = settings.config.llm_request_timeout_seconds++# The phases where no generation happens: waiting on a SYN, or queueing for a+# free connection. Only read/write carry the generation budget. 5.0 matches the+# OpenAI/Anthropic SDK connect default.+FAST_FAIL_TIMEOUT_SECONDS = 5.0+++def request_timeout(timeout_seconds: float) -> httpx.Timeout:+ """Bound one request: generation budget on read/write, fast-fail elsewhere.++ A scalar would set every phase, so a blackholed SYN — or, on the one shared+ client (the copilot aux singleton), a saturated pool — would park a worker+ for the whole deadline. Per-call clients are uncontended on the pool phase;+ the pin costs them nothing.+ """+ return httpx.Timeout(+ timeout_seconds,+ connect=FAST_FAIL_TIMEOUT_SECONDS,+ pool=FAST_FAIL_TIMEOUT_SECONDS,+ )+# Provider names accepted by ``call_provider``. Kept as a string Literal# (not an enum) so the helper stays provider-name-agnostic — callers@@ -206,7 +224,7 @@ async def call_provider(parallel_tool_calls: bool | openai.Omit = openai.omit,ollama_host: str = "localhost:11434",custom_id: str | None = None,- timeout_seconds: float = DEFAULT_REQUEST_TIMEOUT_SECONDS,+ timeout_seconds: float | None = None,) -> ProviderResponse | BatchSubmissionRef:"""Dispatch a single LLM call to the correct provider SDK.@@ -218,8 +236,13 @@ async def call_provider(Raises ``TimeoutError`` if the call exceeds ``timeout_seconds``(sync mode only; batch submissions are bounded by the provider's- own SLA and the poller's own timeout policy).+ own SLA and the poller's own timeout policy). ``timeout_seconds=None``+ reads ``DEFAULT_REQUEST_TIMEOUT_SECONDS`` when the call is made, so a+ test can monkeypatch it; the value itself is still read from settings+ once, at import."""+ if timeout_seconds is None:+ timeout_seconds = DEFAULT_REQUEST_TIMEOUT_SECONDSif execution_mode == "batch":if not custom_id:raise ValueError(@@ -278,10 +301,7 @@ async def call_provider(timeout=timeout_seconds,)except asyncio.TimeoutError as exc:- raise TimeoutError(- f"LLM request to {provider}/{model} exceeded "- f"{timeout_seconds}s and was cancelled."- ) from exc+ raise timeout_error(f"{provider}/{model}", timeout_seconds) from exc# ---------------------------------------------------------------------------@@ -474,7 +494,7 @@ async def _call_openai_responses(# See OPEN-3187.store=False,include=["reasoning.encrypted_content"],- timeout=timeout_seconds,+ timeout=request_timeout(timeout_seconds),# ``omit`` is only valid for TYPED params — the SDK strips it# there. ``extra_body`` flows raw into ``options.extra_json``# (``make_request_options`` checks ``is not None``), and@@ -556,7 +576,7 @@ async def _call_anthropic_messages(messages=anth_messages,max_tokens=max_tokens,tools=an_tools,- timeout=timeout_seconds,+ timeout=request_timeout(timeout_seconds),)if temperature is not None and _anthropic_accepts_temperature(model):create_kwargs["temperature"] = temperature@@ -667,7 +687,7 @@ async def _call_groq(messages=messages,response_format=response_format,max_tokens=max_tokens,- timeout=timeout_seconds,+ timeout=request_timeout(timeout_seconds),)# Same guard as the Anthropic path — only send ``temperature`` when# the caller set one, so models that reject it never see the field.@@ -715,7 +735,9 @@ async def _call_ollama(if temperature is not None:options["temperature"] = temperature- client = ollama.AsyncClient(host=ollama_host, timeout=timeout_seconds)+ client = ollama.AsyncClient(+ host=ollama_host, timeout=request_timeout(timeout_seconds)+ )response = await client.chat(model=model,messages=messages,@@ -830,7 +852,7 @@ async def _call_openai_compat(if force_json_outputelse openai.omit),- timeout=timeout_seconds,+ timeout=request_timeout(timeout_seconds),)# Same guard as the Anthropic path — only send ``temperature`` when# the caller set one, so upstreams that reject it (some reasoning@@ -1021,7 +1043,7 @@ async def call_provider_openai_compat_sync(api_key: str | None = None,extra_body: dict[str, Any] | None = None,extra_headers: dict[str, str] | None = None,- timeout_seconds: float = DEFAULT_REQUEST_TIMEOUT_SECONDS,+ timeout_seconds: float | None = None,client_factory: type[openai.AsyncOpenAI] = openai.AsyncOpenAI,) -> Any:"""Non-streaming OpenAI-compat chat call, returns the raw SDK@@ -1037,6 +1059,8 @@ async def call_provider_openai_compat_sync(+ (optionally) ``client_factory``. See ``call_provider_stream``for rationale."""+ if timeout_seconds is None:+ timeout_seconds = DEFAULT_REQUEST_TIMEOUT_SECONDSsanitize_messages_for_utf8(messages)if client is None:if base_url is None or api_key is None:@@ -1049,13 +1073,31 @@ async def call_provider_openai_compat_sync("model": model,"messages": cast(list[ChatCompletionMessageParam], messages),"max_tokens": max_tokens,- "timeout": timeout_seconds,+ "timeout": request_timeout(timeout_seconds),}if extra_body:create_kwargs["extra_body"] = extra_bodyif extra_headers:create_kwargs["extra_headers"] = extra_headers- return await client.chat.completions.create(**create_kwargs)+ # Same total-duration guarantee as ``call_provider``: the per-request httpx+ # timeout alone is per ATTEMPT, and the SDK's own max_retries multiplies it.+ try:+ return await asyncio.wait_for(+ client.chat.completions.create(**create_kwargs),+ timeout=timeout_seconds,+ )+ except asyncio.TimeoutError as exc:+ raise timeout_error(model, timeout_seconds) from exc+++def timeout_error(target: str, timeout_seconds: float) -> TimeoutError:+ """Provider-agnostic timeout text. The block layer adds its own UI-specific+ remedy, which does not belong in a module dream/briefing/copilot also use."""+ return TimeoutError(+ f"LLM request to {target} exceeded {timeout_seconds}s and was cancelled. "+ "If the model was still generating, shorten the prompt or pick a faster "+ "model."+ )# ---------------------------------------------------------------------------diff --git a/autogpt_platform/backend/backend/util/llm/providers_test.py b/autogpt_platform/backend/backend/util/llm/providers_test.pyindex 5b59cfef4e..e414f5dac7 100644--- a/autogpt_platform/backend/backend/util/llm/providers_test.py+++ b/autogpt_platform/backend/backend/util/llm/providers_test.py@@ -9,6 +9,8 @@ fields each provider exposes.from __future__ import annotations+import asyncio+import contextlibfrom contextlib import contextmanagerfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, patch@@ -16,14 +18,20 @@ from unittest.mock import AsyncMock, MagicMock, patchimport anthropicimport httpximport pytest+from pydantic import ValidationError+from backend.util.llm import providers as providers_modfrom backend.util.llm.providers import (DEFAULT_REQUEST_TIMEOUT_SECONDS,+ FAST_FAIL_TIMEOUT_SECONDS,ProviderResponse,_anthropic_accepts_temperature,_is_temperature_deprecation_error,call_provider,+ call_provider_openai_compat_sync,+ request_timeout,)+from backend.util.settings import Config, Settingsdef _msg(role: str, content: str) -> dict:@@ -896,7 +904,9 @@ class TestOllama:assert result.content == '{"facts": []}'assert result.prompt_tokens == 7assert result.completion_tokens == 9- ctor.assert_called_once_with(host="http://gpu-box:11434", timeout=42.0)+ ctor.assert_called_once_with(+ host="http://gpu-box:11434", timeout=request_timeout(42.0)+ )class TestOllamaTrustedHosts:@@ -1402,11 +1412,238 @@ class TestUtf8Sanitization:# ---------------------------------------------------------------------------+class TestTimeoutThreading:+ """Every SDK call site reached through ``call_provider`` must receive the+ bounded ``httpx.Timeout``.++ A site that silently loses it reverts to the SDK default. On Anthropic+ that is worse than slow: ``_calculate_nonstreaming_timeout`` raises+ ``ValueError("Streaming is required ...")`` above ~21333 max_tokens when+ no explicit timeout is passed, so high-``max_tokens`` calls hard-fail.+ """++ @staticmethod+ @contextlib.contextmanager+ def _sdk_site(kind: str, capture):+ """Install a fake client for one provider branch; `capture` sees the+ kwargs the SDK is called with."""+ if kind == "anthropic":+ response = SimpleNamespace(+ content=[SimpleNamespace(type="text", text="ok")],+ usage=SimpleNamespace(+ input_tokens=1,+ output_tokens=1,+ cache_read_input_tokens=0,+ cache_creation_input_tokens=0,+ ),+ stop_reason="end_turn",+ )+ client = SimpleNamespace(messages=SimpleNamespace(create=capture(response)))+ with patch(+ "backend.util.llm.providers.anthropic.AsyncAnthropic",+ return_value=client,+ ):+ yield+ elif kind == "chat_completions":+ response = _fake_openai_chat_response("ok", prompt=1, completion=1)+ client = SimpleNamespace(+ chat=SimpleNamespace(+ completions=SimpleNamespace(create=capture(response))+ )+ )+ with patch("groq.AsyncGroq", return_value=client), patch(+ "backend.util.llm.providers.openai.AsyncOpenAI", return_value=client+ ):+ yield+ else: # the default `openai` branch: Responses API + its extractors+ client = SimpleNamespace(+ responses=SimpleNamespace(create=capture(SimpleNamespace()))+ )+ with patch(+ "backend.util.llm.providers.openai.AsyncOpenAI", return_value=client+ ), patch(+ "backend.util.llm.providers.extract_responses_tool_calls",+ return_value=None,+ ), patch(+ "backend.util.llm.providers.extract_responses_content",+ return_value="ok",+ ), patch(+ "backend.util.llm.providers.extract_responses_reasoning",+ return_value=None,+ ), patch(+ "backend.util.llm.providers.extract_responses_usage",+ return_value=(1, 1),+ ):+ yield++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "kind, provider, model, api_key",+ [+ ("anthropic", "anthropic", "claude-sonnet-4-6", "sk-test"),+ ("chat_completions", "groq", "llama-3.3-70b", "gsk-test"),+ ("chat_completions", "open_router", "anthropic/claude-sonnet-4.6", "sk-or"),+ ("responses", "openai", "gpt-4.1", "sk-test"),+ ],+ )+ async def test_every_sdk_site_receives_the_bounded_timeout(+ self, kind, provider, model, api_key+ ):+ seen: dict = {}++ def capture(response):+ async def _create(**kwargs):+ seen.update(kwargs)+ return response++ return _create++ with self._sdk_site(kind, capture):+ await call_provider(+ provider=provider,+ model=model,+ api_key=api_key,+ messages=[_msg("user", "hi")],+ max_tokens=10,+ timeout_seconds=42.0,+ )+ assert seen["timeout"] == request_timeout(42.0)++ @pytest.mark.asyncio+ async def test_call_provider_omitted_timeout_resolves_at_call_time(+ self, monkeypatch+ ):+ """The headline configurability, on the PRIMARY dispatch path. Hardcoding+ the default back to 120 passed every other test in this file."""+ monkeypatch.setattr(providers_mod, "DEFAULT_REQUEST_TIMEOUT_SECONDS", 321.0)+ seen: dict = {}++ def capture(response):+ async def _create(**kwargs):+ seen.update(kwargs)+ return response++ return _create++ with self._sdk_site("responses", capture):+ await call_provider(+ provider="openai",+ model="gpt-4.1",+ api_key="sk-test",+ messages=[_msg("user", "hi")],+ max_tokens=10,+ )+ assert seen["timeout"] == request_timeout(321.0)++ @pytest.mark.asyncio+ async def test_openai_compat_sync_helper_receives_bounded_timeout(self):+ captured: dict = {}++ async def capture(**kwargs):+ captured.update(kwargs)+ return _fake_openai_chat_response("ok", prompt=1, completion=1)++ fake_client = SimpleNamespace(+ chat=SimpleNamespace(completions=SimpleNamespace(create=capture))+ )+ await call_provider_openai_compat_sync(+ model="gpt-4.1",+ messages=[_msg("user", "hi")],+ max_tokens=10,+ client=fake_client,+ timeout_seconds=42.0,+ )+ assert captured["timeout"] == request_timeout(42.0)++ @pytest.mark.asyncio+ async def test_sync_helper_bounds_total_duration(self):+ """The httpx timeout is per ATTEMPT and the SDK retries on top of it,+ so the helper needs its own wall-clock bound like ``call_provider``."""++ async def hang(**kwargs):+ await asyncio.sleep(60)++ fake_client = SimpleNamespace(+ chat=SimpleNamespace(completions=SimpleNamespace(create=hang))+ )+ with pytest.raises(TimeoutError):+ await call_provider_openai_compat_sync(+ model="gpt-4.1",+ messages=[_msg("user", "hi")],+ max_tokens=10,+ client=fake_client,+ timeout_seconds=0.2,+ )++class TestDefaults:- def test_default_timeout_is_120_seconds(self):- # Pin the SLA — anything bigger and a stalled provider can park- # an executor thread for too long.- assert DEFAULT_REQUEST_TIMEOUT_SECONDS == 120+ def test_default_timeout_tracks_the_setting(self):+ assert (+ DEFAULT_REQUEST_TIMEOUT_SECONDS+ == Settings().config.llm_request_timeout_seconds+ )++ def test_shipped_default_is_600_seconds(self):+ # The constant above only proves the wiring; without this the shipped+ # SLA is pinned by nothing and can drift silently.+ assert Config.model_fields["llm_request_timeout_seconds"].default == 600++ @pytest.mark.parametrize("bad", [29, 1501])+ def test_timeout_outside_the_supported_band_is_rejected(self, bad):+ # Below 30 a healthy long call dies; above 1500 the deadline no longer+ # clears the per-node cap with margin, so the node timeout can fire+ # first and hide the provider/model error.+ with pytest.raises(ValidationError) as exc:+ Config(llm_request_timeout_seconds=bad)+ assert any(+ e["loc"] == ("llm_request_timeout_seconds",) for e in exc.value.errors()+ ), "a different field's validation error would otherwise green this"++ @pytest.mark.parametrize("ok", [30, 600, 1500])+ def test_supported_band_boundaries_are_accepted(self, ok):+ assert Config(llm_request_timeout_seconds=ok).llm_request_timeout_seconds == ok++ def test_block_and_provider_layers_share_one_deadline(self):+ # A call bounded at one layer and not the other is the drift that+ # routing both through one setting exists to prevent.+ # Function-scoped so this util-side module never imports blocks at+ # import time (see settings.py on the dependency direction).+ from backend.blocks.llm import LLM_REQUEST_TIMEOUT_SECONDS++ assert LLM_REQUEST_TIMEOUT_SECONDS == DEFAULT_REQUEST_TIMEOUT_SECONDS++ @pytest.mark.asyncio+ async def test_omitted_timeout_resolves_the_setting_at_call_time(self, monkeypatch):+ """The headline feature: the deadline follows the config field. Bound as+ a def-time default it would freeze, and this would still pass at the+ shipped value — so patch to a distinctive one."""+ monkeypatch.setattr(providers_mod, "DEFAULT_REQUEST_TIMEOUT_SECONDS", 123.0)+ captured: dict = {}++ async def capture(**kwargs):+ captured.update(kwargs)+ return _fake_openai_chat_response("ok", prompt=1, completion=1)++ fake_client = SimpleNamespace(+ chat=SimpleNamespace(completions=SimpleNamespace(create=capture))+ )+ await call_provider_openai_compat_sync(+ model="gpt-4.1",+ messages=[_msg("user", "hi")],+ max_tokens=10,+ client=fake_client,+ )+ assert captured["timeout"] == request_timeout(123.0)++ def test_request_timeout_pins_connect_and_budgets_the_rest(self):+ # No generation happens while a SYN goes unanswered, so connect is+ # pinned; read/write/pool carry the generation budget.+ t = request_timeout(DEFAULT_REQUEST_TIMEOUT_SECONDS)+ assert t.connect == FAST_FAIL_TIMEOUT_SECONDS+ assert t.read == DEFAULT_REQUEST_TIMEOUT_SECONDS+ assert t.write == DEFAULT_REQUEST_TIMEOUT_SECONDS+ # Queueing for a connection is not generation either.+ assert t.pool == FAST_FAIL_TIMEOUT_SECONDS# ---------------------------------------------------------------------------diff --git a/autogpt_platform/backend/backend/util/llm/saturation.py b/autogpt_platform/backend/backend/util/llm/saturation.pynew file mode 100644index 0000000000..0e6d4d36fe--- /dev/null+++ b/autogpt_platform/backend/backend/util/llm/saturation.py@@ -0,0 +1,140 @@+"""Report when every graph worker is parked on a slow LLM call.++Raising the per-call deadline to 600s means one degraded provider can occupy+every worker for ten minutes. Nothing else reports that state: the executor's+utilization gauge shows the workers as busy, which is indistinguishable from+healthy load.+"""++import contextlib+import logging+import threading+import time+from collections import Counter as _Counter+from typing import Iterator++from prometheus_client import Counter, Gauge+from pydantic import BaseModel++from backend.util.settings import Settings++logger = logging.getLogger(__name__)+settings = Settings()++# A worker holds one graph run, so distinct graph runs with a long call in+# flight is the closest proxy for "workers occupied" reachable from this seam.+SATURATION_CALL_AGE_SECONDS = 60.0++# Saturation is reached by calls AGEING, not by new ones arriving, so a fully+# stuck fleet would never re-evaluate on its own.+_TICK_SECONDS = 15.0++saturated_workers_gauge = Gauge(+ "llm_saturated_graph_workers",+ "Graph runs blocked on an LLM call older than the saturation age",+)+saturation_episodes_counter = Counter(+ "llm_worker_saturation_episodes_total",+ "Times every graph worker was simultaneously blocked on a slow LLM call",+)+++def track_llm_call(+ *, graph_exec_id: str | None, provider: str, now: float | None = None+) -> Iterator[None]:+ """Register one in-flight LLM call for the duration of the block.++ ``graph_exec_id`` is None for callers that do not occupy a graph worker+ (copilot, dream, briefing); those are excluded from the count.+ """+ call = _Call(+ graph_exec_id=graph_exec_id,+ provider=provider,+ started=now if now is not None else time.monotonic(),+ )+ token = object()+ with _lock:+ _in_flight[id(token)] = call+ _ensure_ticker()+ try:+ yield+ finally:+ with _lock:+ _in_flight.pop(id(token), None)+ # Keep `token` alive to here: id() is only unique while it is.+ del token+++def evaluate_saturation(now: float | None = None) -> int:+ """Refresh the gauge; report once on entering saturation. Returns the count."""+ global _saturated+ now = now if now is not None else time.monotonic()+ cutoff = now - SATURATION_CALL_AGE_SECONDS++ with _lock:+ slow: dict[str, list[_Call]] = {}+ for call in _in_flight.values():+ if call.graph_exec_id is None or call.started > cutoff:+ continue+ slow.setdefault(call.graph_exec_id, []).append(call)++ count = len(slow)+ saturated = count > 0 and count >= settings.config.num_graph_workers+ episode: str | None = None+ if saturated and not _saturated:+ calls = [c for group in slow.values() for c in group]+ mix = _Counter(c.provider for c in calls).most_common()+ episode = (+ f"LLM worker saturation: all {count} graph workers on executor "+ f"{_executor_id} are blocked on an LLM call older than "+ f"{SATURATION_CALL_AGE_SECONDS:.0f}s. "+ f"providers={', '.join(f'{p}={n}' for p, n in mix)} "+ f"longest_call_age={now - min(c.started for c in calls):.0f}s"+ )+ _saturated = saturated++ saturated_workers_gauge.set(count)+ if episode:+ saturation_episodes_counter.inc()+ # ERROR, not WARNING: metrics.py registers LoggingIntegration() with its+ # default event_level=ERROR, so a warning reaches no alerting surface.+ logger.error(episode)+ return count+++def set_executor_id(executor_id: str) -> None:+ """Name the pod in the warning; without it an alert can't be routed."""+ global _executor_id+ _executor_id = executor_id+++class _Call(BaseModel, frozen=True):+ graph_exec_id: str | None+ provider: str+ started: float+++def _ensure_ticker() -> None:+ """Start the re-evaluation thread on first use; caller holds ``_lock``."""+ global _ticker+ if _ticker is not None:+ return+ _ticker = threading.Thread(target=_tick_forever, daemon=True, name="llm-saturation")+ _ticker.start()+++def _tick_forever() -> None:+ while True:+ time.sleep(_TICK_SECONDS)+ try:+ evaluate_saturation()+ except Exception: # a metrics thread must never take the process down+ logger.exception("LLM saturation check failed")+++_lock = threading.Lock()+_in_flight: dict[int, _Call] = {}+_saturated = False+_executor_id = "unknown"+_ticker: threading.Thread | None = Nonediff --git a/autogpt_platform/backend/backend/util/llm/saturation_test.py b/autogpt_platform/backend/backend/util/llm/saturation_test.pynew file mode 100644index 0000000000..5f63a3b4f1--- /dev/null+++ b/autogpt_platform/backend/backend/util/llm/saturation_test.py@@ -0,0 +1,180 @@+import contextlib+import logging+import threading++import pytest++from backend.util.llm import saturation++WORKERS = 3++[email protected](autouse=True)+def _isolated_state(monkeypatch):+ monkeypatch.setattr(saturation.settings.config, "num_graph_workers", WORKERS)+ monkeypatch.setattr(saturation, "_in_flight", {})+ monkeypatch.setattr(saturation, "_saturated", False)+ monkeypatch.setattr(saturation, "_executor_id", "exec-1")+ # Non-None keeps _ensure_ticker from spawning its daemon thread per test.+ monkeypatch.setattr(saturation, "_ticker", threading.current_thread())+++def _warnings():+ """Attach to the module logger directly — caplog captures nothing for+ backend.* loggers under the app's logging config."""+ records: list[logging.LogRecord] = []++ class _Collect(logging.Handler):+ def emit(self, record):+ records.append(record)++ handler = _Collect(level=logging.DEBUG)+ saturation.logger.addHandler(handler)+ try:+ yield records+ finally:+ saturation.logger.removeHandler(handler)+++def _busy(count: int, started: float, provider: str = "openai", first: int = 0):+ """`count` graph runs, each holding one LLM call started at `started`."""+ with contextlib.ExitStack() as stack:+ for i in range(first, first + count):+ stack.enter_context(+ saturation.track_llm_call(+ graph_exec_id=f"run-{i}", provider=provider, now=started+ )+ )+ yield+++def test_warns_once_while_saturation_persists():+ with _busy(WORKERS, started=0.0), _warnings() as records:+ assert saturation.evaluate_saturation(now=59.0) == 0, "not old enough yet"+ assert not records++ assert saturation.evaluate_saturation(now=61.0) == WORKERS+ assert len(records) == 1, "entering saturation must warn"++ saturation.evaluate_saturation(now=120.0)+ saturation.evaluate_saturation(now=600.0)+ assert len(records) == 1, "a persisting episode must not warn again"+++def test_the_warning_carries_what_an_operator_needs():+ with _busy(2, started=0.0, provider="openai"), _busy(+ 1, started=10.0, provider="anthropic", first=2+ ), _warnings() as records:+ saturation.evaluate_saturation(now=100.0)++ assert len(records) == 1+ # ERROR is the mechanism: LoggingIntegration()'s default event_level drops+ # anything lower, so a WARNING here would reach no alerting surface.+ assert records[0].levelno == logging.ERROR+ msg = records[0].getMessage()+ assert "exec-1" in msg, "an alert that can't name the pod can't be routed"+ assert "openai=2" in msg and "anthropic=1" in msg+ assert "longest_call_age=100s" in msg+++def test_a_second_episode_warns_again():+ with _warnings() as records:+ with _busy(WORKERS, started=0.0):+ saturation.evaluate_saturation(now=61.0)+ assert len(records) == 1+ assert saturation.evaluate_saturation(now=62.0) == 0, "calls released"++ with _busy(WORKERS, started=100.0):+ saturation.evaluate_saturation(now=161.0)+ assert len(records) == 2, "a new episode is a new warning"+++def test_one_free_worker_is_not_saturation():+ with _busy(WORKERS - 1, started=0.0), _warnings() as records:+ assert saturation.evaluate_saturation(now=600.0) == WORKERS - 1+ assert not records+++def test_parallel_calls_in_one_run_occupy_one_worker():+ """A graph with two LLM nodes in flight still holds a single worker."""+ with contextlib.ExitStack() as stack, _warnings() as records:+ for _ in range(WORKERS * 2):+ stack.enter_context(+ saturation.track_llm_call(+ graph_exec_id="run-0", provider="openai", now=0.0+ )+ )+ assert saturation.evaluate_saturation(now=600.0) == 1+ assert not records+++def test_callers_without_a_graph_run_are_excluded():+ """Copilot, dream and briefing do not occupy graph workers."""+ with contextlib.ExitStack() as stack, _warnings() as records:+ for _ in range(WORKERS * 2):+ stack.enter_context(+ saturation.track_llm_call(+ graph_exec_id=None, provider="openai", now=0.0+ )+ )+ assert saturation.evaluate_saturation(now=600.0) == 0+ assert not records+++def test_the_episode_counter_tracks_the_warnings():+ before = saturation.saturation_episodes_counter._value.get()+ with _busy(WORKERS, started=0.0):+ saturation.evaluate_saturation(now=61.0)+ saturation.evaluate_saturation(now=62.0)+ assert saturation.saturation_episodes_counter._value.get() == before + 1+++def test_the_first_tracked_call_starts_one_daemon_ticker(monkeypatch):+ """Every other test stubs `_ticker`, so this is the only place the thread the+ module rests on is really started."""+ monkeypatch.setattr(saturation, "_ticker", None)+ monkeypatch.setattr(saturation, "_TICK_SECONDS", 0.01)+ ticked = threading.Event()+ parked = threading.Event() # never set++ def _evaluate(now=None):+ ticked.set()+ # Park the daemon inside the stub: `while True` has no other exit, and a+ # thread left looping would call the real evaluator for the whole session.+ parked.wait()+ return 0++ monkeypatch.setattr(saturation, "evaluate_saturation", _evaluate)++ with saturation.track_llm_call(graph_exec_id="run-0", provider="openai"):+ ticker = saturation._ticker+ with saturation.track_llm_call(graph_exec_id="run-1", provider="openai"):+ assert saturation._ticker is ticker, "one ticker per process, not per call"++ assert ticker is not None, "the first tracked call must start the ticker"+ assert ticker.daemon, "a non-daemon ticker would hold the process open at exit"+ assert ticked.wait(timeout=5), "the ticker never re-evaluated"+++def test_the_ticker_keeps_ticking_after_a_failed_evaluation(monkeypatch):+ """A metrics thread that dies on one bad evaluation stops reporting for the+ life of the pod, silently."""+ monkeypatch.setattr(saturation, "_TICK_SECONDS", 0)+ calls: list[int] = []++ def _evaluate(now=None):+ calls.append(len(calls))+ if len(calls) == 1:+ raise RuntimeError("evaluation blew up")+ if len(calls) == 3:+ raise SystemExit # BaseException: the only way out of `while True`+ return 0++ monkeypatch.setattr(saturation, "evaluate_saturation", _evaluate)+ with _warnings() as records, pytest.raises(SystemExit):+ saturation._tick_forever()++ assert len(calls) == 3, "one failed evaluation must not stop the timer"+ assert [r.levelno for r in records] == [logging.ERROR], "the failure must be logged"diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.pyindex ea2d9fd163..ae6601ddc3 100644--- a/autogpt_platform/backend/backend/util/settings.py+++ b/autogpt_platform/backend/backend/util/settings.py@@ -178,6 +178,21 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):default=300,description="The default timeout in seconds, for RPC client calls.",)+ llm_request_timeout_seconds: int = Field(+ default=600,+ ge=30,+ # Literal rather than an import of DEFAULT_BLOCK_EXECUTION_TIMEOUT_SECONDS+ # (1800): util must not import blocks. test_llm.py asserts this bound+ # stays under that cap, whatever it is set to.+ le=1500,+ description=(+ "Wall-clock cap on a single LLM provider request, covering the whole "+ "generation (the block path is non-streaming). Raising it lengthens how "+ "long a stalled provider holds one of `num_graph_workers` slots. "+ "AgentExecutor and AutoPilot opt out of the per-node cap, so for those "+ "this is the only per-call wall-clock bound."+ ),+ )enable_auth: bool = Field(default=True,description="If authentication is enabled or not",