MCPcopy Create free account
hub / github.com/anomalyco/opencode-sdk-python / AsyncStream

Class AsyncStream

src/opencode_ai/_streaming.py:84–145  ·  view source on GitHub ↗

Provides the core interface to iterate over an asynchronous stream response.

Source from the content-addressed store, hash-verified

82
83
84class AsyncStream(Generic[_T]):
85 """Provides the core interface to iterate over an asynchronous stream response."""
86
87 response: httpx.Response
88
89 _decoder: SSEDecoder | SSEBytesDecoder
90
91 def __init__(
92 self,
93 *,
94 cast_to: type[_T],
95 response: httpx.Response,
96 client: AsyncOpencode,
97 ) -> None:
98 self.response = response
99 self._cast_to = cast_to
100 self._client = client
101 self._decoder = client._make_sse_decoder()
102 self._iterator = self.__stream__()
103
104 async def __anext__(self) -> _T:
105 return await self._iterator.__anext__()
106
107 async def __aiter__(self) -> AsyncIterator[_T]:
108 async for item in self._iterator:
109 yield item
110
111 async def _iter_events(self) -> AsyncIterator[ServerSentEvent]:
112 async for sse in self._decoder.aiter_bytes(self.response.aiter_bytes()):
113 yield sse
114
115 async def __stream__(self) -> AsyncIterator[_T]:
116 cast_to = cast(Any, self._cast_to)
117 response = self.response
118 process_data = self._client._process_response_data
119 iterator = self._iter_events()
120
121 async for sse in iterator:
122 yield process_data(data=sse.json(), cast_to=cast_to, response=response)
123
124 # Ensure the entire stream is consumed
125 async for _sse in iterator:
126 ...
127
128 async def __aenter__(self) -> Self:
129 return self
130
131 async def __aexit__(
132 self,
133 exc_type: type[BaseException] | None,
134 exc: BaseException | None,
135 exc_tb: TracebackType | None,
136 ) -> None:
137 await self.close()
138
139 async def close(self) -> None:
140 """
141 Close the response and release the connection.

Callers 1

make_event_iteratorFunction · 0.90

Calls

no outgoing calls

Tested by 1

make_event_iteratorFunction · 0.72