Overview
TheClaudeSDKClient provides full control over interactive conversations with Claude. Unlike the one-shot query() function, the client maintains conversation state and allows bidirectional communication.
For simple one-off questions, use the query() function instead.
When to Use ClaudeSDKClient
UseClaudeSDKClient when you need:
- Multi-turn conversations - Back-and-forth dialogue with context
- Dynamic messaging - Send messages based on Claude’s responses
- Interactive applications - Chat interfaces, REPL-like tools
- Interrupts - Stop execution and change direction
- Session management - Long-running conversations with state
- Real-time applications - React to user input as it comes
Basic Usage with Context Manager
The simplest way to useClaudeSDKClient is with an async context manager:
Multi-Turn Conversations
The client maintains conversation context across multiple exchanges:Manual Connection Management
For more control, manage the connection lifecycle manually:Receiving Messages
There are two ways to receive messages:- receive_response()
- receive_messages()
Automatically stops after receiving a
ResultMessage:Concurrent Send and Receive
Handle responses while sending new messages:Interrupting Execution
Stop Claude mid-execution and change direction:Dynamic Configuration
Change settings during a conversation:- Permission Mode
- Model Selection
Async Iterable Prompts
Stream multiple messages dynamically:Working with Server Info
Get information about the Claude Code server:Error Handling
Handle connection errors and timeouts gracefully:Complete Chat Application Example
Here’s a complete example of a simple chat application:Best Practices
Use Context Managers
Use Context Managers
Always use
async with when possible to ensure proper cleanup:Handle Interrupts Properly
Handle Interrupts Properly
When using interrupts, always have a background task consuming messages:
Choose the Right Receive Method
Choose the Right Receive Method
- Use
receive_response()for single query-response cycles - Use
receive_messages()for continuous streaming
Clean Up Background Tasks
Clean Up Background Tasks
Always cancel and await background tasks to avoid warnings:
Caveats
Next Steps
Custom Tools
Create custom tools with the @tool decorator
Hooks
Implement hooks to customize agent behavior
Permissions
Learn about tool permission control
Examples
More streaming mode examples