fix(llm): stream chunks as they arrive and raise stream errors at the call

1Q
1mo ago
+664-210

Problem

With stream=True, every HTTP-based LLM provider sends the request with a buffered client.post(...) / async_client.post(...) and then parses the SSE events from the finished response. httpx reads the whole body before post returns, so the "stream" arrives all at once when the model has finished.

Measured against an OpenAI-compatible vLLM gateway with OpenAICompatibleLanguageModel.achat_complete(stream=True):

1st chunktotal
2.28.06.72 s6.73 s
raw httpx stream to the same server0.53 s2.09 s
this branch0.50-0.56 s3.8 s

Azure already used client.stream(...), but raised HTTP errors inside the generator, so a 429 surfaced only when the caller started iterating.

Change

  • LanguageModel._open_stream / _aopen_stream (base class): build the request, send(..., stream=True), and on an error status read the body, close it and call the provider's _handle_error, so the error is raised at the call, before an iterator is returned. A caller that retries on 429 (or any rate limit) therefore still sees it where it can retry.
  • Every provider whose streaming path parsed a buffered response now uses the helpers and closes the response in a finally: anthropic, azure, cohere, google, groq, mistral, ollama (NDJSON), openai, openai_compatible (and the profiles that inherit it), openrouter, perplexity.
  • Vertex is unchanged: its REST path calls the non-streaming generateContent and yields 1 chunk by design.

Tests

  • tests/providers/llm/test_streaming_transport.py: for each of the 11 classes, sync and async, chat_complete(stream=True) against an httpx.MockTransport whose body sends the 1st event and then blocks until the test has received the 1st chunk. Buffered code can never return that chunk, so the test times out. Proven by reverting Groq to the buffered .post: test_provider_chat_streaming_opens_before_body_finishes[GroqLanguageModel] timed out; restored, the file passes.
  • A 429 matrix: the error is raised by the chat_complete/achat_complete call itself, before iteration.
  • The existing streaming tests that mocked .post now mock the opening path; every assertion on payloads (stream flag, merged extra_body, tools, thinking) and on chunk content is kept.

uv run pytest tests/providers tests/unit tests/common_types tests/test_deprecation_warnings.py -q --no-cov: 1792 passed (1748 on main), ruff check . and mypy src/esperanto clean.