Debian Codegraph @

src/anthropic/lib/streaming/_messages.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 from __future__ import annotations
2
3 from types import TracebackType
4 from typing import TYPE_CHECKING, Any, Type, Generic, Callable, cast
5 from typing_extensions import Self, Iterator, Awaitable, AsyncIterator, assert_never
6
7 import httpx2
8 from pydantic import BaseModel
9
10 from anthropic.types.tool_use_block import ToolUseBlock
11 from anthropic.types.server_tool_use_block import ServerToolUseBlock
12
13 from ._types import (
14 TextEvent,
15 CitationEvent,
16 ThinkingEvent,
17 InputJsonEvent,
18 SignatureEvent,
19 ParsedMessageStopEvent,
20 ParsedMessageStreamEvent,
21 ParsedContentBlockStopEvent,
22 )
23 from ...types import RawMessageStreamEvent
24 from ..._types import NotGiven, not_given
25 from ..._utils import consume_sync_iterator, consume_async_iterator
26 from ..._models import build, construct_type, construct_type_unchecked
27 from ..._streaming import Stream, AsyncStream
28 from ..._utils._utils import is_given
29 from .._parse._response import ResponseFormatT, parse_text
30 from ...types.parsed_message import ParsedMessage, ParsedContentBlock
31
32
33 class MessageStream(Generic[ResponseFormatT]):
34 text_stream: Iterator[str]
35 """Iterator over just the text deltas in the stream.
36
37 ```py
38 for text in stream.text_stream:
39 print(text, end="", flush=True)
40 print()
41 ```
42 """
43
44 def __init__(
45 self,
46 raw_stream: Stream[RawMessageStreamEvent],
47 output_format: ResponseFormatT | NotGiven,
48 ) -> None:
49 self._raw_stream = raw_stream
50 self.text_stream = self.__stream_text__()
51 self._iterator = self.__stream__()
52 self.__final_message_snapshot: ParsedMessage[ResponseFormatT] | None = None
53 self.__json_bufs: dict[int, bytes] = {}
54 self.__output_format = output_format
55
56 @property
57 def response(self) -> httpx2.Response:
58 return self._raw_stream.response
59
60 @property
61 def request_id(self) -> str | None:
62 return self.response.headers.get("request-id") # type: ignore[no-any-return]
63
64 @property
65 def workspace_id(self) -> str | None:
66 return self.response.headers.get("anthropic-workspace-id") # type: ignore[no-any-return]
67
68 def __next__(self) -> ParsedMessageStreamEvent[ResponseFormatT]:
69 return self._iterator.__next__()
70
71 def __iter__(self) -> Iterator[ParsedMessageStreamEvent[ResponseFormatT]]:
72 for item in self._iterator:
73 yield item
74
75 def __enter__(self) -> Self:
76 return self
77
78 def __exit__(
79 self,
80 exc_type: type[BaseException] | None,
81 exc: BaseException | None,
82 exc_tb: TracebackType | None,
83 ) -> None:
84 self.close()
85
86 def close(self) -> None:
87 """
88 Close the response and release the connection.
89
90 Automatically called if the response body is read to completion.
91 """
92 self._raw_stream.close()
93
94 def get_final_message(self) -> ParsedMessage[ResponseFormatT]:
95 """Waits until the stream has been read to completion and returns
96 the accumulated `Message` object.
97 """
98 self.until_done()
99 assert self.__final_message_snapshot is not None
100 return self.__final_message_snapshot
101
102 def get_final_text(self) -> str:
103 """Returns all `text` content blocks concatenated together.
104
105 > [!NOTE]
106 > Currently the API will only respond with a single content block.
107
108 Will raise an error if no `text` content blocks were returned.
109 """
110 message = self.get_final_message()
111 text_blocks: list[str] = []
112 for block in message.content:
113 if block.type == "text":
114 text_blocks.append(block.text)
115
116 if not text_blocks:
117 raise RuntimeError(
118 f".get_final_text() can only be called when the API returns a `text` content block.\nThe API returned {','.join([b.type for b in message.content])} content block type(s) that you can access by calling get_final_message().content"
119 )
120
121 return "".join(text_blocks)
122
123 def until_done(self) -> None:
124 """Blocks until the stream has been consumed"""
125 consume_sync_iterator(self)
126
127 @property
128 def current_message_snapshot(self) -> ParsedMessage[ResponseFormatT]:
129 assert self.__final_message_snapshot is not None
130 return self.__final_message_snapshot
131
132 def __stream__(self) -> Iterator[ParsedMessageStreamEvent[ResponseFormatT]]:
133 for sse_event in self._raw_stream:
134 self.__final_message_snapshot = accumulate_event(
135 event=sse_event,
136 current_snapshot=self.__final_message_snapshot,
137 json_bufs=self.__json_bufs,
138 output_format=self.__output_format,
139 )
140
141 events_to_fire = build_events(event=sse_event, message_snapshot=self.current_message_snapshot)
142 for event in events_to_fire:
143 yield event
144
145 def __stream_text__(self) -> Iterator[str]:
146 for chunk in self:
147 if chunk.type == "content_block_delta" and chunk.delta.type == "text_delta":
148 yield chunk.delta.text
149
150
151 class MessageStreamManager(Generic[ResponseFormatT]):
152 """Wrapper over MessageStream that is returned by `.stream()`.
153
154 ```py
155 with client.messages.stream(...) as stream:
156 for chunk in stream:
157 ...
158 ```
159 """
160
161 def __init__(
162 self,
163 api_request: Callable[[], Stream[RawMessageStreamEvent]],
164 *,
165 output_format: ResponseFormatT | NotGiven,
166 ) -> None:
167 self.__stream: MessageStream[ResponseFormatT] | None = None
168 self.__api_request = api_request
169 self.__output_format = output_format
170
171 def __enter__(self) -> MessageStream[ResponseFormatT]:
172 raw_stream = self.__api_request()
173 self.__stream = MessageStream(raw_stream, output_format=self.__output_format)
174 return self.__stream
175
176 def __exit__(
177 self,
178 exc_type: type[BaseException] | None,
179 exc: BaseException | None,
180 exc_tb: TracebackType | None,
181 ) -> None:
182 if self.__stream is not None:
183 self.__stream.close()
184
185
186 class AsyncMessageStream(Generic[ResponseFormatT]):
187 text_stream: AsyncIterator[str]
188 """Async iterator over just the text deltas in the stream.
189
190 ```py
191 async for text in stream.text_stream:
192 print(text, end="", flush=True)
193 print()
194 ```
195 """
196
197 def __init__(
198 self,
199 raw_stream: AsyncStream[RawMessageStreamEvent],
200 output_format: ResponseFormatT | NotGiven,
201 ) -> None:
202 self._raw_stream = raw_stream
203 self.text_stream = self.__stream_text__()
204 self._iterator = self.__stream__()
205 self.__final_message_snapshot: ParsedMessage[ResponseFormatT] | None = None
206 self.__json_bufs: dict[int, bytes] = {}
207 self.__output_format = output_format
208
209 @property
210 def response(self) -> httpx2.Response:
211 return self._raw_stream.response
212
213 @property
214 def request_id(self) -> str | None:
215 return self.response.headers.get("request-id") # type: ignore[no-any-return]
216
217 @property
218 def workspace_id(self) -> str | None:
219 return self.response.headers.get("anthropic-workspace-id") # type: ignore[no-any-return]
220
221 async def __anext__(self) -> ParsedMessageStreamEvent[ResponseFormatT]:
222 return await self._iterator.__anext__()
223
224 async def __aiter__(self) -> AsyncIterator[ParsedMessageStreamEvent[ResponseFormatT]]:
225 async for item in self._iterator:
226 yield item
227
228 async def __aenter__(self) -> Self:
229 return self
230
231 async def __aexit__(
232 self,
233 exc_type: type[BaseException] | None,
234 exc: BaseException | None,
235 exc_tb: TracebackType | None,
236 ) -> None:
237 await self.close()
238
239 async def close(self) -> None:
240 """
241 Close the response and release the connection.
242
243 Automatically called if the response body is read to completion.
244 """
245 await self._raw_stream.close()
246
247 async def get_final_message(self) -> ParsedMessage[ResponseFormatT]:
248 """Waits until the stream has been read to completion and returns
249 the accumulated `Message` object.
250 """
251 await self.until_done()
252 assert self.__final_message_snapshot is not None
253 return self.__final_message_snapshot
254
255 async def get_final_text(self) -> str:
256 """Returns all `text` content blocks concatenated together.
257
258 > [!NOTE]
259 > Currently the API will only respond with a single content block.
260
261 Will raise an error if no `text` content blocks were returned.
262 """
263 message = await self.get_final_message()
264 text_blocks: list[str] = []
265 for block in message.content:
266 if block.type == "text":
267 text_blocks.append(block.text)
268
269 if not text_blocks:
270 raise RuntimeError(
271 f".get_final_text() can only be called when the API returns a `text` content block.\nThe API returned {','.join([b.type for b in message.content])} content block type(s) that you can access by calling get_final_message().content"
272 )
273
274 return "".join(text_blocks)
275
276 async def until_done(self) -> None:
277 """Waits until the stream has been consumed"""
278 await consume_async_iterator(self)
279
280 @property
281 def current_message_snapshot(self) -> ParsedMessage[ResponseFormatT]:
282 assert self.__final_message_snapshot is not None
283 return self.__final_message_snapshot
284
285 async def __stream__(self) -> AsyncIterator[ParsedMessageStreamEvent[ResponseFormatT]]:
286 async for sse_event in self._raw_stream:
287 self.__final_message_snapshot = accumulate_event(
288 event=sse_event,
289 current_snapshot=self.__final_message_snapshot,
290 json_bufs=self.__json_bufs,
291 output_format=self.__output_format,
292 )
293
294 events_to_fire = build_events(event=sse_event, message_snapshot=self.current_message_snapshot)
295 for event in events_to_fire:
296 yield event
297
298 async def __stream_text__(self) -> AsyncIterator[str]:
299 async for chunk in self:
300 if chunk.type == "content_block_delta" and chunk.delta.type == "text_delta":
301 yield chunk.delta.text
302
303
304 class AsyncMessageStreamManager(Generic[ResponseFormatT]):
305 """Wrapper over AsyncMessageStream that is returned by `.stream()`
306 so that an async context manager can be used without `await`ing the
307 original client call.
308
309 ```py
310 async with client.messages.stream(...) as stream:
311 async for chunk in stream:
312 ...
313 ```
314 """
315
316 def __init__(
317 self,
318 api_request: Awaitable[AsyncStream[RawMessageStreamEvent]],
319 *,
320 output_format: ResponseFormatT | NotGiven = not_given,
321 ) -> None:
322 self.__stream: AsyncMessageStream[ResponseFormatT] | None = None
323 self.__api_request = api_request
324 self.__output_format = output_format
325
326 async def __aenter__(self) -> AsyncMessageStream[ResponseFormatT]:
327 raw_stream = await self.__api_request
328 self.__stream = AsyncMessageStream(raw_stream, output_format=self.__output_format)
329 return self.__stream
330
331 async def __aexit__(
332 self,
333 exc_type: type[BaseException] | None,
334 exc: BaseException | None,
335 exc_tb: TracebackType | None,
336 ) -> None:
337 if self.__stream is not None:
338 await self.__stream.close()
339
340
341 def build_events(
342 *,
343 event: RawMessageStreamEvent,
344 message_snapshot: ParsedMessage[ResponseFormatT],
345 ) -> list[ParsedMessageStreamEvent[ResponseFormatT]]:
346 events_to_fire: list[ParsedMessageStreamEvent[ResponseFormatT]] = []
347
348 if event.type == "message_start":
349 events_to_fire.append(event)
350 elif event.type == "message_delta":
351 events_to_fire.append(event)
352 elif event.type == "message_stop":
353 events_to_fire.append(
354 build(ParsedMessageStopEvent[ResponseFormatT], type="message_stop", message=message_snapshot)
355 )
356 elif event.type == "content_block_start":
357 events_to_fire.append(event)
358 elif event.type == "content_block_delta":
359 events_to_fire.append(event)
360
361 content_block = message_snapshot.content[event.index]
362 if event.delta.type == "text_delta":
363 if content_block.type == "text":
364 events_to_fire.append(
365 build(
366 TextEvent,
367 type="text",
368 text=event.delta.text,
369 snapshot=content_block.text,
370 )
371 )
372 elif event.delta.type == "input_json_delta":
373 if isinstance(content_block, TRACKS_TOOL_INPUT):
374 events_to_fire.append(
375 build(
376 InputJsonEvent,
377 type="input_json",
378 partial_json=event.delta.partial_json,
379 snapshot=content_block.input,
380 )
381 )
382 elif event.delta.type == "citations_delta":
383 if content_block.type == "text":
384 events_to_fire.append(
385 build(
386 CitationEvent,
387 type="citation",
388 citation=event.delta.citation,
389 snapshot=content_block.citations or [],
390 )
391 )
392 elif event.delta.type == "thinking_delta":
393 if content_block.type == "thinking":
394 events_to_fire.append(
395 build(
396 ThinkingEvent,
397 type="thinking",
398 thinking=event.delta.thinking,
399 snapshot=content_block.thinking,
400 )
401 )
402 elif event.delta.type == "signature_delta":
403 if content_block.type == "thinking":
404 events_to_fire.append(
405 build(
406 SignatureEvent,
407 type="signature",
408 signature=content_block.signature,
409 )
410 )
411 pass
412 else:
413 # we only want exhaustive checking for linters, not at runtime
414 if TYPE_CHECKING: # type: ignore[unreachable]
415 assert_never(event.delta)
416 elif event.type == "content_block_stop":
417 content_block = message_snapshot.content[event.index]
418
419 event_to_fire = build(
420 ParsedContentBlockStopEvent,
421 type="content_block_stop",
422 index=event.index,
423 content_block=content_block,
424 )
425
426 events_to_fire.append(event_to_fire)
427 else:
428 # we only want exhaustive checking for linters, not at runtime
429 if TYPE_CHECKING: # type: ignore[unreachable]
430 assert_never(event)
431
432 return events_to_fire
433
434
435 TRACKS_TOOL_INPUT = (
436 ToolUseBlock,
437 ServerToolUseBlock,
438 )
439
440
441 def accumulate_event(
442 *,
443 event: RawMessageStreamEvent,
444 current_snapshot: ParsedMessage[ResponseFormatT] | None,
445 json_bufs: dict[int, bytes],
446 output_format: ResponseFormatT | NotGiven = not_given,
447 ) -> ParsedMessage[ResponseFormatT]:
448 if not isinstance(cast(Any, event), BaseModel):
449 event = cast( # pyright: ignore[reportUnnecessaryCast]
450 RawMessageStreamEvent,
451 construct_type_unchecked(
452 type_=cast(Type[RawMessageStreamEvent], RawMessageStreamEvent),
453 value=event,
454 ),
455 )
456 if not isinstance(cast(Any, event), BaseModel):
457 raise TypeError(f"Unexpected event runtime type, after deserialising twice - {event} - {type(event)}")
458
459 if current_snapshot is None:
460 if event.type == "message_start":
461 return cast(ParsedMessage[ResponseFormatT], ParsedMessage.construct(**cast(Any, event.message.to_dict())))
462
463 raise RuntimeError(f'Unexpected event order, got {event.type} before "message_start"')
464
465 if event.type == "content_block_start":
466 # TODO: check index
467 current_snapshot.content.append(
468 cast(
469 Any, # Pydantic does not support generic unions at runtime
470 construct_type(type_=ParsedContentBlock, value=event.content_block.to_dict()),
471 ),
472 )
473 elif event.type == "content_block_delta":
474 content = current_snapshot.content[event.index]
475 if event.delta.type == "text_delta":
476 if content.type == "text":
477 content.text += event.delta.text
478 elif event.delta.type == "input_json_delta":
479 if isinstance(content, TRACKS_TOOL_INPUT):
480 from jiter import from_json
481
482 json_buf = json_bufs.get(event.index, b"")
483 json_buf += bytes(event.delta.partial_json, "utf-8")
484
485 if json_buf:
486 try:
487 content.input = from_json(json_buf, partial_mode=True)
488 except ValueError as e:
489 raise ValueError(
490 f"Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: {e}. JSON: {json_buf.decode('utf-8')}"
491 ) from e
492
493 json_bufs[event.index] = json_buf
494 elif event.delta.type == "citations_delta":
495 if content.type == "text":
496 if not content.citations:
497 content.citations = [event.delta.citation]
498 else:
499 content.citations.append(event.delta.citation)
500 elif event.delta.type == "thinking_delta":
501 if content.type == "thinking":
502 content.thinking += event.delta.thinking
503 elif event.delta.type == "signature_delta":
504 if content.type == "thinking":
505 content.signature = event.delta.signature
506 else:
507 # we only want exhaustive checking for linters, not at runtime
508 if TYPE_CHECKING: # type: ignore[unreachable]
509 assert_never(event.delta)
510 elif event.type == "content_block_stop":
511 content_block = current_snapshot.content[event.index]
512 if content_block.type == "text" and is_given(output_format):
513 content_block.parsed_output = parse_text(content_block.text, output_format)
514 elif event.type == "message_delta":
515 current_snapshot.stop_reason = event.delta.stop_reason
516 current_snapshot.stop_sequence = event.delta.stop_sequence
517 current_snapshot.stop_details = event.delta.stop_details
518 if event.delta.container is not None:
519 current_snapshot.container = event.delta.container
520 current_snapshot.usage.output_tokens = event.usage.output_tokens
521
522 # Usage counts on a message_delta are cumulative totals, so they overwrite rather
523 # than add; optional ones are omitted when not applicable, in which case the
524 # message_start value must survive.
525 if event.usage.input_tokens is not None:
526 current_snapshot.usage.input_tokens = event.usage.input_tokens
527 if event.usage.cache_creation_input_tokens is not None:
528 current_snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens
529 if event.usage.cache_read_input_tokens is not None:
530 current_snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens
531 if event.usage.server_tool_use is not None:
532 current_snapshot.usage.server_tool_use = event.usage.server_tool_use
533 if event.usage.output_tokens_details is not None:
534 current_snapshot.usage.output_tokens_details = event.usage.output_tokens_details
535
536 return current_snapshot