Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(llm): stream responses to an optional sink
trohitgc660c7c7d3cf
diff --git a/docs-internal/native_llm_sdk.md b/docs-internal/native_llm_sdk.mdindex dd95b802..8cf02322 100644--- a/docs-internal/native_llm_sdk.md+++ b/docs-internal/native_llm_sdk.md@@ -212,6 +212,7 @@ class LLMProvider(Protocol):max_tokens: int = 4096,thinking: Optional[ThinkingConfig] = None,tools: Optional[List[ToolDef]] = None,+ on_event: Optional[StreamSink] = None,) -> LLMResponse: ...async def fetch_models(self, api_key: str) -> List[str]: ...@@ -236,6 +237,37 @@ class LLMResponse:`thinking`, and `tool_calls` fields remain convenience views; `raw` is neverwritten to memory or Temporal history.+### Streaming (`on_event`)++`chat()` takes an optional `on_event: StreamSink`, an async callable that+receives each `StreamEvent(kind, delta)` (`kind` is `text` or `reasoning`) while+the response is written. Streaming never changes the response: the provider+still returns the whole `LLMResponse` it would have returned without a sink,+and the text deltas, joined, are its `content`. The chat answer of an employee+streams this way (see [Chat Protocol](./chat_protocol.md)).++A provider streams only when its `llm_defaults.json` block declares+`"streaming": true` (today `anthropic` and `openai`); `ChatUnifier._streams`+reads the flag, so no code branches on a provider name. For every other+provider the unifier calls `chat()` without a sink and replays the finished+response into it (reasoning, then text), so a caller sees the same events+either way, only later. How each declared provider streams:++- **Anthropic** iterates the `messages.stream(...)` context it already opened+ (`text` and `thinking` events), then takes `get_final_message()` as before.+- **OpenAI chat completions** call `create(stream=True, stream_options=+ {"include_usage": True})` and fold the chunks with the SDK's own+ `ChatCompletionStreamState`, whose `current_completion_snapshot` is parsed+ exactly like a non-streamed completion (the `.stream()` helper is not used:+ it insists on strict tools and raises on `length`).+- **OpenAI Responses** call `responses.create(stream=True)`, send+ `response.output_text.delta` and `response.reasoning_summary_text.delta`, and+ return the terminal event's `response` (`completed`, `incomplete` or+ `failed`); a stream that ends without one raises a retryable connection error.++Turning streaming on for another provider means declaring the flag after a+recorded-stream test shows its response is unchanged (`tests/llm/test_streaming.py`).+## Registry, Unifier, and Lazy SDK ClientsThe lightweight provider modules are imported eagerly so the registry isdiff --git a/server/config/llm_defaults.json b/server/config/llm_defaults.jsonindex d206a6b8..209a9169 100644--- a/server/config/llm_defaults.json+++ b/server/config/llm_defaults.json@@ -1,7 +1,7 @@{"version": "2026.09.29","last_updated": "2026-09-29",- "_description": "LLM provider defaults. popular_models drives the ordered global selector and offline fallback independently of token constraints. POLICY (2026-07-23): popular_models lists only models with >= 1M-token context windows — providers whose models are all below 1M carry an empty list and contribute nothing to the global selector (their models stay reachable via the live per-provider fetch_models dropdown). SOURCE (2026-09-26): model_registry.json, the OpenRouter snapshot, is the ground truth for the curated ids, context, max output and prices of every provider whose models it lists; an id it does not list is not curated (Mistral's -latest aliases excepted, see its note). It carries nothing for the hosts (groq, cerebras, sarvam), which keep their own documented values. base_url directly configures the nine OpenAI-compatible native providers; dedicated OpenAI, Anthropic, and Gemini providers use SDK defaults, while OpenRouter has its own gateway default. Runtime proxy credentials can override supported endpoints. Model specs are enriched by model_registry.json at runtime; kimi and mistral are the exception, because the registry files their models under moonshotai/ and mistralai/, so their maps here are what requests use.",+ "_description": "LLM provider defaults. popular_models drives the ordered global selector and offline fallback independently of token constraints. POLICY (2026-07-23): popular_models lists only models with >= 1M-token context windows — providers whose models are all below 1M carry an empty list and contribute nothing to the global selector (their models stay reachable via the live per-provider fetch_models dropdown). SOURCE (2026-09-26): model_registry.json, the OpenRouter snapshot, is the ground truth for the curated ids, context, max output and prices of every provider whose models it lists; an id it does not list is not curated (Mistral's -latest aliases excepted, see its note). It carries nothing for the hosts (groq, cerebras, sarvam), which keep their own documented values. base_url directly configures the nine OpenAI-compatible native providers; dedicated OpenAI, Anthropic, and Gemini providers use SDK defaults, while OpenRouter has its own gateway default. Runtime proxy credentials can override supported endpoints. Model specs are enriched by model_registry.json at runtime; kimi and mistral are the exception, because the registry files their models under moonshotai/ and mistralai/, so their maps here are what requests use. streaming: true marks a provider whose answers stream to the chat as they are written (ChatUnifier passes it the stream sink); declare it only once the provider's stream is shown to report what its finished response does, usage included (tests/llm/test_streaming.py).","agent": {"_description": "Agent execution defaults. recursion_limit and compaction.ratio are sourced from the environment (AGENT_RECURSION_LIMIT, COMPACTION_RATIO via core.config.Settings) — these JSON values are last-resort fallbacks when the env vars aren't loaded (e.g. one-off CLI scripts that bypass Settings). default_temperature stays JSON-resident since it has no env override yet.",@@ -15,6 +15,7 @@"providers": {"openai": {"display_name": "OpenAI",+ "streaming": true,"default_model": "gpt-6-sol","popular_models": ["gpt-6-sol", "gpt-6-astra", "gpt-6-astra-pro", "gpt-6-sol-pro", "gpt-6-luna", "gpt-6-luna-pro", "gpt-5.6-sol", "gpt-5.6-sol-pro", "gpt-5.6-terra", "gpt-5.6-terra-pro", "gpt-5.6-luna", "gpt-5.6-luna-pro", "gpt-5.5", "gpt-5.4", "gpt-4.1"],"detection_patterns": ["gpt", "openai", "o1", "o3", "o4"],@@ -70,6 +71,7 @@},"anthropic": {"display_name": "Anthropic",+ "streaming": true,"default_model": "claude-opus-5-5","popular_models": ["claude-opus-5-5", "claude-fable-5-1", "claude-fable-5", "claude-opus-5", "claude-sonnet-5-5", "claude-sonnet-5", "claude-opus-4-8", "claude-opus-4-7", "claude-sonnet-4-6"],"_models_note": "Ids, context, max output and prices follow the OpenRouter registry (2026-09-29), which gives every curated Claude model 1,000,000 tokens of context and 128K max output (Haiku 4.5: 200K and 64K). claude-opus-5-5 is the default: the newest Opus, at $4/$20 per MTok, below claude-opus-5 ($5/$25), which stays curated. claude-fable-5-1 ($10/$50) is the top tier and supersedes claude-fable-5 (same price), also still curated. claude-sonnet-5-5 (new in the 2026-09-29 registry) and claude-sonnet-5 are both $2/$10. Ids use Anthropic's hyphenated form; the registry's dotted ids (claude-opus-5.5) match them through ModelRegistryService's dot/hyphen variants. The adaptive-thinking / sampling-removed lists below match by prefix, so the claude-opus-5, claude-fable-5 and claude-sonnet-5 entries cover Opus 5.5, Fable 5.1 and Sonnet 5.5. claude-opus-5-fast and the registry's claude-sonnet-5.5:batch variant are not curated.",diff --git a/server/services/agent_runtime.py b/server/services/agent_runtime.pyindex f7a062fc..b0f3f7dd 100644--- a/server/services/agent_runtime.py+++ b/server/services/agent_runtime.py@@ -33,6 +33,7 @@ from services.llm.protocol import (LLMError,LLMResponse,Message,+ StreamSink,ThinkingConfig,ToolCall,ToolDef,@@ -111,12 +112,14 @@ async def run_native_llm_step(sdk_max_retries: int = 0,explicit_max_retries: int = 2,translate_errors: bool = True,+ on_event: Optional[StreamSink] = None,) -> LLMResponse:"""Execute one native SDK turn and return its lossless response envelope.Agent retries are deliberately outside the provider SDK so only failuresnormalized as retryable :class:`LLMError` values are repeated. Temporalpasses ``explicit_max_retries=0`` and owns activity-level retry itself.+ ``on_event`` receives the response as it is written (ChatUnifier.chat)."""if chat_unifier is None:@@ -144,6 +147,7 @@ async def run_native_llm_step(sdk_max_retries=max(0, int(sdk_max_retries)),# Preserve structured metadata until this agent-step boundary.translate_errors=False,+ on_event=on_event,)except LLMError as error:if not error.retryable or attempt + 1 >= attempts:diff --git a/server/services/llm/__init__.py b/server/services/llm/__init__.pyindex 149d2368..545a23c8 100644--- a/server/services/llm/__init__.py+++ b/server/services/llm/__init__.py@@ -23,6 +23,8 @@ from services.llm.protocol import (LLMError,LLMErrorCategory,LLMProvider,+ StreamEvent,+ StreamSink,message_to_wire,message_from_wire,messages_to_wire,@@ -68,6 +70,8 @@ __all__ = ["LLMError","LLMErrorCategory","LLMProvider",+ "StreamEvent",+ "StreamSink","message_to_wire","message_from_wire","messages_to_wire",diff --git a/server/services/llm/protocol.py b/server/services/llm/protocol.pyindex a167a428..013df282 100644--- a/server/services/llm/protocol.py+++ b/server/services/llm/protocol.py@@ -18,6 +18,8 @@ from dataclasses import dataclass, fieldfrom enum import Enumfrom typing import (Any,+ Awaitable,+ Callable,Dict,Iterable,List,@@ -104,6 +106,24 @@ class ThinkingConfig:format: str = "parsed"+@dataclass(frozen=True)+class StreamEvent:+ """A piece of a response as the provider produces it.++ ``kind`` is ``text`` (answer text) or ``reasoning`` (thinking text).+ Streaming never changes the response: the provider still returns the+ whole :class:`LLMResponse` it would have returned without a sink, and+ the deltas, joined, are that response's text.+ """++ kind: str+ delta: str+++#: Receives each :class:`StreamEvent` while a response streams.+StreamSink = Callable[[StreamEvent], Awaitable[None]]++@dataclassclass ToolDef:"""Tool definition passed to the LLM."""@@ -842,6 +862,11 @@ class LLMProvider(Protocol):thinking: Optional[ThinkingConfig] = None,tools: Optional[List[ToolDef]] = None,context_management: Optional[Dict[str, Any]] = None,- ) -> LLMResponse: ...+ on_event: Optional[StreamSink] = None,+ ) -> LLMResponse:+ """One turn. A provider that streams (``streaming`` in+ llm_defaults.json) hands each delta to ``on_event`` as it arrives and+ still returns the same response; the others never receive one."""+ ...async def fetch_models(self, api_key: str) -> List[str]: ...diff --git a/server/services/llm/providers/anthropic.py b/server/services/llm/providers/anthropic.pyindex dcaea0c6..72176473 100644--- a/server/services/llm/providers/anthropic.py+++ b/server/services/llm/providers/anthropic.py@@ -11,6 +11,8 @@ from services.llm.protocol import (encode_binary_state,LLMResponse,Message,+ StreamEvent,+ StreamSink,ThinkingConfig,ToolCall,ToolDef,@@ -54,6 +56,7 @@ class AnthropicProvider:thinking: Optional[ThinkingConfig] = None,tools: Optional[List[ToolDef]] = None,context_management: Optional[Dict[str, Any]] = None,+ on_event: Optional[StreamSink] = None,) -> LLMResponse:system, api_msgs = self._split_system(messages)policy = self._model_policy(model)@@ -130,6 +133,20 @@ class AnthropicProvider:stream_ctx = self._client.messages.stream(**params)async with stream_ctx as stream:+ if on_event is not None:+ # The SDK's helper events carry each delta once (the raw+ # ``content_block_delta`` they come from is skipped), and+ # ``get_final_message`` still returns the accumulated message.+ async for event in stream:+ kind = getattr(event, "type", None)+ if kind == "text":+ delta = getattr(event, "text", "") or ""+ if delta:+ await on_event(StreamEvent("text", delta))+ elif kind == "thinking":+ delta = getattr(event, "thinking", "") or ""+ if delta:+ await on_event(StreamEvent("reasoning", delta))resp = await stream.get_final_message()return self._normalize(resp, model)diff --git a/server/services/llm/providers/openai.py b/server/services/llm/providers/openai.pyindex f78d9d00..55ef3efd 100644--- a/server/services/llm/providers/openai.py+++ b/server/services/llm/providers/openai.py@@ -12,14 +12,21 @@ from typing import Any, Dict, List, Optionalfrom core.logging import get_loggerfrom services.llm.protocol import (ContentBlock,+ LLMError,+ LLMErrorCategory,LLMResponse,Message,+ StreamEvent,+ StreamSink,ThinkingConfig,ToolCall,ToolDef,Usage,)+#: Responses API stream events that carry the finished response.+_RESPONSES_TERMINAL_EVENTS = frozenset({"response.completed", "response.incomplete", "response.failed"})+logger = get_logger(__name__)@@ -102,6 +109,7 @@ class OpenAIProvider:thinking: Optional[ThinkingConfig] = None,tools: Optional[List[ToolDef]] = None,context_management: Optional[Dict[str, Any]] = None,+ on_event: Optional[StreamSink] = None,) -> LLMResponse:model = self._clean_model(model)policy = self._model_policy(model, thinking)@@ -117,6 +125,7 @@ class OpenAIProvider:thinking=thinking,tools=tools,context_management=context_management,+ on_event=on_event,)params: Dict[str, Any] = {@@ -160,9 +169,37 @@ class OpenAIProvider:if tools:params["tools"] = [self._to_api_tool(t) for t in tools]+ if on_event is not None:+ return self._normalize(await self._stream_completion(params, on_event), model)resp = await self._client.chat.completions.create(**params)return self._normalize(resp, model)+ async def _stream_completion(self, params: Dict[str, Any], on_event: StreamSink) -> Any:+ """The completion ``create(**params)`` would return, streamed.++ Chunks fold into the SDK's own snapshot (the state its ``stream()``+ helper keeps). That helper is not used: it refuses tools that are not+ ``strict``, and its final parse raises on a ``length`` finish that a+ plain ``create`` returns normally.+ """+ from openai.lib.streaming.chat._completions import ChatCompletionStreamState++ state = ChatCompletionStreamState()+ stream = await self._client.chat.completions.create(+ **params, stream=True, stream_options={"include_usage": True}+ )+ async for chunk in stream:+ state.handle_chunk(chunk)+ for choice in chunk.choices or ():+ delta = choice.delta+ text = getattr(delta, "content", None)+ if isinstance(text, str) and text:+ await on_event(StreamEvent("text", text))+ reasoning = getattr(delta, "reasoning_content", None) or getattr(delta, "reasoning", None)+ if isinstance(reasoning, str) and reasoning:+ await on_event(StreamEvent("reasoning", reasoning))+ return state.current_completion_snapshot+async def _chat_responses(self,*,@@ -172,6 +209,7 @@ class OpenAIProvider:thinking: Optional[ThinkingConfig],tools: Optional[List[ToolDef]],context_management: Optional[Dict[str, Any]],+ on_event: Optional[StreamSink] = None,) -> LLMResponse:"""Run a self-contained Responses API turn for reasoning tool use."""@@ -206,9 +244,39 @@ class OpenAIProvider:"compact_threshold": threshold,}]+ if on_event is not None:+ return self._normalize_responses(await self._stream_response(params, on_event), model)response = await self._client.responses.create(**params)return self._normalize_responses(response, model)+ async def _stream_response(self, params: Dict[str, Any], on_event: StreamSink) -> Any:+ """The response ``responses.create(**params)`` would return, streamed:+ the one the terminal event carries. Not the SDK's ``stream()``+ helper, whose final read raises for an incomplete or failed response+ that a plain ``create`` returns."""+ final: Any = None+ stream = await self._client.responses.create(**params, stream=True)+ async for event in stream:+ kind = getattr(event, "type", "")+ if kind == "response.output_text.delta":+ delta = getattr(event, "delta", "") or ""+ if delta:+ await on_event(StreamEvent("text", delta))+ elif kind == "response.reasoning_summary_text.delta":+ delta = getattr(event, "delta", "") or ""+ if delta:+ await on_event(StreamEvent("reasoning", delta))+ elif kind in _RESPONSES_TERMINAL_EVENTS:+ final = getattr(event, "response", None)+ if final is None:+ raise LLMError(+ message="The response stream ended before the response was complete.",+ provider=self.provider_name,+ category=LLMErrorCategory.CONNECTION,+ retryable=True,+ )+ return final+# ------------------------------------------------------------------# fetch_models# ------------------------------------------------------------------diff --git a/server/services/llm/unifier.py b/server/services/llm/unifier.pyindex d378472c..0b571aee 100644--- a/server/services/llm/unifier.py+++ b/server/services/llm/unifier.py@@ -30,6 +30,8 @@ from services.llm.protocol import (LLMProvider,LLMResponse,Message,+ StreamEvent,+ StreamSink,ThinkingConfig,ToolDef,)@@ -93,6 +95,7 @@ class ChatUnifier:context_management: Optional[Dict[str, Any]] = None,sdk_max_retries: int = 2,translate_errors: bool = True,+ on_event: Optional[StreamSink] = None,) -> LLMResponse:"""Execute a chat completion against the named provider.@@ -104,23 +107,36 @@ class ChatUnifier:``provider`` is a provider reference: a registered id, or a namedendpoint ``openai_compatible:<slug>`` (RFC-0003 D13).++ ``on_event`` receives the response as it is produced. A provider+ that declares ``streaming`` in llm_defaults.json streams it; for any+ other the events come from the finished response, one per kind, so+ a caller handles both the same way. The response is the same either+ way."""- spec = get_provider(split_provider_ref(provider)[0])+ provider_id = split_provider_ref(provider)[0]+ spec = get_provider(provider_id)+ streams = on_event is not None and self._streams(provider_id)api_key = self._resolve_credential(provider, api_key)entry: Optional[_ClientEntry] = Nonetry:entry = await self._acquire_client(spec, api_key, provider_ref=provider, sdk_max_retries=sdk_max_retries)- return await entry.client.chat(- messages,- model=model,- temperature=temperature,- max_tokens=max_tokens,- thinking=thinking,- tools=tools,- context_management=context_management,- )+ kwargs: Dict[str, Any] = {+ "model": model,+ "temperature": temperature,+ "max_tokens": max_tokens,+ "thinking": thinking,+ "tools": tools,+ "context_management": context_management,+ }+ if streams:+ kwargs["on_event"] = on_event+ response = await entry.client.chat(messages, **kwargs)+ if on_event is not None and not streams:+ await _replay_response(response, on_event)+ return responseexcept LLMError as error:# Raised by provider logic rather than the SDK, e.g. a 2xx that# carried an error body instead of a completion. Logged whether@@ -219,6 +235,13 @@ class ChatUnifier:return modelsreturn [m for m in models if m not in blocklist]+ def _streams(self, provider_id: str) -> bool:+ """Whether the provider streams its responses (``streaming`` in+ llm_defaults.json). Declared per provider once its stream is known+ to report what the finished response does, usage included."""+ config = (self._defaults.get("providers") or {}).get(provider_id) or {}+ return config.get("streaming") is True+def is_registered(self, provider: str) -> bool:"""Cheap probe used by callers that want graceful fallback when aprovider is not wired into the registry.@@ -451,3 +474,12 @@ class ChatUnifier:url=redact_url(getattr(client, "endpoint_url", None)),url_source=getattr(client, "url_source", None),)+++async def _replay_response(response: LLMResponse, on_event: StreamSink) -> None:+ """Hand a finished response to a sink as if it had streamed: its+ reasoning, then its text, each in one event."""+ if response.thinking:+ await on_event(StreamEvent("reasoning", response.thinking))+ if response.content:+ await on_event(StreamEvent("text", response.content))diff --git a/server/tests/llm/test_streaming.py b/server/tests/llm/test_streaming.pynew file mode 100644index 00000000..bc57e009--- /dev/null+++ b/server/tests/llm/test_streaming.py@@ -0,0 +1,315 @@+"""Streaming a response never changes it.++A provider that declares ``streaming`` (llm_defaults.json) hands each delta+to the sink and still returns the response it would have returned without+one; ChatUnifier gives the sink to those providers only, and for every other+provider hands it the finished response. The chunks and events below are+built from the SDKs' own types, so the comparison is against what the+non-streaming call really returns.+"""++from __future__ import annotations++import json+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from services.llm.protocol import LLMError, LLMResponse, Message, StreamEvent, ToolDef+++class Sink:+ def __init__(self) -> None:+ self.events: list[StreamEvent] = []++ async def __call__(self, event: StreamEvent) -> None:+ self.events.append(event)++ def joined(self, kind: str = "text") -> str:+ return "".join(event.delta for event in self.events if event.kind == kind)+++def comparable(response: LLMResponse):+ """Everything a caller reads from a response (``raw`` is the SDK object+ itself and differs by construction)."""+ return (+ response.content,+ response.thinking,+ response.tool_calls,+ response.usage,+ response.finish_reason,+ response.assistant_message,+ )+++class AsyncIter:+ def __init__(self, items) -> None:+ self._items = list(items)++ def __aiter__(self):+ async def gen():+ for item in self._items:+ yield item++ return gen()+++MESSAGES = [Message(role="system", content="Be brief."), Message(role="user", content="Any bookings?")]+++# ---------------------------------------------------------------------------+# Anthropic+# ---------------------------------------------------------------------------+++def _anthropic_final():+ from anthropic.types import Message as AnthropicMessage++ return AnthropicMessage.model_validate(+ {+ "id": "msg_1",+ "type": "message",+ "role": "assistant",+ "model": "claude-test",+ "content": [+ {"type": "thinking", "thinking": "Check Saturday.", "signature": "sig"},+ {"type": "text", "text": "Saturday works."},+ {"type": "tool_use", "id": "tu_1", "name": "calendar", "input": {"day": "sat"}},+ ],+ "stop_reason": "tool_use",+ "stop_sequence": None,+ "usage": {"input_tokens": 10, "output_tokens": 5},+ }+ )+++def _anthropic_stream(final):+ from anthropic.lib.streaming import TextEvent+ from anthropic.lib.streaming._types import ThinkingEvent++ events = [+ ThinkingEvent(type="thinking", thinking="Check Saturday.", snapshot="Check Saturday."),+ # The raw delta a helper event comes from: never counted twice.+ SimpleNamespace(type="content_block_delta", delta=SimpleNamespace(type="text_delta", text="Saturday ")),+ TextEvent(type="text", text="Saturday ", snapshot="Saturday "),+ TextEvent(type="text", text="works.", snapshot="Saturday works."),+ ]+ stream = AsyncIter(events)+ stream.get_final_message = AsyncMock(return_value=final)+ ctx = MagicMock()+ ctx.__aenter__ = AsyncMock(return_value=stream)+ ctx.__aexit__ = AsyncMock(return_value=False)+ return MagicMock(return_value=ctx)+++async def test_anthropic_streams_each_delta_once_and_returns_the_same_response():+ with patch("anthropic.AsyncAnthropic"):+ from services.llm.providers.anthropic import AnthropicProvider++ provider = AnthropicProvider("sk-test")+ final = _anthropic_final()+ provider._client.messages.stream = _anthropic_stream(final)++ sink = Sink()+ streamed = await provider.chat(MESSAGES, model="claude-test", on_event=sink)+ plain = await provider.chat(MESSAGES, model="claude-test")++ assert sink.joined("text") == "Saturday works."+ assert sink.joined("reasoning") == "Check Saturday."+ assert comparable(streamed) == comparable(plain)+ assert streamed.tool_calls[0].name == "calendar"+++# ---------------------------------------------------------------------------+# OpenAI chat completions+# ---------------------------------------------------------------------------+++def _chunk(choices, usage=None):+ from openai.types.chat import ChatCompletionChunk++ payload = {"id": "cc_1", "object": "chat.completion.chunk", "created": 1, "model": "gpt-test", "choices": choices}+ if usage is not None:+ payload["usage"] = usage+ return ChatCompletionChunk.model_validate(payload)+++USAGE = {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}+ARGUMENTS = json.dumps({"day": "sat"})+++def _openai_chunks(finish_reason: str):+ return [+ _chunk([{"index": 0, "delta": {"role": "assistant", "content": ""}, "finish_reason": None}]),+ _chunk([{"index": 0, "delta": {"content": "Two"}, "finish_reason": None}]),+ _chunk([{"index": 0, "delta": {"content": " bookings."}, "finish_reason": None}]),+ _chunk([{"index": 0, "delta": {"tool_calls": [{"index": 0, "id": "call_1", "type": "function", "function": {"name": "calendar", "arguments": ARGUMENTS[:5]}}]}, "finish_reason": None}]),+ _chunk([{"index": 0, "delta": {"tool_calls": [{"index": 0, "function": {"arguments": ARGUMENTS[5:]}}]}, "finish_reason": None}]),+ _chunk([{"index": 0, "delta": {}, "finish_reason": finish_reason}]),+ _chunk([], usage=USAGE),+ ]+++def _openai_completion(finish_reason: str):+ from openai.types.chat import ChatCompletion++ return ChatCompletion.model_validate(+ {+ "id": "cc_1",+ "object": "chat.completion",+ "created": 1,+ "model": "gpt-test",+ "choices": [+ {+ "index": 0,+ "finish_reason": finish_reason,+ "message": {+ "role": "assistant",+ "content": "Two bookings.",+ "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "calendar", "arguments": ARGUMENTS}}],+ },+ }+ ],+ "usage": USAGE,+ }+ )+++def _openai_provider():+ with patch("openai.AsyncOpenAI"):+ from services.llm.providers.openai import OpenAIProvider++ return OpenAIProvider("sk-test")++[email protected]("finish_reason", ["tool_calls", "length"])+async def test_openai_chat_streams_and_returns_what_create_returns(finish_reason):+ provider = _openai_provider()+ calls = []++ async def create(**kwargs):+ calls.append(kwargs)+ if kwargs.get("stream"):+ return AsyncIter(_openai_chunks(finish_reason))+ return _openai_completion(finish_reason)++ provider._client.chat.completions.create = create+ tools = [ToolDef(name="calendar", description="Read the calendar", parameters={"type": "object", "properties": {"day": {"type": "string"}}})]++ sink = Sink()+ streamed = await provider.chat(MESSAGES, model="gpt-test", tools=tools, on_event=sink)+ plain = await provider.chat(MESSAGES, model="gpt-test", tools=tools)++ assert sink.joined() == "Two bookings."+ # A truncated (``length``) answer returns normally, as it does unstreamed.+ assert comparable(streamed) == comparable(plain)+ assert streamed.usage.total_tokens == 15+ streamed_call, plain_call = calls+ assert streamed_call.pop("stream") is True+ assert streamed_call.pop("stream_options") == {"include_usage": True}+ assert streamed_call == plain_call+++# ---------------------------------------------------------------------------+# OpenAI Responses API+# ---------------------------------------------------------------------------++[email protected]("terminal", ["response.completed", "response.incomplete"])+async def test_openai_responses_stream_returns_the_terminal_events_response(terminal):+ provider = _openai_provider()+ final = object()+ events = [+ SimpleNamespace(type="response.created"),+ SimpleNamespace(type="response.reasoning_summary_text.delta", delta="Checking."),+ SimpleNamespace(type="response.output_text.delta", delta="Two"),+ SimpleNamespace(type="response.output_text.delta", delta=" bookings."),+ SimpleNamespace(type=terminal, response=final),+ ]+ provider._client.responses.create = AsyncMock(return_value=AsyncIter(events))+ normalized = LLMResponse(content="Two bookings.")+ with patch.object(provider, "_normalize_responses", return_value=normalized) as normalize:+ sink = Sink()+ response = await provider._chat_responses(+ messages=MESSAGES, model="gpt-test", max_tokens=100, thinking=None, tools=None, context_management=None, on_event=sink+ )+ assert response is normalized+ assert normalize.call_args.args[0] is final+ assert provider._client.responses.create.call_args.kwargs["stream"] is True+ assert sink.joined() == "Two bookings."+ assert sink.joined("reasoning") == "Checking."+++async def test_openai_responses_stream_that_never_finishes_is_a_retryable_error():+ provider = _openai_provider()+ provider._client.responses.create = AsyncMock(return_value=AsyncIter([SimpleNamespace(type="response.output_text.delta", delta="Two")]))+ with pytest.raises(LLMError) as caught:+ await provider._chat_responses(+ messages=MESSAGES, model="gpt-test", max_tokens=100, thinking=None, tools=None, context_management=None, on_event=Sink()+ )+ assert caught.value.retryable+++# ---------------------------------------------------------------------------+# ChatUnifier+# ---------------------------------------------------------------------------+++def _unifier_with(name: str, client, *, streaming: bool):+ from services.llm import registry+ from services.llm.registry import ProviderSpec+ from services.llm.unifier import ChatUnifier++ registry._REGISTRY[name] = ProviderSpec(name=name, factory=lambda **kwargs: client, sdk_exception_refs=("openai:OpenAIError",))+ auth = MagicMock()+ auth.get_api_key = AsyncMock(return_value=None)+ providers = {name: {"streaming": True}} if streaming else {}+ return ChatUnifier(defaults={"providers": providers}, auth_service=auth, client_cache_size=0)+++async def test_unifier_hands_the_sink_only_to_a_provider_that_declares_streaming():+ from services.llm import registry++ name = "streaming-test"+ client = MagicMock()+ client.chat = AsyncMock(return_value=LLMResponse(content="Two bookings."))+ unifier = _unifier_with(name, client, streaming=True)+ sink = Sink()+ try:+ await unifier.chat(provider=name, api_key="k", messages=MESSAGES, model="m", on_event=sink)+ finally:+ registry._REGISTRY.pop(name, None)+ assert client.chat.call_args.kwargs["on_event"] is sink+ # The provider streamed (here: did not call the sink); nothing is replayed.+ assert sink.events == []+++async def test_unifier_replays_the_finished_response_for_any_other_provider():+ from services.llm import registry++ name = "not-streaming-test"+ client = MagicMock()+ client.chat = AsyncMock(return_value=LLMResponse(content="Two bookings.", thinking="Checked."))+ unifier = _unifier_with(name, client, streaming=False)+ sink = Sink()+ try:+ response = await unifier.chat(provider=name, api_key="k", messages=MESSAGES, model="m", on_event=sink)+ finally:+ registry._REGISTRY.pop(name, None)+ assert "on_event" not in client.chat.call_args.kwargs+ assert [(event.kind, event.delta) for event in sink.events] == [("reasoning", "Checked."), ("text", "Two bookings.")]+ assert response.content == "Two bookings."+++def test_only_providers_whose_streams_were_checked_declare_streaming():+ from services.llm.config import LLM_DEFAULTS++ declared = sorted(name for name, config in LLM_DEFAULTS["providers"].items() if config.get("streaming") is True)+ assert declared == ["anthropic", "openai"]