|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Example demonstrating streaming mode with bidirectional communication.""" |
| 3 | + |
| 4 | +import asyncio |
| 5 | +from collections.abc import AsyncIterator |
| 6 | + |
| 7 | +from claude_code_sdk import ClaudeCodeOptions, ClaudeSDKClient, query |
| 8 | + |
| 9 | + |
| 10 | +async def create_message_stream() -> AsyncIterator[dict]: |
| 11 | + """Create an async stream of user messages.""" |
| 12 | + # Example messages to send |
| 13 | + messages = [ |
| 14 | + { |
| 15 | + "type": "user", |
| 16 | + "message": { |
| 17 | + "role": "user", |
| 18 | + "content": "Hello! Please tell me a bit about Python async programming.", |
| 19 | + }, |
| 20 | + "parent_tool_use_id": None, |
| 21 | + "session_id": "example-session-1", |
| 22 | + }, |
| 23 | + # Add a delay to simulate interactive conversation |
| 24 | + None, # We'll use this as a signal to delay |
| 25 | + { |
| 26 | + "type": "user", |
| 27 | + "message": { |
| 28 | + "role": "user", |
| 29 | + "content": "Can you give me a simple code example?", |
| 30 | + }, |
| 31 | + "parent_tool_use_id": None, |
| 32 | + "session_id": "example-session-1", |
| 33 | + }, |
| 34 | + ] |
| 35 | + |
| 36 | + for msg in messages: |
| 37 | + if msg is None: |
| 38 | + await asyncio.sleep(2) # Simulate user thinking time |
| 39 | + continue |
| 40 | + yield msg |
| 41 | + |
| 42 | + |
| 43 | +async def example_string_mode(): |
| 44 | + """Example using traditional string mode (backward compatible).""" |
| 45 | + print("=== String Mode Example ===") |
| 46 | + |
| 47 | + # Option 1: Using query function |
| 48 | + async for message in query( |
| 49 | + prompt="What is 2+2? Please give a brief answer.", options=ClaudeCodeOptions() |
| 50 | + ): |
| 51 | + print(f"Received: {type(message).__name__}") |
| 52 | + if hasattr(message, "content"): |
| 53 | + print(f" Content: {message.content}") |
| 54 | + |
| 55 | + print("Completed\n") |
| 56 | + |
| 57 | + |
| 58 | +async def example_streaming_mode(): |
| 59 | + """Example using new streaming mode with async iterable.""" |
| 60 | + print("=== Streaming Mode Example ===") |
| 61 | + |
| 62 | + options = ClaudeCodeOptions() |
| 63 | + |
| 64 | + # Create message stream |
| 65 | + message_stream = create_message_stream() |
| 66 | + |
| 67 | + # Use query with async iterable |
| 68 | + message_count = 0 |
| 69 | + async for message in query(prompt=message_stream, options=options): |
| 70 | + message_count += 1 |
| 71 | + msg_type = type(message).__name__ |
| 72 | + |
| 73 | + print(f"\nMessage #{message_count} ({msg_type}):") |
| 74 | + |
| 75 | + if hasattr(message, "content"): |
| 76 | + content = message.content |
| 77 | + if isinstance(content, list): |
| 78 | + for block in content: |
| 79 | + if hasattr(block, "text"): |
| 80 | + print(f" {block.text}") |
| 81 | + else: |
| 82 | + print(f" {content}") |
| 83 | + elif hasattr(message, "subtype"): |
| 84 | + print(f" Subtype: {message.subtype}") |
| 85 | + |
| 86 | + print("\nCompleted") |
| 87 | + |
| 88 | + |
| 89 | +async def example_with_context_manager(): |
| 90 | + """Example using context manager for cleaner code.""" |
| 91 | + print("=== Context Manager Example ===") |
| 92 | + |
| 93 | + # Simple one-shot query with automatic cleanup |
| 94 | + async with ClaudeSDKClient() as client: |
| 95 | + await client.send_message("What is the meaning of life?") |
| 96 | + async for message in client.receive_messages(): |
| 97 | + if hasattr(message, "content"): |
| 98 | + print(f"Response: {message.content}") |
| 99 | + |
| 100 | + print("\nCompleted with automatic cleanup\n") |
| 101 | + |
| 102 | + |
| 103 | +async def example_with_interrupt(): |
| 104 | + """Example demonstrating interrupt functionality.""" |
| 105 | + print("=== Streaming Mode with Interrupt Example ===") |
| 106 | + |
| 107 | + options = ClaudeCodeOptions() |
| 108 | + client = ClaudeSDKClient(options=options) |
| 109 | + |
| 110 | + async def interruptible_stream(): |
| 111 | + """Stream that we'll interrupt.""" |
| 112 | + yield { |
| 113 | + "type": "user", |
| 114 | + "message": { |
| 115 | + "role": "user", |
| 116 | + "content": "Count to 1000 slowly, saying each number.", |
| 117 | + }, |
| 118 | + "parent_tool_use_id": None, |
| 119 | + "session_id": "interrupt-example", |
| 120 | + } |
| 121 | + # Keep the stream open by waiting indefinitely |
| 122 | + # This prevents stdin from being closed |
| 123 | + await asyncio.Event().wait() |
| 124 | + |
| 125 | + try: |
| 126 | + await client.connect(interruptible_stream()) |
| 127 | + print("Connected - will interrupt after 3 seconds") |
| 128 | + |
| 129 | + # Create tasks for receiving and interrupting |
| 130 | + async def receive_and_interrupt(): |
| 131 | + # Start a background task to continuously receive messages |
| 132 | + async def receive_messages(): |
| 133 | + async for message in client.receive_messages(): |
| 134 | + msg_type = type(message).__name__ |
| 135 | + print(f"Received: {msg_type}") |
| 136 | + |
| 137 | + if hasattr(message, "content") and isinstance( |
| 138 | + message.content, list |
| 139 | + ): |
| 140 | + for block in message.content: |
| 141 | + if hasattr(block, "text"): |
| 142 | + print(f" {block.text[:50]}...") # First 50 chars |
| 143 | + |
| 144 | + # Start receiving in background |
| 145 | + receive_task = asyncio.create_task(receive_messages()) |
| 146 | + |
| 147 | + # Wait 3 seconds then interrupt |
| 148 | + await asyncio.sleep(3) |
| 149 | + print("\nSending interrupt signal...") |
| 150 | + |
| 151 | + try: |
| 152 | + await client.interrupt() |
| 153 | + print("Interrupt sent successfully") |
| 154 | + except Exception as e: |
| 155 | + print(f"Interrupt error: {e}") |
| 156 | + |
| 157 | + # Give some time to see any final messages |
| 158 | + await asyncio.sleep(2) |
| 159 | + |
| 160 | + # Cancel the receive task |
| 161 | + receive_task.cancel() |
| 162 | + try: |
| 163 | + await receive_task |
| 164 | + except asyncio.CancelledError: |
| 165 | + pass |
| 166 | + |
| 167 | + await receive_and_interrupt() |
| 168 | + |
| 169 | + except Exception as e: |
| 170 | + print(f"Error: {e}") |
| 171 | + finally: |
| 172 | + await client.disconnect() |
| 173 | + print("\nDisconnected") |
| 174 | + |
| 175 | + |
| 176 | +async def main(): |
| 177 | + """Run all examples.""" |
| 178 | + # Run string mode example |
| 179 | + await example_string_mode() |
| 180 | + |
| 181 | + # Run streaming mode example |
| 182 | + await example_streaming_mode() |
| 183 | + |
| 184 | + # Run context manager example |
| 185 | + await example_with_context_manager() |
| 186 | + |
| 187 | + # Run interrupt example |
| 188 | + await example_with_interrupt() |
| 189 | + |
| 190 | + |
| 191 | +if __name__ == "__main__": |
| 192 | + asyncio.run(main()) |
0 commit comments