Repository navigation
fix(llm): stream chunks as they arrive and raise stream errors at the call #320
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -774,22 +774,27 @@ def chat_complete( | |
| top_p=effective_top_p, | ||
| ) | ||
|
|
||
| # Make HTTP request | ||
| if should_stream: | ||
| response = self._open_stream( | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 Prompt for AI agents |
||
| f"{self.base_url}/messages", self._get_headers(), payload | ||
| ) | ||
| def generate(): | ||
| try: | ||
| for event_data in self._parse_sse_stream(response): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1: The new streaming path feeds Prompt for AI agents |
||
| 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) | ||
|
|
||
|
|
@@ -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) | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
@@ -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, | ||
|
|
@@ -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) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 Prompt for AI agents |
||
| else: | ||
| # Non-streaming request | ||
| url = self._build_url("chat/completions") | ||
|
|
@@ -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, | ||
|
|
@@ -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") | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
||
|
|
@@ -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() | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: A failed read of an error response skips Prompt for AI agents |
||
| 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]]: | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1: Streaming now reads raw network chunks, but Prompt for AI agents |
||
| 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) | ||
|
|
||
|
|
@@ -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) | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: The stream is opened before Prompt for AI agents |
||
| 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): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: The SSE parser splits each network chunk on Prompt for AI agents |
||
| 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) | ||
|
|
||
|
|
@@ -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) | ||
|
|
||
|
|
||
There was a problem hiding this comment.
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