Debian Codegraph @

examples/messages_stream.py

raw
1 #!/usr/bin/env -S uv run python
2
3 import asyncio
4
5 from anthropic import AsyncAnthropic
6
7 client = AsyncAnthropic()
8
9
10 async def main() -> None:
11 async with client.messages.stream(
12 max_tokens=1024,
13 messages=[
14 {
15 "role": "user",
16 "content": "Say hello there!",
17 }
18 ],
19 model="claude-sonnet-5",
20 ) as stream:
21 async for event in stream:
22 if event.type == "text":
23 print(event.text, end="", flush=True)
24 elif event.type == "content_block_stop":
25 print()
26 print("\ncontent block finished accumulating:", event.content_block)
27 print()
28
29 # you can still get the accumulated final message outside of
30 # the context manager, as long as the entire stream was consumed
31 # inside of the context manager
32 accumulated = await stream.get_final_message()
33 print("accumulated message: ", accumulated.to_json())
34
35
36 asyncio.run(main())