forked from anthropics/claude-agent-sdk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinclude_partial_messages.py
More file actions
62 lines (49 loc) · 1.63 KB
/
Copy pathinclude_partial_messages.py
File metadata and controls
62 lines (49 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3
"""
Example of using the "include_partial_messages" option to stream partial messages
from Claude Code SDK.
This feature allows you to receive stream events that contain incremental
updates as Claude generates responses. This is useful for:
- Building real-time UIs that show text as it's being generated
- Monitoring tool use progress
- Getting early results before the full response is complete
Note: Partial message streaming requires the CLI to support it, and the
messages will include StreamEvent messages interspersed with regular messages.
"""
import asyncio
from claude_code_sdk import ClaudeSDKClient
from claude_code_sdk.types import (
ClaudeCodeOptions,
StreamEvent,
AssistantMessage,
UserMessage,
SystemMessage,
ResultMessage,
)
async def main():
# Enable partial message streaming
options = ClaudeCodeOptions(
include_partial_messages=True,
model="claude-sonnet-4-20250514",
max_turns=2,
env={
"MAX_THINKING_TOKENS": "8000",
},
)
client = ClaudeSDKClient(options)
try:
await client.connect()
# Send a prompt that will generate a streaming response
# prompt = "Run a bash command to sleep for 5 seconds"
prompt = "Think of three jokes, then tell one"
print(f"Prompt: {prompt}\n")
print("=" * 50)
await client.query(prompt)
async for message in client.receive_response():
print(message)
finally:
await client.disconnect()
if __name__ == "__main__":
print("Partial Message Streaming Example")
print("=" * 50)
asyncio.run(main())