Debian Codegraph @

src/anthropic/lib/streaming/_beta_messages.py

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