Skip to main content

Overview

The ClaudeSDKClient 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

Use ClaudeSDKClient 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 use ClaudeSDKClient 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:
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:
Important: Interrupts only work when messages are being actively consumed. You must have a background task receiving messages for interrupts to process.

Dynamic Configuration

Change settings during a conversation:

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

Always use async with when possible to ensure proper cleanup:
When using interrupts, always have a background task consuming messages:
  • Use receive_response() for single query-response cycles
  • Use receive_messages() for continuous streaming
Always cancel and await background tasks to avoid warnings:

Caveats

Async Runtime Context: As of v0.0.20, you cannot use a ClaudeSDKClient instance across different async runtime contexts (e.g., different trio nurseries or asyncio task groups). The client maintains a persistent task group that remains active from connect() until disconnect(). Complete all operations within the same async context where the client was connected.

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