Skip to main content

Your first query

The simplest way to interact with Claude is using the query() function. Here’s a complete working example:
import anyio
from claude_agent_sdk import query

async def main():
    async for message in query(prompt="What is 2 + 2?"):
        print(message)

anyio.run(main)
The query() function is an async function that returns an AsyncIterator of response messages.

Understanding the response

To extract specific content from Claude’s responses, check the message type and content blocks:
from claude_agent_sdk import query, AssistantMessage, TextBlock

async for message in query(prompt="What is 2 + 2?"):
    if isinstance(message, AssistantMessage):
        for block in message.content:
            if isinstance(block, TextBlock):
                print(f"Claude: {block.text}")

Configuring with options

Customize Claude’s behavior using ClaudeAgentOptions:
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, TextBlock

options = ClaudeAgentOptions(
    system_prompt="You are a helpful assistant that explains things simply.",
    max_turns=1,
)

async for message in query(
    prompt="Explain what Python is in one sentence.",
    options=options
):
    if isinstance(message, AssistantMessage):
        for block in message.content:
            if isinstance(block, TextBlock):
                print(f"Claude: {block.text}")

Using tools

Enable Claude to perform actions like reading and writing files:
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, TextBlock

options = ClaudeAgentOptions(
    allowed_tools=["Read", "Write"],
    system_prompt="You are a helpful file assistant.",
)

async for message in query(
    prompt="Create a file called hello.txt with 'Hello, World!' in it",
    options=options,
):
    if isinstance(message, AssistantMessage):
        for block in message.content:
            if isinstance(block, TextBlock):
                print(f"Claude: {block.text}")
By default, Claude will ask for permission before using tools. To auto-accept file edits, set permission_mode='acceptEdits' in your options.

Auto-accepting tool usage

options = ClaudeAgentOptions(
    allowed_tools=["Read", "Write", "Bash"],
    permission_mode='acceptEdits'  # Auto-accept file edits
)

Setting the working directory

Specify a working directory for file operations:
from pathlib import Path
from claude_agent_sdk import ClaudeAgentOptions

options = ClaudeAgentOptions(
    cwd="/path/to/project"  # or Path("/path/to/project")
)

Complete example

Here’s a complete example combining multiple concepts:
import anyio
from claude_agent_sdk import (
    AssistantMessage,
    ClaudeAgentOptions,
    ResultMessage,
    TextBlock,
    query,
)

async def main():
    # Configure options
    options = ClaudeAgentOptions(
        allowed_tools=["Read", "Write"],
        system_prompt="You are a helpful file assistant.",
        max_turns=5,
    )
    
    # Send query
    async for message in query(
        prompt="Create a file called hello.txt with 'Hello, World!' in it",
        options=options,
    ):
        # Handle assistant responses
        if isinstance(message, AssistantMessage):
            for block in message.content:
                if isinstance(block, TextBlock):
                    print(f"Claude: {block.text}")
        
        # Handle result with cost information
        elif isinstance(message, ResultMessage) and message.total_cost_usd > 0:
            print(f"\nCost: ${message.total_cost_usd:.4f}")

if __name__ == "__main__":
    anyio.run(main)

Next steps

Client API

Build interactive, bidirectional conversations

Custom tools

Create your own tools for Claude to use

Hooks

Add custom logic to the agent loop

Error handling

Handle errors gracefully in your application

Build docs developers (and LLMs) love