Overview
Thequery() function is ideal for simple, stateless queries where you don’t need bidirectional communication or conversation management. For interactive, stateful conversations, use ClaudeSDKClient instead.
Key Features
- Unidirectional: Send all messages upfront, receive all responses
- Stateless: Each query is independent, no conversation state
- Simple: Fire-and-forget style, no connection management
- No interrupts: Cannot interrupt or send follow-up messages
When to Use query()
- Simple one-off questions (“What is 2+2?”)
- Batch processing of independent prompts
- Code generation or analysis tasks
- Automated scripts and CI/CD pipelines
- When you know all inputs upfront
When to Use ClaudeSDKClient
- Interactive conversations with follow-ups
- Chat applications or REPL-like interfaces
- When you need to send messages based on responses
- When you need interrupt capabilities
- Long-running sessions with state
Function Signature
Parameters
The prompt to send to Claude. Can be:
- String: For single-shot queries
- AsyncIterable[dict]: For streaming mode with continuous interaction
Optional configuration (defaults to
ClaudeAgentOptions() if None).Key options:- permission_mode: Control tool execution
'default': CLI prompts for dangerous tools'acceptEdits': Auto-accept file edits'bypassPermissions': Allow all tools (use with caution)
- cwd: Working directory for the session
- system_prompt: Custom system prompt
- mcp_servers: MCP server configurations
Optional transport implementation. If provided, this will be used instead of the default transport selection based on options. The transport will be automatically configured with the prompt and options.
Returns
An async iterator that yields messages from the conversation. Messages can include:
AssistantMessage: Text and tool use responses from ClaudeUserMessage: User messages (when using replay-user-messages)SystemMessage: System notifications and status updatesResultMessage: Final result with metadata (cost, tokens, etc.)
Examples
Simple Query
Query with Options
Streaming Mode
Custom Transport
Processing Messages
Related
- ClaudeSDKClient - For interactive, stateful conversations
- ClaudeAgentOptions - Configuration options
- Message Types - Available message types