Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed

- **LLM streaming now yields chunks as they arrive.** Errors on a streamed call are
raised when the call is made, before iteration begins.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: Document this new streaming contract in the README and LLM capability guide. Their streaming sections omit both early chunk delivery and the fact that HTTP errors surface before iteration.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At CHANGELOG.md, line 13:

<comment>Document this new streaming contract in the README and LLM capability guide. Their streaming sections omit both early chunk delivery and the fact that HTTP errors surface before iteration.</comment>

<file context>
@@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
+### Fixed
+
+- **LLM streaming now yields chunks as they arrive.** Errors on a streamed call are
+  raised when the call is made, before iteration begins.
+
 ## [2.28.0] - 2026-10-03
</file context>


## [2.28.0] - 2026-10-03

### Added
Expand Down
46 changes: 28 additions & 18 deletions src/esperanto/providers/llm/anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -774,22 +774,27 @@ def chat_complete(
top_p=effective_top_p,
)

# Make HTTP request
if should_stream:
response = self._open_stream(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Opening the response before returning the generator leaves it unclosed when callers abandon the stream before its first next()/anext(); the generator’s finally never starts. Return a stream wrapper with deterministic cleanup (including an unstarted stream), or otherwise document and enforce cleanup for abandoned streams.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/esperanto/providers/llm/anthropic.py, line 778:

<comment>Opening the response before returning the generator leaves it unclosed when callers abandon the stream before its first `next()`/`anext()`; the generator’s `finally` never starts. Return a stream wrapper with deterministic cleanup (including an unstarted stream), or otherwise document and enforce cleanup for abandoned streams.</comment>

<file context>
@@ -774,22 +774,27 @@ def chat_complete(
 
-        # Make HTTP request
+        if should_stream:
+            response = self._open_stream(
+                f"{self.base_url}/messages", self._get_headers(), payload
+            )
</file context>

f"{self.base_url}/messages", self._get_headers(), payload
)
def generate():
try:
for event_data in self._parse_sse_stream(response):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: The new streaming path feeds _parse_sse_stream raw network chunks, but that parser assumes each chunk holds complete lines. A chunk boundary inside a data: line silently drops that event, so text or tool-call deltas go missing with no error. Buffer partial lines across chunks in _parse_sse_stream and _parse_sse_stream_async, and flush the remainder at end of stream. The same applies to the async call on the _parse_sse_stream_async line.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/esperanto/providers/llm/anthropic.py, line 783:

<comment>The new streaming path feeds `_parse_sse_stream` raw network chunks, but that parser assumes each chunk holds complete lines. A chunk boundary inside a `data:` line silently drops that event, so text or tool-call deltas go missing with no error. Buffer partial lines across chunks in `_parse_sse_stream` and `_parse_sse_stream_async`, and flush the remainder at end of stream. The same applies to the async call on the `_parse_sse_stream_async` line.</comment>

<file context>
@@ -774,22 +774,27 @@ def chat_complete(
+            )
+            def generate():
+                try:
+                    for event_data in self._parse_sse_stream(response):
+                        chunk = self._normalize_stream_event(event_data)
+                        if chunk:
</file context>

chunk = self._normalize_stream_event(event_data)
if chunk:
yield chunk
finally:
response.close()
return generate()

response = self.client.post(
f"{self.base_url}/messages",
headers=self._get_headers(),
json=payload
)
self._handle_error(response)

if should_stream:
def generate():
for event_data in self._parse_sse_stream(response):
chunk = self._normalize_stream_event(event_data)
if chunk:
yield chunk
return generate()

response_data = response.json()
result = self._normalize_response(response_data)

Expand Down Expand Up @@ -891,22 +896,27 @@ async def achat_complete(
top_p=effective_top_p,
)

# Make async HTTP request
if should_stream:
response = await self._aopen_stream(
f"{self.base_url}/messages", self._get_headers(), payload
)
async def generate():
try:
async for event_data in self._parse_sse_stream_async(response):
chunk = self._normalize_stream_event(event_data)
if chunk:
yield chunk
finally:
await response.aclose()
return generate()

response = await self.async_client.post(
f"{self.base_url}/messages",
headers=self._get_headers(),
json=payload
)
self._handle_error(response)

if should_stream:
async def generate():
async for event_data in self._parse_sse_stream_async(response):
chunk = self._normalize_stream_event(event_data)
if chunk:
yield chunk
return generate()

response_data = response.json()
result = self._normalize_response(response_data)

Expand Down
40 changes: 20 additions & 20 deletions src/esperanto/providers/llm/azure.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,17 +321,10 @@ def _get_api_kwargs(
return {k: v for k, v in effective_kwargs.items() if v is not None}

def _chat_complete_streaming(
self, messages: List[Dict[str, Any]], api_kwargs: Dict[str, Any]
self, response: httpx.Response
) -> Generator[ChatCompletionChunk, None, None]:
"""Handle streaming chat completion."""
url = self._build_url("chat/completions")
with self.client.stream(
"POST",
url,
headers=self._get_headers(),
json={"messages": messages, "stream": True, **api_kwargs},
) as response:
self._handle_error(response)
try:
for chunk_data in self._parse_sse_stream(response):
# Azure can emit metadata-only chunks (e.g., content-filter
# results) before the content stream begins. These chunks
Expand All @@ -342,6 +335,8 @@ def _chat_complete_streaming(
if not chunk_data.get("choices"):
continue
yield self._normalize_chunk(chunk_data)
finally:
response.close()

def chat_complete(
self,
Expand Down Expand Up @@ -428,7 +423,12 @@ def chat_complete(

if effective_stream_setting:
# Return streaming generator
return self._chat_complete_streaming(messages, api_kwargs)
response = self._open_stream(
self._build_url("chat/completions"),
self._get_headers(),
{"messages": messages, "stream": True, **api_kwargs},
)
return self._chat_complete_streaming(response)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The response is now opened before the generator exists, but it is only closed inside the generator's finally. If the returned stream is dropped without ever being iterated, finally never runs and the connection stays checked out. Tie the close to the generator object's lifetime, for example with weakref.finalize, so an unstarted stream still releases its response.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/esperanto/providers/llm/azure.py, line 431:

<comment>The response is now opened before the generator exists, but it is only closed inside the generator's `finally`. If the returned stream is dropped without ever being iterated, `finally` never runs and the connection stays checked out. Tie the close to the generator object's lifetime, for example with `weakref.finalize`, so an unstarted stream still releases its response.</comment>

<file context>
@@ -428,7 +423,12 @@ def chat_complete(
+                self._get_headers(),
+                {"messages": messages, "stream": True, **api_kwargs},
+            )
+            return self._chat_complete_streaming(response)
         else:
             # Non-streaming request
</file context>

else:
# Non-streaming request
url = self._build_url("chat/completions")
Expand All @@ -451,23 +451,18 @@ def chat_complete(
return result

async def _achat_complete_streaming(
self, messages: List[Dict[str, Any]], api_kwargs: Dict[str, Any]
self, response: httpx.Response
) -> AsyncGenerator[ChatCompletionChunk, None]:
"""Handle async streaming chat completion."""
url = self._build_url("chat/completions")
async with self.async_client.stream(
"POST",
url,
headers=self._get_headers(),
json={"messages": messages, "stream": True, **api_kwargs},
) as response:
self._handle_error(response)
try:
async for chunk_data in self._parse_sse_stream_async(response):
# See sync variant above — Azure metadata-only chunks have
# empty `choices`; skip for provider parity.
if not chunk_data.get("choices"):
continue
yield self._normalize_chunk(chunk_data)
finally:
await response.aclose()

async def achat_complete(
self,
Expand Down Expand Up @@ -554,7 +549,12 @@ async def achat_complete(

if effective_stream_setting:
# Return async streaming generator
return self._achat_complete_streaming(messages, api_kwargs)
response = await self._aopen_stream(
self._build_url("chat/completions"),
self._get_headers(),
{"messages": messages, "stream": True, **api_kwargs},
)
return self._achat_complete_streaming(response)
else:
# Non-streaming async request
url = self._build_url("chat/completions")
Expand Down
36 changes: 36 additions & 0 deletions src/esperanto/providers/llm/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from dataclasses import dataclass, field
from typing import Any, AsyncGenerator, Dict, Generator, List, Optional, Union

import httpx

from esperanto.common_types import ChatCompletion, ChatCompletionChunk, Model, Tool
from esperanto.utils.connect import HttpConnectionMixin

Expand Down Expand Up @@ -90,6 +92,40 @@ def _clean_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
"""Remove None values from config dictionary."""
return {k: v for k, v in config.items() if v is not None}

def _handle_error(self, response: httpx.Response) -> None:
"""Raise the provider-specific error for an unsuccessful response."""
raise NotImplementedError

def _open_stream(
self,
url: str,
headers: Dict[str, str],
payload: Dict[str, Any],
) -> httpx.Response:
"""Open an HTTP response without buffering its streaming body."""
request = self.client.build_request("POST", url, headers=headers, json=payload)
response = self.client.send(request, stream=True)
if response.status_code >= 400:
response.read()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: A failed read of an error response skips close(), leaking the streamed response. Wrap both read()/aread() calls in try/finally blocks so close()/aclose() always runs.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/esperanto/providers/llm/base.py, line 109:

<comment>A failed read of an error response skips `close()`, leaking the streamed response. Wrap both `read()`/`aread()` calls in `try/finally` blocks so `close()`/`aclose()` always runs.</comment>

<file context>
@@ -90,6 +92,40 @@ def _clean_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
+        request = self.client.build_request("POST", url, headers=headers, json=payload)
+        response = self.client.send(request, stream=True)
+        if response.status_code >= 400:
+            response.read()
+            response.close()
+            self._handle_error(response)
</file context>

response.close()
self._handle_error(response)
return response

async def _aopen_stream(
self,
url: str,
headers: Dict[str, str],
payload: Dict[str, Any],
) -> httpx.Response:
"""Open an async HTTP response without buffering its streaming body."""
request = self.async_client.build_request("POST", url, headers=headers, json=payload)
response = await self.async_client.send(request, stream=True)
if response.status_code >= 400:
await response.aread()
await response.aclose()
self._handle_error(response)
return response

def _resolve_tools(
self, tools: Optional[List[Tool]] = None
) -> Optional[List[Tool]]:
Expand Down
44 changes: 28 additions & 16 deletions src/esperanto/providers/llm/cohere.py
Original file line number Diff line number Diff line change
Expand Up @@ -585,21 +585,27 @@ def chat_complete(
resolved_structured=resolved_structured,
)

if should_stream:
response = self._open_stream(
f"{self.base_url}/v2/chat", self._get_headers(), payload
)
def generate():
try:
for event_data in self._parse_sse_stream(response):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Streaming now reads raw network chunks, but _parse_sse_stream splits each chunk on newlines independently. An SSE data: line that spans two reads is parsed as two broken fragments, both are silently skipped, and those tokens are lost. Buffer partial lines across reads, for example by iterating response.iter_lines() in _parse_sse_stream and _parse_sse_stream_async. The other HTTP providers share this parser pattern and need the same change.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/esperanto/providers/llm/cohere.py, line 594:

<comment>Streaming now reads raw network chunks, but `_parse_sse_stream` splits each chunk on newlines independently. An SSE `data:` line that spans two reads is parsed as two broken fragments, both are silently skipped, and those tokens are lost. Buffer partial lines across reads, for example by iterating `response.iter_lines()` in `_parse_sse_stream` and `_parse_sse_stream_async`. The other HTTP providers share this parser pattern and need the same change.</comment>

<file context>
@@ -585,21 +585,27 @@ def chat_complete(
+            )
+            def generate():
+                try:
+                    for event_data in self._parse_sse_stream(response):
+                        chunk = self._normalize_stream_event(event_data)
+                        if chunk:
</file context>

chunk = self._normalize_stream_event(event_data)
if chunk:
yield chunk
finally:
response.close()
return generate()

response = self.client.post(
f"{self.base_url}/v2/chat",
headers=self._get_headers(),
json=payload,
)
self._handle_error(response)

if should_stream:
def generate():
for event_data in self._parse_sse_stream(response):
chunk = self._normalize_stream_event(event_data)
if chunk:
yield chunk
return generate()

response_data = response.json()
result = self._normalize_response(response_data)

Expand Down Expand Up @@ -657,21 +663,27 @@ async def achat_complete(
resolved_structured=resolved_structured,
)

if should_stream:
response = await self._aopen_stream(
f"{self.base_url}/v2/chat", self._get_headers(), payload
)
async def generate():
try:
async for event_data in self._parse_sse_stream_async(response):
chunk = self._normalize_stream_event(event_data)
if chunk:
yield chunk
finally:
await response.aclose()
return generate()

response = await self.async_client.post(
f"{self.base_url}/v2/chat",
headers=self._get_headers(),
json=payload,
)
self._handle_error(response)

if should_stream:
async def generate():
async for event_data in self._parse_sse_stream_async(response):
chunk = self._normalize_stream_event(event_data)
if chunk:
yield chunk
return generate()

response_data = response.json()
result = self._normalize_response(response_data)

Expand Down
46 changes: 22 additions & 24 deletions src/esperanto/providers/llm/google.py
Original file line number Diff line number Diff line change
Expand Up @@ -499,22 +499,21 @@ def chat_complete(
endpoint = "generateContent"
url = f"{self.base_url}/models/{model_name}:{endpoint}?key={self.api_key}"

# Make HTTP request
response = self.client.post(
url,
headers=self._get_headers(),
json=payload
)
self._handle_error(response)

if should_stream:
response = self._open_stream(url, self._get_headers(), payload)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The stream is opened before generate() is returned, but it is only closed inside the generator's try/finally. If the caller never starts iterating, the connection is never released. Consider returning an iterator object that owns response and closes it in close() or __del__, so unconsumed streams are released. The async path has the same gap.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/esperanto/providers/llm/google.py, line 503:

<comment>The stream is opened before `generate()` is returned, but it is only closed inside the generator's `try/finally`. If the caller never starts iterating, the connection is never released. Consider returning an iterator object that owns `response` and closes it in `close()` or `__del__`, so unconsumed streams are released. The async path has the same gap.</comment>

<file context>
@@ -499,22 +499,21 @@ def chat_complete(
-        self._handle_error(response)
-
         if should_stream:
+            response = self._open_stream(url, self._get_headers(), payload)
             def generate():
-                for chunk_data in self._parse_sse_stream(response):
</file context>

def generate():
for chunk_data in self._parse_sse_stream(response):
chunk = self._normalize_chunk(chunk_data)
if chunk: # Only yield if chunk is not None
yield chunk
try:
for chunk_data in self._parse_sse_stream(response):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The SSE parser splits each network chunk on \n and silently drops any line whose JSON is incomplete. Now that the body streams, an event split across chunk boundaries is lost without an error. Buffer partial lines across chunks, e.g. iterate response.iter_lines() / aiter_lines() as ollama.py does.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/esperanto/providers/llm/google.py, line 506:

<comment>The SSE parser splits each network chunk on `\n` and silently drops any line whose JSON is incomplete. Now that the body streams, an event split across chunk boundaries is lost without an error. Buffer partial lines across chunks, e.g. iterate `response.iter_lines()` / `aiter_lines()` as `ollama.py` does.</comment>

<file context>
@@ -499,22 +499,21 @@ def chat_complete(
-                    if chunk:  # Only yield if chunk is not None
-                        yield chunk
+                try:
+                    for chunk_data in self._parse_sse_stream(response):
+                        chunk = self._normalize_chunk(chunk_data)
+                        if chunk:  # Only yield if chunk is not None
</file context>

chunk = self._normalize_chunk(chunk_data)
if chunk: # Only yield if chunk is not None
yield chunk
finally:
response.close()
return generate()

response = self.client.post(url, headers=self._get_headers(), json=payload)
self._handle_error(response)

response_data = response.json()
result = self._normalize_response(response_data)

Expand Down Expand Up @@ -774,23 +773,22 @@ async def achat_complete(
endpoint = "generateContent"
url = f"{self.base_url}/models/{model_name}:{endpoint}?key={self.api_key}"

# Make async HTTP request
response = await self.async_client.post(
url,
headers=self._get_headers(),
json=payload
)
self._handle_error(response)

if should_stream:
response = await self._aopen_stream(url, self._get_headers(), payload)
async def generate():
async for chunk_data in self._parse_sse_stream_async(response):
chunk = self._normalize_chunk(chunk_data)
if chunk: # Only yield if chunk is not None
yield chunk
try:
async for chunk_data in self._parse_sse_stream_async(response):
chunk = self._normalize_chunk(chunk_data)
if chunk: # Only yield if chunk is not None
yield chunk
finally:
await response.aclose()

return generate()

response = await self.async_client.post(url, headers=self._get_headers(), json=payload)
self._handle_error(response)

response_data = response.json()
result = self._normalize_response(response_data)

Expand Down
Loading