Provides the core interface to iterate over a synchronous stream response.
| 43 | |
| 44 | |
| 45 | class Stream(Generic[_T], metaclass=_SyncStreamMeta): |
| 46 | """Provides the core interface to iterate over a synchronous stream response.""" |
| 47 | |
| 48 | response: httpx.Response |
| 49 | _options: Optional[FinalRequestOptions] = None |
| 50 | _decoder: SSEBytesDecoder |
| 51 | |
| 52 | def __init__( |
| 53 | self, |
| 54 | *, |
| 55 | cast_to: type[_T], |
| 56 | response: httpx.Response, |
| 57 | client: Anthropic, |
| 58 | options: Optional[FinalRequestOptions] = None, |
| 59 | ) -> None: |
| 60 | self.response = response |
| 61 | self._cast_to = cast_to |
| 62 | self._client = client |
| 63 | self._options = options |
| 64 | self._decoder = client._make_sse_decoder() |
| 65 | self._iterator = self.__stream__() |
| 66 | |
| 67 | def __next__(self) -> _T: |
| 68 | return self._iterator.__next__() |
| 69 | |
| 70 | def __iter__(self) -> Iterator[_T]: |
| 71 | for item in self._iterator: |
| 72 | yield item |
| 73 | |
| 74 | def _iter_events(self) -> Iterator[ServerSentEvent]: |
| 75 | yield from self._decoder.iter_bytes(self.response.iter_bytes()) |
| 76 | |
| 77 | @staticmethod |
| 78 | def raw_events(response: httpx.Response) -> Iterator[ServerSentEvent]: |
| 79 | """Iterate the raw Server-Sent Events from `response`, before any JSON |
| 80 | parsing or event-name filtering. |
| 81 | |
| 82 | This reads the response body directly, so the response is consumed. |
| 83 | """ |
| 84 | return SSEDecoder().iter_bytes(response.iter_bytes()) |
| 85 | |
| 86 | def __stream__(self) -> Iterator[_T]: |
| 87 | cast_to = cast(Any, self._cast_to) |
| 88 | response = self.response |
| 89 | process_data = self._client._process_response_data |
| 90 | iterator = self._iter_events() |
| 91 | |
| 92 | try: |
| 93 | for sse in iterator: |
| 94 | if sse.event == "completion": |
| 95 | yield process_data(data=sse.json(), cast_to=cast_to, response=response) |
| 96 | |
| 97 | if ( |
| 98 | sse.event == "message_start" |
| 99 | or sse.event == "message_delta" |
| 100 | or sse.event == "message_stop" |
| 101 | or sse.event == "content_block_start" |
| 102 | or sse.event == "content_block_delta" |
no outgoing calls