fix: stream internal model calls with idle timeouts (#5730)
* fix: stream internal model calls with idle timeouts * fix(providers): reject streams without terminal events
This commit is contained in:
1 parent
aeb7b207d7
commit
73410e0217
60 files changed
+815
-795
No files matched your search
+1
-13
@@ -78,10 +78,7 @@ from nanobot.security.workspace_access import (
|
||||
)
|
||||
from nanobot.session import turn_continuation
|
||||
from nanobot.session.automation_turns import automation_history_overrides
|
||||
from nanobot.session.goal_state import (
|
||||
goal_state_runtime_lines,
|
||||
runner_wall_llm_timeout_s,
|
||||
)
|
||||
from nanobot.session.goal_state import goal_state_runtime_lines
|
||||
from nanobot.session.history_visibility import HIDDEN_HISTORY_META
|
||||
from nanobot.session.keys import UNIFIED_SESSION_KEY, remember_last_channel
|
||||
from nanobot.session.manager import SESSION_CACHE_MAX_SIZE, Session, SessionManager
|
||||
@@ -395,7 +392,6 @@ class AgentLoop:
|
||||
disabled_skills=disabled_skills,
|
||||
max_iterations=self.max_iterations,
|
||||
max_concurrent_subagents=max_concurrent_subagents,
|
||||
llm_wall_timeout_for_session=lambda sk: runner_wall_llm_timeout_s(self.sessions, sk),
|
||||
)
|
||||
self._unified_session = unified_session
|
||||
self._running = False
|
||||
@@ -1207,14 +1203,6 @@ class AgentLoop:
|
||||
),
|
||||
injection_callback=_drain_pending,
|
||||
terminal_injection_callback=_wait_for_pending,
|
||||
# Sustained goals may legitimately exceed NANOBOT_LLM_TIMEOUT_S; idle stall
|
||||
# is still capped by NANOBOT_STREAM_IDLE_TIMEOUT_S in streaming providers.
|
||||
llm_timeout_s=runner_wall_llm_timeout_s(
|
||||
self.sessions,
|
||||
session.key if session is not None else request_ctx.session_key,
|
||||
metadata=session_metadata,
|
||||
message_metadata=request_metadata,
|
||||
),
|
||||
continuation_callback=_goal_continue,
|
||||
finalize_on_max_iterations=turn_continuation.should_finalize_on_max_iterations(
|
||||
pending_queue_available=pending_queue is not None and session is not None,
|
||||
|
||||
@@ -899,7 +899,7 @@ class MemoryArchiver:
|
||||
|
||||
try:
|
||||
with llm_usage_source("dream"):
|
||||
response = await runtime.provider.chat_with_retry(
|
||||
response = await runtime.provider.chat_stream_with_retry(
|
||||
model=runtime.model,
|
||||
messages=request_messages,
|
||||
tools=call_tools,
|
||||
|
||||
+4
-60
@@ -4,7 +4,6 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import inspect
|
||||
import os
|
||||
import time
|
||||
from collections.abc import Awaitable, Callable, Iterable
|
||||
from copy import deepcopy
|
||||
@@ -109,7 +108,6 @@ class AgentRunSpec:
|
||||
consolidate_provider_compaction: ProviderCompactionConsolidator | None = None
|
||||
injection_callback: InjectionCallback | None = None
|
||||
terminal_injection_callback: InjectionCallback | None = None
|
||||
llm_timeout_s: float | None = None
|
||||
continuation_callback: ContinuationCallback | None = None
|
||||
finalize_on_max_iterations: bool = True
|
||||
provider_state: ProviderConversationState | None = None
|
||||
@@ -873,7 +871,6 @@ class AgentRunner:
|
||||
malformed_retry: bool = False,
|
||||
transcript: list[dict[str, Any]] | None,
|
||||
) -> tuple[LLMResponse, LLMUsage]:
|
||||
timeout_s = self._resolve_llm_timeout_s(spec)
|
||||
tool_definitions = spec.tools.get_definitions()
|
||||
messages, provider_context = await self.context_governor.prepare_request(
|
||||
request_state,
|
||||
@@ -991,44 +988,19 @@ class AgentRunner:
|
||||
on_stream_recover=_stream_recover,
|
||||
)
|
||||
else:
|
||||
coro = spec.runtime.provider.chat_with_retry(
|
||||
coro = spec.runtime.provider.chat_stream_with_retry(
|
||||
**kwargs,
|
||||
provider_context=provider_context,
|
||||
)
|
||||
|
||||
# Streaming requests also have provider-level idle timeouts
|
||||
# (NANOBOT_STREAM_IDLE_TIMEOUT_S), but a stream that keeps producing
|
||||
# very slow deltas can still run forever. Use a more generous wall-clock
|
||||
# timeout for streaming while preserving NANOBOT_LLM_TIMEOUT_S=0 as an
|
||||
# opt-out for all LLM wall-clock timeouts.
|
||||
outer_timeout_s = (
|
||||
max(300.0, timeout_s * 2)
|
||||
if wants_streaming and timeout_s is not None
|
||||
else timeout_s
|
||||
)
|
||||
# Providers bound the wait for each stream event, including reasoning and tool deltas.
|
||||
request_started_at = time.perf_counter()
|
||||
try:
|
||||
response = (
|
||||
await coro if outer_timeout_s is None
|
||||
else await asyncio.wait_for(coro, timeout=outer_timeout_s)
|
||||
)
|
||||
response = await coro
|
||||
except asyncio.CancelledError:
|
||||
_pause_generation()
|
||||
await _close_native_reasoning()
|
||||
raise
|
||||
except asyncio.TimeoutError:
|
||||
if outer_timeout_s is None:
|
||||
response = LLMResponse(
|
||||
content="Error calling LLM: stream stalled",
|
||||
finish_reason="error",
|
||||
error_kind="timeout",
|
||||
)
|
||||
else:
|
||||
response = LLMResponse(
|
||||
content=f"Error calling LLM: timed out after {outer_timeout_s:g}s",
|
||||
finish_reason="error",
|
||||
error_kind="timeout",
|
||||
)
|
||||
_pause_generation()
|
||||
await _close_native_reasoning()
|
||||
if first_output_at is not None:
|
||||
@@ -1261,23 +1233,10 @@ class AgentRunner:
|
||||
messages,
|
||||
tools=None,
|
||||
)
|
||||
coro = spec.runtime.provider.chat_with_retry(
|
||||
response = await spec.runtime.provider.chat_stream_with_retry(
|
||||
**kwargs,
|
||||
provider_context=provider_context,
|
||||
)
|
||||
timeout_s = self._resolve_llm_timeout_s(spec)
|
||||
try:
|
||||
response = (
|
||||
await coro
|
||||
if timeout_s is None
|
||||
else await asyncio.wait_for(coro, timeout=timeout_s)
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
response = LLMResponse(
|
||||
content=f"Error calling LLM: timed out after {timeout_s:g}s",
|
||||
finish_reason="error",
|
||||
error_kind="timeout",
|
||||
)
|
||||
await self.context_governor.summarize_provider_compaction(
|
||||
request_state,
|
||||
response,
|
||||
@@ -1286,21 +1245,6 @@ class AgentRunner:
|
||||
request_state.provider_compaction_applied |= response.provider_compaction_applied
|
||||
return response
|
||||
|
||||
@staticmethod
|
||||
def _resolve_llm_timeout_s(spec: AgentRunSpec) -> float | None:
|
||||
"""Resolve the wall-clock limit shared by every model request path."""
|
||||
timeout_s = spec.llm_timeout_s
|
||||
if timeout_s is None:
|
||||
# Default to a finite timeout to avoid per-session lock starvation when an LLM
|
||||
# request hangs indefinitely (e.g. gateway/network stall).
|
||||
# Set NANOBOT_LLM_TIMEOUT_S=0 to disable.
|
||||
raw = os.environ.get("NANOBOT_LLM_TIMEOUT_S", "300").strip()
|
||||
try:
|
||||
timeout_s = float(raw)
|
||||
except (TypeError, ValueError):
|
||||
timeout_s = 300.0
|
||||
return timeout_s if timeout_s > 0 else None
|
||||
|
||||
@staticmethod
|
||||
def _budget_exhausted_finalization_messages(
|
||||
messages: list[dict[str, Any]],
|
||||
|
||||
@@ -8,7 +8,7 @@ import warnings
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, NotRequired, TypedDict
|
||||
from typing import Any, NotRequired, TypedDict
|
||||
|
||||
from loguru import logger
|
||||
|
||||
@@ -105,7 +105,6 @@ class SubagentManager:
|
||||
disabled_skills: list[str] | None = None,
|
||||
max_iterations: int | None = None,
|
||||
max_concurrent_subagents: int | None = None,
|
||||
llm_wall_timeout_for_session: Callable[[str | None], float | None] | None = None,
|
||||
):
|
||||
if workspace is None:
|
||||
raise TypeError("SubagentManager.__init__() missing required argument: 'workspace'")
|
||||
@@ -151,7 +150,6 @@ class SubagentManager:
|
||||
self._run_slots = asyncio.Semaphore(self.max_concurrent_subagents)
|
||||
self.runner = AgentRunner()
|
||||
self._exec_session_manager = ExecSessionManager()
|
||||
self._llm_wall_timeout_for_session = llm_wall_timeout_for_session
|
||||
self._running_tasks: dict[str, asyncio.Task[str]] = {}
|
||||
self._task_statuses: dict[str, SubagentStatus] = {}
|
||||
self._session_tasks: dict[str, set[str]] = {} # session_key -> {task_id, ...}
|
||||
@@ -417,11 +415,6 @@ class SubagentManager:
|
||||
]
|
||||
|
||||
sess_key = origin.get("session_key")
|
||||
llm_timeout = (
|
||||
self._llm_wall_timeout_for_session(sess_key)
|
||||
if self._llm_wall_timeout_for_session
|
||||
else None
|
||||
)
|
||||
request_token = bind_request_context(RequestContext(
|
||||
channel=origin["channel"],
|
||||
chat_id=origin["chat_id"],
|
||||
@@ -444,7 +437,6 @@ class SubagentManager:
|
||||
checkpoint_callback=_on_checkpoint,
|
||||
session_key=sess_key,
|
||||
workspace=root,
|
||||
llm_timeout_s=llm_timeout,
|
||||
llm_usage_source=origin.get(
|
||||
"llm_usage_source",
|
||||
current_llm_usage_source(),
|
||||
|
||||
@@ -784,6 +784,7 @@ class AnthropicProvider(LLMProvider):
|
||||
reasoning_effort, tool_choice,
|
||||
)
|
||||
idle_timeout_s = resolve_stream_idle_timeout_s()
|
||||
kwargs["timeout"] = idle_timeout_s
|
||||
try:
|
||||
async with self._client.messages.stream(**kwargs) as stream:
|
||||
# Idle timeout must track *any* SSE chunk (thinking_delta,
|
||||
@@ -848,6 +849,8 @@ class AnthropicProvider(LLMProvider):
|
||||
"arguments_delta": partial,
|
||||
})
|
||||
response = await stream.get_final_message()
|
||||
if not response.stop_reason:
|
||||
raise ConnectionError("Model stream ended before a stop reason was received")
|
||||
return self._parse_response(response)
|
||||
except asyncio.TimeoutError:
|
||||
return LLMResponse(
|
||||
|
||||
@@ -19,8 +19,9 @@ Two modes are supported, selected automatically:
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
from collections.abc import Awaitable, Callable
|
||||
from collections.abc import AsyncIterator, Awaitable, Callable
|
||||
from typing import Any, cast
|
||||
|
||||
from loguru import logger
|
||||
@@ -31,6 +32,7 @@ from nanobot.providers.base import (
|
||||
LLMResponse,
|
||||
ProviderCallContext,
|
||||
ProviderConversationState,
|
||||
resolve_stream_idle_timeout_s,
|
||||
)
|
||||
from nanobot.providers.openai_responses import (
|
||||
ResponsesStreamCapture,
|
||||
@@ -250,8 +252,11 @@ class AzureOpenAIProvider(LLMProvider):
|
||||
body: dict[str, Any],
|
||||
) -> Any:
|
||||
"""Retry once without server compaction when Azure rejects the option."""
|
||||
request_options: dict[str, Any] = (
|
||||
{"timeout": resolve_stream_idle_timeout_s()} if body.get("stream") else {}
|
||||
)
|
||||
try:
|
||||
return cast(Any, await self._client.responses.create(**body))
|
||||
return cast(Any, await self._client.responses.create(**body, **request_options))
|
||||
except Exception as exc:
|
||||
if (
|
||||
"context_management" not in body
|
||||
@@ -265,7 +270,7 @@ class AzureOpenAIProvider(LLMProvider):
|
||||
"instance (status={})",
|
||||
getattr(exc, "status_code", None),
|
||||
)
|
||||
return cast(Any, await self._client.responses.create(**body))
|
||||
return cast(Any, await self._client.responses.create(**body, **request_options))
|
||||
|
||||
@staticmethod
|
||||
def _handle_error(e: Exception) -> LLMResponse:
|
||||
@@ -377,22 +382,34 @@ class AzureOpenAIProvider(LLMProvider):
|
||||
on_tool_call_delta: Callable[[dict[str, Any]], Awaitable[None]] | None = None,
|
||||
provider_context: ProviderCallContext | None = None,
|
||||
) -> LLMResponse:
|
||||
_ = on_thinking_delta
|
||||
body = self._build_body(
|
||||
messages, tools, model, max_tokens, temperature,
|
||||
reasoning_effort, tool_choice,
|
||||
provider_context,
|
||||
)
|
||||
body["stream"] = True
|
||||
idle_timeout_s = resolve_stream_idle_timeout_s()
|
||||
|
||||
try:
|
||||
stream = await self._create_response_with_compaction_fallback(body)
|
||||
|
||||
async def _timed_stream() -> AsyncIterator[Any]:
|
||||
stream_iter: AsyncIterator[Any] = stream.__aiter__()
|
||||
while True:
|
||||
try:
|
||||
yield await asyncio.wait_for(
|
||||
stream_iter.__anext__(), timeout=idle_timeout_s,
|
||||
)
|
||||
except StopAsyncIteration:
|
||||
break
|
||||
|
||||
capture = ResponsesStreamCapture()
|
||||
content, tool_calls, finish_reason, usage, reasoning_content = (
|
||||
await consume_sdk_stream(
|
||||
stream,
|
||||
_timed_stream(),
|
||||
on_content_delta,
|
||||
on_tool_call_delta,
|
||||
on_reasoning_delta=on_thinking_delta,
|
||||
capture=capture,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -1321,14 +1321,17 @@ class LLMProvider(ABC):
|
||||
streaming should override this method.
|
||||
"""
|
||||
_ = on_thinking_delta, on_tool_call_delta
|
||||
response = await self.chat(
|
||||
messages=messages,
|
||||
tools=tools,
|
||||
model=model,
|
||||
max_tokens=max_tokens,
|
||||
temperature=temperature,
|
||||
reasoning_effort=reasoning_effort,
|
||||
tool_choice=tool_choice,
|
||||
response = await asyncio.wait_for(
|
||||
self.chat(
|
||||
messages=messages,
|
||||
tools=tools,
|
||||
model=model,
|
||||
max_tokens=max_tokens,
|
||||
temperature=temperature,
|
||||
reasoning_effort=reasoning_effort,
|
||||
tool_choice=tool_choice,
|
||||
),
|
||||
timeout=resolve_stream_idle_timeout_s(),
|
||||
)
|
||||
if on_content_delta and response.content:
|
||||
await on_content_delta(response.content)
|
||||
|
||||
@@ -75,6 +75,7 @@ class BedrockProvider(LLMProvider):
|
||||
os.environ["AWS_BEARER_TOKEN_BEDROCK"] = self.api_key
|
||||
try:
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
except ImportError as exc: # pragma: no cover - exercised only without boto3 installed
|
||||
raise RuntimeError(
|
||||
"AWS Bedrock provider requires boto3. Run `nanobot plugins enable bedrock`."
|
||||
@@ -86,7 +87,10 @@ class BedrockProvider(LLMProvider):
|
||||
boto3_module = cast(Any, boto3)
|
||||
session = boto3_module.Session(**session_kwargs)
|
||||
|
||||
client_kwargs: dict[str, Any] = {}
|
||||
idle_timeout_s = resolve_stream_idle_timeout_s()
|
||||
client_kwargs: dict[str, Any] = {
|
||||
"config": Config(connect_timeout=idle_timeout_s, read_timeout=idle_timeout_s),
|
||||
}
|
||||
if self.region:
|
||||
client_kwargs["region_name"] = self.region
|
||||
if self.api_base:
|
||||
@@ -775,7 +779,10 @@ class BedrockProvider(LLMProvider):
|
||||
)
|
||||
response = cast(
|
||||
dict[str, Any],
|
||||
await asyncio.to_thread(self._client.converse_stream, **kwargs),
|
||||
await asyncio.wait_for(
|
||||
asyncio.to_thread(self._client.converse_stream, **kwargs),
|
||||
timeout=idle_timeout_s,
|
||||
),
|
||||
)
|
||||
stream = cast(Iterator[dict[str, Any]], iter(response.get("stream") or []))
|
||||
while True:
|
||||
@@ -795,6 +802,8 @@ class BedrockProvider(LLMProvider):
|
||||
)
|
||||
if delta and on_content_delta:
|
||||
await on_content_delta(delta)
|
||||
if not state.get("stop_reason"):
|
||||
raise ConnectionError("Model stream ended before a stop reason was received")
|
||||
return self._stream_result(
|
||||
content_parts=content_parts,
|
||||
reasoning_parts=reasoning_parts,
|
||||
|
||||
@@ -568,7 +568,7 @@ def _codex_error_response(exc: Exception) -> LLMResponse:
|
||||
error_kind = "connection"
|
||||
default_detail = "network protocol error while reading response"
|
||||
should_retry = True if should_retry is None else should_retry
|
||||
elif isinstance(exc, (httpx.NetworkError, httpx.TransportError)):
|
||||
elif isinstance(exc, (ConnectionError, httpx.NetworkError, httpx.TransportError)):
|
||||
error_kind = "connection"
|
||||
default_detail = "network connection failed"
|
||||
should_retry = True if should_retry is None else should_retry
|
||||
|
||||
@@ -1376,8 +1376,11 @@ class OpenAICompatProvider(LLMProvider):
|
||||
extra_headers: dict[str, str] | None = None,
|
||||
) -> Any:
|
||||
"""Retry Responses once without server compaction on compatibility errors."""
|
||||
request_options = (
|
||||
{"timeout": resolve_stream_idle_timeout_s()} if body.get("stream") else {}
|
||||
)
|
||||
try:
|
||||
return await client.responses.create(**body, extra_headers=extra_headers)
|
||||
return await client.responses.create(**body, extra_headers=extra_headers, **request_options)
|
||||
except Exception as exc:
|
||||
if (
|
||||
"context_management" not in body
|
||||
@@ -1391,7 +1394,7 @@ class OpenAICompatProvider(LLMProvider):
|
||||
"(status={})",
|
||||
getattr(exc, "status_code", None),
|
||||
)
|
||||
return await client.responses.create(**body, extra_headers=extra_headers)
|
||||
return await client.responses.create(**body, extra_headers=extra_headers, **request_options)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Response parsing
|
||||
@@ -2123,12 +2126,14 @@ class OpenAICompatProvider(LLMProvider):
|
||||
# can surface live file-edit progress.
|
||||
kwargs.setdefault("extra_body", {})["tool_stream"] = True
|
||||
kwargs["stream"] = True
|
||||
kwargs["timeout"] = idle_timeout_s
|
||||
kwargs["stream_options"] = {"include_usage": True}
|
||||
chat_stream = cast(
|
||||
Any,
|
||||
await client.chat.completions.create(**kwargs),
|
||||
)
|
||||
chunks: list[Any] = []
|
||||
completed = False
|
||||
stream_iter: AsyncIterator[Any] = chat_stream.__aiter__()
|
||||
while True:
|
||||
try:
|
||||
@@ -2140,6 +2145,7 @@ class OpenAICompatProvider(LLMProvider):
|
||||
break
|
||||
chunks.append(chunk)
|
||||
if chunk.choices:
|
||||
completed |= bool(chunk.choices[0].finish_reason)
|
||||
delta_obj = chunk.choices[0].delta
|
||||
raw_delta_content = getattr(delta_obj, "content", None)
|
||||
if on_content_delta:
|
||||
@@ -2183,6 +2189,8 @@ class OpenAICompatProvider(LLMProvider):
|
||||
"name": str(_get(function_call, "name") or ""),
|
||||
"arguments_delta": str(_get(function_call, "arguments") or ""),
|
||||
})
|
||||
if not completed:
|
||||
raise ConnectionError("Model stream ended before a finish reason was received")
|
||||
return self._parse_chunks(chunks)
|
||||
except asyncio.TimeoutError:
|
||||
return LLMResponse(
|
||||
|
||||
@@ -368,7 +368,7 @@ async def consume_sse_with_reasoning(
|
||||
tool_calls: list[ToolCallRequest] = []
|
||||
tool_call_buffers: dict[str, dict[str, Any]] = {}
|
||||
tool_call_args_emitted: set[str] = set()
|
||||
finish_reason = "stop"
|
||||
finish_reason: str | None = None
|
||||
usage: LLMUsage | None = None
|
||||
reasoning_content: str | None = None
|
||||
streamed_reasoning = False
|
||||
@@ -558,6 +558,8 @@ async def consume_sse_with_reasoning(
|
||||
detail = event.get("error") or event.get("message") or event
|
||||
raise RuntimeError(f"Response failed: {str(detail)[:500]}")
|
||||
|
||||
if finish_reason is None:
|
||||
raise ConnectionError("Model stream ended before a terminal response event was received")
|
||||
if refusal_seen:
|
||||
finish_reason = "refusal"
|
||||
return content, tool_calls, finish_reason, usage, reasoning_content
|
||||
@@ -681,7 +683,7 @@ async def consume_sdk_stream(
|
||||
tool_calls: list[ToolCallRequest] = []
|
||||
tool_call_buffers: dict[str, dict[str, Any]] = {}
|
||||
tool_call_args_emitted: set[str] = set()
|
||||
finish_reason = "stop"
|
||||
finish_reason: str | None = None
|
||||
usage: LLMUsage | None = None
|
||||
reasoning_content: str | None = None
|
||||
streamed_reasoning = False
|
||||
@@ -852,6 +854,8 @@ async def consume_sdk_stream(
|
||||
detail = getattr(event, "error", None) or getattr(event, "message", None) or event
|
||||
raise RuntimeError(f"Response failed: {str(detail)[:500]}")
|
||||
|
||||
if finish_reason is None:
|
||||
raise ConnectionError("Model stream ended before a terminal response event was received")
|
||||
if refusal_seen:
|
||||
finish_reason = "refusal"
|
||||
return content, tool_calls, finish_reason, usage, reasoning_content
|
||||
@@ -599,7 +599,7 @@ def _xai_error_response(exc: Exception) -> LLMResponse:
|
||||
if isinstance(exc, (httpx.TimeoutException, asyncio.TimeoutError)):
|
||||
error_kind = "timeout"
|
||||
should_retry = True if should_retry is None else should_retry
|
||||
elif isinstance(exc, (httpx.NetworkError, httpx.TransportError)):
|
||||
elif isinstance(exc, (ConnectionError, httpx.NetworkError, httpx.TransportError)):
|
||||
error_kind = "connection"
|
||||
should_retry = True if should_retry is None else should_retry
|
||||
elif isinstance(exc, _XAIHTTPError):
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""Session metadata helpers for explicit sustained goals.
|
||||
|
||||
Tools set ``metadata[GOAL_STATE_KEY]``. Reads accept the legacy session key ``thread_goal``
|
||||
for older sessions. Callers use ``goal_state_runtime_lines``, ``goal_state_ws_blob``, and
|
||||
``runner_wall_llm_timeout_s`` without importing tool implementations.
|
||||
for older sessions. Callers use ``goal_state_runtime_lines`` and ``goal_state_ws_blob`` without
|
||||
importing tool implementations.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -10,8 +10,6 @@ from __future__ import annotations
|
||||
import json
|
||||
from typing import Any, Mapping, MutableMapping, cast
|
||||
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
GOAL_STATE_KEY = "goal_state"
|
||||
GOAL_COMMAND = "/goal"
|
||||
MAX_GOAL_OBJECTIVE_CHARS = 4000
|
||||
@@ -114,23 +112,3 @@ def goal_state_ws_blob(metadata: Mapping[str, Any] | None) -> dict[str, Any]:
|
||||
blob["recap"] = recap
|
||||
return blob
|
||||
return {"active": False}
|
||||
|
||||
|
||||
def runner_wall_llm_timeout_s(
|
||||
sessions: SessionManager,
|
||||
session_key: str | None,
|
||||
*,
|
||||
metadata: Mapping[str, Any] | None = None,
|
||||
message_metadata: Mapping[str, Any] | None = None,
|
||||
) -> float | None:
|
||||
"""Wall-clock cap for :class:`~nanobot.agent.runner.AgentRunner` when streaming an LLM.
|
||||
|
||||
Returns ``0.0`` to disable ``asyncio.wait_for`` around the request when this is a
|
||||
sustained-goal turn; ``None`` means use ``NANOBOT_LLM_TIMEOUT_S``. Pass in-memory
|
||||
``metadata`` when the caller already holds :attr:`~nanobot.session.manager.Session.metadata`
|
||||
for this turn.
|
||||
"""
|
||||
meta: Mapping[str, Any] | None = metadata
|
||||
if meta is None and session_key:
|
||||
meta = sessions.get_or_create(session_key).metadata
|
||||
return 0.0 if sustained_goal_turn(meta, message_metadata=message_metadata) else None
|
||||
@@ -256,7 +256,7 @@ async def maybe_generate_webui_title(
|
||||
|
||||
try:
|
||||
with llm_usage_source("system"):
|
||||
response = await provider.chat_with_retry(
|
||||
response = await provider.chat_stream_with_retry(
|
||||
[
|
||||
{
|
||||
"role": "system",
|
||||
|
||||
@@ -96,7 +96,7 @@ async def evaluate_response(
|
||||
"""
|
||||
|
||||
try:
|
||||
llm_response = await provider.chat_with_retry(
|
||||
llm_response = await provider.chat_stream_with_retry(
|
||||
messages=[
|
||||
{"role": "system", "content": evaluator_prompt},
|
||||
{"role": "user", "content": render_template(
|
||||
|
||||
Reference in new issue
Block a user