Claude Agent SDK

0.1.56 · active · verified Thu Apr 09

The Claude Agent SDK provides a Python interface for interacting with Claude's agent capabilities, allowing developers to define tools, manage sessions, and build conversational agents. It bundles the Claude CLI and runs it as a subprocess. The current version is 0.1.56, and releases are frequent, often weekly, bundling updates to the underlying Claude CLI.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `ClaudeSDKClient`, define a simple tool using the `@tool` decorator, and send a query to Claude. It highlights the use of an API key for authentication and how to capture tool calls and agent responses.

import os
from claude_agent_sdk import ClaudeSDKClient, tool

# Set your API key as an environment variable or replace 'YOUR_ANTHROPIC_API_KEY'
# CLAUDE_CODE_TOKEN is also supported for authentication.
ANTHROPIC_API_KEY = os.environ.get('ANTHROPIC_API_KEY', 'YOUR_ANTHROPIC_API_KEY')

@tool
def get_current_weather(location: str) -> str:
    """Gets the current weather for a given location."""
    if location == "San Francisco":
        return "Sunny, 70F"
    return "Cloudy, 50F"

async def main():
    if ANTHROPIC_API_KEY == 'YOUR_ANTHROPIC_API_KEY':
        print("Please set the ANTHROPIC_API_KEY environment variable or replace the placeholder.")
        return

    client = ClaudeSDKClient(api_key=ANTHROPIC_API_KEY)
    try:
        response = await client.query(
            "What's the weather like in San Francisco?",
            tools=[get_current_weather]
        )
        print(f"Agent response: {response.response}")
        if response.tool_calls:
            for call in response.tool_calls:
                print(f"Tool call: {call.tool_name}({call.input_json})")
        if response.messages:
            for message in response.messages:
                if hasattr(message, 'text'):
                    print(f"Message: {message.text}")

    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == '__main__':
    import asyncio
    asyncio.run(main())

view raw JSON →