Stream-internal LLMClient: chat()/chat_with_tools() consume chat_stream

Extends the 1.2.1 Agent-loop fix to every LLM caller: with completions
streamed internally, the 120 s httpx timeout bounds the gap BETWEEN chunks
(liveness) instead of total generation time, so a thinking model that
streams reasoning_content can legitimately work past 120 s while a dead
server still fails fast. chat_stream gains response_format= with an
in-stream HTTP-400 drop-ladder (response_format first, then tools); servers
that reject stream:true entirely fall back to one plain blocking POST.
A reasoning-only stream (zero content accumulated) raises ValueError so
generate_structured's json_object retry fires instead of returning blank.
This commit is contained in:
Justo Stoll
2026-08-24 07:05:35 +02:00
parent 7f2c6dce66
commit ffc1424566
2 changed files with 400 additions and 68 deletions
+181 -67
View File
@@ -10,12 +10,22 @@ from calliope.config import settings
logger = logging.getLogger("calliope.llm")
# Status codes that mean "this server does not do SSE streaming at all" —
# chat()/chat_with_tools() then fall back to one plain blocking POST. Anything
# else (401, 429, 5xx) is a real error and re-raises.
_STREAM_UNSUPPORTED_STATUS = frozenset({400, 404, 405, 501})
class LLMClient:
def __init__(self) -> None:
self.base_url = settings.llm_base_url.rstrip("/")
self.model = settings.llm_model
self.api_key = settings.llm_api_key
# With every completion streamed (chat/chat_with_tools consume
# chat_stream), 120 s bounds the gap BETWEEN chunks, not total
# generation time: a thinking model streaming reasoning_content keeps
# the connection fed for as long as it genuinely works, while a dead
# server still fails fast.
self.client = httpx.AsyncClient(timeout=120.0)
def _headers(self) -> dict[str, str]:
@@ -29,6 +39,43 @@ class LLMClient:
messages: list[dict[str, str]],
temperature: float = 0.7,
response_format: dict[str, str] | None = None,
) -> str:
try:
parts: list[str] = []
reasoning_chars = 0
async for ev in self.chat_stream(
messages, temperature=temperature, response_format=response_format
):
if ev["type"] == "delta":
parts.append(ev["content"])
elif ev["type"] == "reasoning":
reasoning_chars += len(ev["content"])
except httpx.HTTPStatusError as exc:
if exc.response.status_code not in _STREAM_UNSUPPORTED_STATUS:
raise
# Server rejected streaming itself (the in-stream field fallbacks
# are exhausted) — one plain blocking call preserves old behavior.
logger.warning(
"Streaming unavailable (HTTP %s); falling back to blocking call",
exc.response.status_code,
)
return await self._chat_blocking(messages, temperature, response_format)
content = "".join(parts).strip()
if not content:
# Thinking models can burn the whole completion in reasoning and
# stream no content tokens at all. Raise ValueError so
# generate_structured's retry ladder fires instead of returning a
# silently blank reply.
raise ValueError(
f"LLM returned no content (reasoning_chars={reasoning_chars})"
)
return content
async def _chat_blocking(
self,
messages: list[dict[str, str]],
temperature: float = 0.7,
response_format: dict[str, str] | None = None,
) -> str:
payload: dict[str, Any] = {
"model": self.model,
@@ -64,12 +111,47 @@ class LLMClient:
tools: list[dict[str, Any]] | None = None,
tool_choice: str | dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Non-streaming tool-call round. Returns the full assistant message
dict: {"role": "assistant", "content": str|None, "tool_calls": [...]}.
"""One tool-call round, streamed internally. Returns the full assistant
message dict: {"role": "assistant", "content": str|None, "tool_calls": [...]}.
Some OpenAI-compatible servers reject the tools field outright —
falls back to a plain call (the reply will have no tool_calls).
Servers that reject the tools field get it dropped in-stream (the reply
will have no tool_calls); servers that reject streaming itself get one
plain blocking call.
"""
try:
parts: list[str] = []
tool_calls: list[dict[str, Any]] = []
async for ev in self.chat_stream(
messages, temperature=temperature, tools=tools, tool_choice=tool_choice
):
if ev["type"] == "delta":
parts.append(ev["content"])
elif ev["type"] == "tool_call":
tool_calls.append(ev["tool_call"])
except httpx.HTTPStatusError as exc:
if exc.response.status_code not in _STREAM_UNSUPPORTED_STATUS:
raise
logger.warning(
"Streaming unavailable (HTTP %s); falling back to blocking call",
exc.response.status_code,
)
return await self._chat_with_tools_blocking(
messages, temperature, tools, tool_choice
)
content = "".join(parts)
return {
"role": "assistant",
"content": content if content else None,
"tool_calls": tool_calls,
}
async def _chat_with_tools_blocking(
self,
messages: list[dict[str, Any]],
temperature: float = 0.7,
tools: list[dict[str, Any]] | None = None,
tool_choice: str | dict[str, Any] | None = None,
) -> dict[str, Any]:
payload: dict[str, Any] = {
"model": self.model,
"messages": messages,
@@ -104,6 +186,7 @@ class LLMClient:
temperature: float = 0.7,
tools: list[dict[str, Any]] | None = None,
tool_choice: str | dict[str, Any] | None = None,
response_format: dict[str, str] | None = None,
) -> AsyncIterator[dict[str, Any]]:
"""Streaming completion. Yields event dicts:
@@ -112,6 +195,11 @@ class LLMClient:
- {"type": "tool_call", "tool_call": {...}} — one complete tool call
(argument fragments accumulated across chunks)
- {"type": "done"} — stream finished
On HTTP 400 the optional fields are dropped one at a time
(response_format first, then tools) and the request retried — the same
LM-Studio-style fallbacks the blocking path has. A 400 that survives
both drops surfaces as HTTPStatusError.
"""
payload: dict[str, Any] = {
"model": self.model,
@@ -123,75 +211,97 @@ class LLMClient:
payload["tools"] = tools
if tool_choice is not None:
payload["tool_choice"] = tool_choice
if response_format:
payload["response_format"] = response_format
url = f"{self.base_url}/chat/completions"
logger.info("LLM stream request to %s with model %s", url, self.model)
tool_acc: dict[int, dict[str, Any]] = {}
async with self.client.stream("POST", url, headers=self._headers(), json=payload) as resp:
if resp.status_code == 400:
# Read body for logging, then let the error surface as 400.
await resp.aread()
logger.warning("Stream request rejected (HTTP 400): %s", resp.text[:500])
resp.raise_for_status()
async for line in resp.aiter_lines():
if not line.startswith("data:"):
continue
data_str = line[5:].strip()
if not data_str or data_str == "[DONE]":
continue
try:
chunk = json.loads(data_str)
except json.JSONDecodeError:
continue
choices = chunk.get("choices") or []
if not choices:
# Mid-stream error payloads ({"error": {...}}) carry no
# choices — surface them instead of ending the turn with
# a silently blank assistant message.
err = chunk.get("error")
if err is not None:
message = (
err.get("message")
if isinstance(err, dict)
else str(err)
)
raise RuntimeError(f"LLM stream error: {message}")
continue
delta = choices[0].get("delta") or {}
content = delta.get("content")
if content:
yield {"type": "delta", "content": content}
reasoning = delta.get("reasoning_content")
if reasoning:
yield {"type": "reasoning", "content": reasoning}
for tc in delta.get("tool_calls") or []:
idx = tc.get("index", 0)
acc = tool_acc.get(idx)
if acc is None:
acc = {
"id": tc.get("id") or f"call_{idx}",
"type": "function",
"function": {"name": "", "arguments": ""},
}
tool_acc[idx] = acc
if tc.get("id"):
acc["id"] = tc["id"]
fn = tc.get("function") or {}
if fn.get("name"):
acc["function"]["name"] += fn["name"]
if fn.get("arguments"):
acc["function"]["arguments"] += fn["arguments"]
finish = choices[0].get("finish_reason")
if finish == "tool_calls":
for idx in sorted(tool_acc):
if tool_acc[idx]["function"]["name"]:
yield {"type": "tool_call", "tool_call": tool_acc[idx]}
tool_acc.clear()
while True:
retry_without: str | None = None
async with self.client.stream("POST", url, headers=self._headers(), json=payload) as resp:
if resp.status_code == 400:
# Read body for logging, then drop optional fields one at a
# time before giving up.
await resp.aread()
logger.warning("Stream request rejected (HTTP 400): %s", resp.text[:500])
if "response_format" in payload:
retry_without = "response_format"
elif "tools" in payload:
retry_without = "tools"
if retry_without is None:
resp.raise_for_status()
async for ev in self._parse_sse(resp, tool_acc):
yield ev
if retry_without is None:
break
logger.warning("Retrying stream without %s", retry_without)
payload.pop(retry_without)
if retry_without == "tools":
payload.pop("tool_choice", None)
# Some servers only send finish_reason=stop — flush anything accumulated.
for idx in sorted(tool_acc):
if tool_acc[idx]["function"]["name"]:
yield {"type": "tool_call", "tool_call": tool_acc[idx]}
yield {"type": "done"}
async def _parse_sse(
self, resp: httpx.Response, tool_acc: dict[int, dict[str, Any]]
) -> AsyncIterator[dict[str, Any]]:
async for line in resp.aiter_lines():
if not line.startswith("data:"):
continue
data_str = line[5:].strip()
if not data_str or data_str == "[DONE]":
continue
try:
chunk = json.loads(data_str)
except json.JSONDecodeError:
continue
choices = chunk.get("choices") or []
if not choices:
# Mid-stream error payloads ({"error": {...}}) carry no
# choices — surface them instead of ending the turn with
# a silently blank assistant message.
err = chunk.get("error")
if err is not None:
message = (
err.get("message")
if isinstance(err, dict)
else str(err)
)
raise RuntimeError(f"LLM stream error: {message}")
continue
delta = choices[0].get("delta") or {}
content = delta.get("content")
if content:
yield {"type": "delta", "content": content}
reasoning = delta.get("reasoning_content")
if reasoning:
yield {"type": "reasoning", "content": reasoning}
for tc in delta.get("tool_calls") or []:
idx = tc.get("index", 0)
acc = tool_acc.get(idx)
if acc is None:
acc = {
"id": tc.get("id") or f"call_{idx}",
"type": "function",
"function": {"name": "", "arguments": ""},
}
tool_acc[idx] = acc
if tc.get("id"):
acc["id"] = tc["id"]
fn = tc.get("function") or {}
if fn.get("name"):
acc["function"]["name"] += fn["name"]
if fn.get("arguments"):
acc["function"]["arguments"] += fn["arguments"]
finish = choices[0].get("finish_reason")
if finish == "tool_calls":
for idx in sorted(tool_acc):
if tool_acc[idx]["function"]["name"]:
yield {"type": "tool_call", "tool_call": tool_acc[idx]}
tool_acc.clear()
def extract_json(text: str) -> dict[str, Any]:
"""Extract a JSON object from a model reply.
@@ -258,12 +368,16 @@ async def generate_structured(
# JSON mode is off by default: several OpenAI-compatible servers
# (notably LM Studio) reject response_format, and the prompts already
# instruct the model to answer with a single JSON object.
text = await client.chat(messages, temperature=temperature)
try:
# chat() itself can raise ValueError when a thinking model spends
# the whole completion streaming reasoning and accumulates no
# content — that must reach the retry below, so it lives inside
# this try alongside the parse.
text = await client.chat(messages, temperature=temperature)
return extract_json(text)
except ValueError:
except ValueError as exc:
# One retry with JSON mode requested, for servers that support it
logger.warning("LLM reply was not parseable JSON; retrying with json_object mode")
logger.warning("LLM reply unusable (%s); retrying with json_object mode", exc)
text = await client.chat(
messages, temperature=temperature, response_format={"type": "json_object"}
)
+219 -1
View File
@@ -54,8 +54,27 @@ def test_extract_json_empty():
# ---------- LLMClient response_format fallback ----------
def _sse_body(message: dict) -> bytes:
"""Encode a full assistant message as a minimal SSE stream."""
chunks = []
if message.get("reasoning_content"):
chunks.append(
{"choices": [{"delta": {"reasoning_content": message["reasoning_content"]}}]}
)
if message.get("content"):
chunks.append({"choices": [{"delta": {"content": message["content"]}}]})
chunks.append({"choices": [{"delta": {}, "finish_reason": "stop"}]})
lines = [b"data: " + json.dumps(c).encode() for c in chunks]
lines.append(b"data: [DONE]")
return b"\n".join(lines) + b"\n"
class _FakeRouter:
"""httpx mock transport handler that 400s any request containing response_format."""
"""httpx mock transport handler that 400s any request containing response_format.
Serves SSE when the request asks for stream:true, plain JSON otherwise —
chat()/chat_with_tools() stream internally, so both shapes occur.
"""
def __init__(self, content: str, reject_response_format: bool) -> None:
self.content = content
@@ -70,6 +89,12 @@ class _FakeRouter:
400,
json={"error": {"message": "response_format is not supported"}},
)
if body.get("stream"):
return httpx.Response(
200,
content=_sse_body({"content": self.content}),
headers={"content-type": "text/event-stream"},
)
return httpx.Response(
200,
json={"choices": [{"message": {"content": self.content}}]},
@@ -235,3 +260,196 @@ async def test_chat_stream_normal_tokens_unaffected(monkeypatch):
types = [e["type"] for e in events]
assert types == ["delta", "delta", "done"]
assert events[0]["content"] == "Hi"
# ---------- reasoning-only replies (thinking models returning no `content`) ----------
# Reasoning models served via OpenAI-compatible endpoints can spend the whole
# completion in a reasoning channel (e.g. `reasoning_content`) and return a
# message with NO `content` key. That must be a retryable failure, not a
# KeyError bubbling up as an HTTP 500.
class _MessageRouter:
"""Returns full message dicts in sequence (to simulate reasoning-only replies).
Streamed requests get the message re-encoded as SSE deltas — a
reasoning-only message becomes a stream with reasoning chunks and no
content chunks, which is exactly what oMLX-style servers emit."""
def __init__(self, messages: list[dict]) -> None:
self.messages = messages
self.requests: list[dict] = []
async def __call__(self, request: httpx.Request) -> httpx.Response:
body = json.loads(request.content.decode())
self.requests.append(body)
message = self.messages[min(len(self.requests) - 1, len(self.messages) - 1)]
if body.get("stream"):
return httpx.Response(
200,
content=_sse_body(message),
headers={"content-type": "text/event-stream"},
)
return httpx.Response(
200,
json={"choices": [{"message": message, "finish_reason": "length"}]},
)
async def test_chat_raises_value_error_on_missing_content(monkeypatch):
router = _MessageRouter(
[{"role": "assistant", "reasoning_content": "thinking forever..."}]
)
client = LLMClient()
monkeypatch.setattr(
client, "client", httpx.AsyncClient(transport=httpx.MockTransport(router))
)
with pytest.raises(ValueError, match="no content"):
await client.chat([{"role": "user", "content": "hi"}])
async def test_generate_structured_recovers_from_reasoning_only_reply(monkeypatch):
router = _MessageRouter(
[
{"role": "assistant", "reasoning_content": "hmm..."},
{"role": "assistant", "content": '{"title": "Saved"}'},
]
)
client = LLMClient()
monkeypatch.setattr(
client, "client", httpx.AsyncClient(transport=httpx.MockTransport(router))
)
monkeypatch.setattr("calliope.agent.llm.LLMClient", lambda: client)
result = await generate_structured_public([{"role": "user", "content": "hi"}])
assert result == {"title": "Saved"}
assert len(router.requests) == 2
assert router.requests[1].get("response_format") == {"type": "json_object"}
# ---------- streaming-internal chat: fallbacks and accumulation ----------
# chat()/chat_with_tools() now consume chat_stream, so the 120 s client
# timeout bounds the gap BETWEEN chunks (liveness), not total generation time.
# These tests pin the two fallback ladders and the accumulation contract.
class _NoStreamRouter:
"""A server that rejects stream:true outright (400), accepts blocking."""
def __init__(self, content: str) -> None:
self.content = content
self.requests: list[dict] = []
async def __call__(self, request: httpx.Request) -> httpx.Response:
body = json.loads(request.content.decode())
self.requests.append(body)
if body.get("stream"):
return httpx.Response(
400, json={"error": {"message": "stream is not supported"}}
)
return httpx.Response(
200, json={"choices": [{"message": {"content": self.content}}]}
)
async def test_chat_falls_back_to_blocking_when_stream_rejected(monkeypatch):
router = _NoStreamRouter(content='{"ok": true}')
client = LLMClient()
monkeypatch.setattr(
client, "client", httpx.AsyncClient(transport=httpx.MockTransport(router))
)
text = await client.chat([{"role": "user", "content": "hi"}])
assert text == '{"ok": true}'
# one rejected stream attempt, then one blocking call
assert [b.get("stream", False) for b in router.requests] == [True, False]
async def test_chat_stream_drops_response_format_then_streams(monkeypatch):
"""The in-stream 400 ladder: response_format dropped, request retried."""
router = _FakeRouter(content='{"ok": true}', reject_response_format=True)
client = LLMClient()
monkeypatch.setattr(
client, "client", httpx.AsyncClient(transport=httpx.MockTransport(router))
)
text = await client.chat(
[{"role": "user", "content": "hi"}],
response_format={"type": "json_object"},
)
assert text == '{"ok": true}'
assert len(router.requests) == 2
assert "response_format" in router.requests[0]
assert "response_format" not in router.requests[1]
assert router.requests[1].get("stream") is True # still streaming, not blocking
class _ToolStreamRouter:
"""Streams one content delta plus one chunked tool call."""
def __init__(self) -> None:
self.requests: list[dict] = []
async def __call__(self, request: httpx.Request) -> httpx.Response:
body = json.loads(request.content.decode())
self.requests.append(body)
chunks = [
{"choices": [{"delta": {"content": "Queuing now."}}]},
{
"choices": [
{
"delta": {
"tool_calls": [
{
"index": 0,
"id": "call_1",
"function": {"name": "enqueue_asset", "arguments": '{"scene'},
}
]
}
}
]
},
{
"choices": [
{
"delta": {
"tool_calls": [
{"index": 0, "function": {"arguments": '_id": 3}'}}
]
},
"finish_reason": "tool_calls",
}
]
},
]
lines = [b"data: " + json.dumps(c).encode() for c in chunks]
lines.append(b"data: [DONE]")
return httpx.Response(
200,
content=b"\n".join(lines) + b"\n",
headers={"content-type": "text/event-stream"},
)
async def test_chat_with_tools_accumulates_streamed_tool_call(monkeypatch):
router = _ToolStreamRouter()
client = LLMClient()
monkeypatch.setattr(
client, "client", httpx.AsyncClient(transport=httpx.MockTransport(router))
)
msg = await client.chat_with_tools(
[{"role": "user", "content": "hi"}],
tools=[{"type": "function", "function": {"name": "enqueue_asset"}}],
)
assert msg["role"] == "assistant"
assert msg["content"] == "Queuing now."
assert len(msg["tool_calls"]) == 1
call = msg["tool_calls"][0]
assert call["function"]["name"] == "enqueue_asset"
assert json.loads(call["function"]["arguments"]) == {"scene_id": 3}