849 words Slides

17.2 Python SDK Setup

Course: Claude Code - Enterprise Development

Section: Claude Agent SDK

Video Length: 2-3 minutes

Presenter: Daniel Treasure


Opening Hook

"Let's get hands-on. We're setting up the Claude Code Agent SDK in Python, creating your first agent, and running it. By the end of this video, you'll have a working Python script that launches an agent."


Key Talking Points

What to say:

  • "Setup is straightforward: install package, set API key, define an agent, run."
  • "The Python SDK is the most Pythonic—familiar patterns if you know the Anthropic SDK."
  • "Your first agent will demonstrate: model selection, system prompt, tools, running a task."

What to show on screen:

  • Terminal showing pip install
  • .env file with ANTHROPIC_API_KEY
  • Python script with agent definition
  • Agent execution and output

Demo Plan

[00:00 - 00:30] Installation & Environment 1. Show terminal: pip install anthropic 2. Create .env file with ANTHROPIC_API_KEY=... 3. Show python-dotenv installation for local development 4. Emphasize: never commit API keys to Git

[00:30 - 01:30] First Agent 1. Create first_agent.py 2. Import: from claude_code import Agent 3. Define agent with: model, system_prompt, tools 4. Add: result = agent.run("Your task here") 5. Print result 6. Run: python first_agent.py 7. Show output: agent response with reasoning

[01:30 - 02:15] Accessing Agent Results 1. Show result object structure: status, output, tool_calls, metadata 2. Demonstrate: accessing different fields 3. Show error handling: try/except for API failures 4. Show logging: what the agent is doing step-by-step

[02:15 - 03:00] (Optional) Configuration 1. Show how to configure: model choice, temperature, max_tokens 2. Explain defaults vs. custom configuration 3. Show: multiple agents in one script (different tasks)


Code Examples & Commands

Installation:

# Create virtual environment
python -m venv venv
source venv/bin/activate  # macOS/Linux
# or: venv\Scripts\activate  # Windows

# Install SDK
pip install anthropic python-dotenv

# Create .env file
echo "ANTHROPIC_API_KEY=your_key_here" > .env

First agent script (first_agent.py):

import os
from dotenv import load_dotenv
from claude_code import Agent

# Load API key from environment
load_dotenv()
api_key = os.getenv("ANTHROPIC_API_KEY")

# Create agent
agent = Agent(
    api_key=api_key,
    model="claude-sonnet-4-5-20250929",
    system_prompt="You are a helpful code assistant. Provide clear, concise answers."
)

# Define task
task = "Explain what a closure is in Python with a simple example"

# Run agent
print(f"Running task: {task}\n")
result = agent.run(task)

# Access results
print(f"Status: {result.status}")
print(f"Output:\n{result.output}")

With error handling:

import os
import logging
from dotenv import load_dotenv
from claude_code import Agent

# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Load environment
load_dotenv()

try:
    agent = Agent(
        model="claude-sonnet-4-5-20250929",
        system_prompt="You are a Python expert."
    )

    result = agent.run("What are decorators in Python?")

    print(f"Output: {result.output}")
    logger.info("Agent task completed successfully")

except Exception as e:
    logger.error(f"Agent failed: {str(e)}")
    raise

With tools:

from claude_code import Agent

agent = Agent(
    model="claude-sonnet-4-5-20250929",
    system_prompt="You are a code reviewer. Use tools to read and analyze code.",
    tools=["Read", "Grep", "Bash"]  # Available tools
)

# Claude will now have access to these tools
result = agent.run("Review the file at /path/to/script.py for security issues")

Gotchas & Tips

Gotcha 1: Missing API Key - If ANTHROPIC_API_KEY is not set, SDK will fail - Solution: Use .env file with python-dotenv, or set directly - Error message: "APIError: No API key provided"

Gotcha 2: Virtual Environment - Always use virtual environment to avoid dependency conflicts - Gotcha: Forgetting to activate venv before pip install

Gotcha 3: Tool Availability - Not all CLI tools are immediately available in SDK - Check documentation for current supported tools - Some tools may require additional setup (e.g., MCP servers)

Gotcha 4: Model Name Typos - Use exact model name: claude-sonnet-4-5-20250929, not sonnet or claude-sonnet - Invalid model name will cause API errors

Tip 1: Virtual Environments - Create separate venv for each project - Naming: venv/ or .venv/ (both work)

Tip 2: Logging - Use Python logging to debug agent behavior - Log: task inputs, outputs, errors, timing

Tip 3: Configuration File - For larger projects, use config file (JSON/YAML) for agent settings - Example: different agents with different models/prompts

Tip 4: Development vs. Production - In development: use staging API keys - In production: use secrets manager (AWS Secrets, HashiCorp Vault)


Lead-out

"You've got Python setup complete. Next, we'll do the same for TypeScript—showing how to set up the SDK in a Node.js project. Then we'll dive into advanced features like streaming and permissions."


Reference URLs

  • Anthropic Python SDK: https://github.com/anthropics/anthropic-sdk-python
  • Python Virtual Environments: https://docs.python.org/3/tutorial/venv.html
  • python-dotenv: https://github.com/theskumar/python-dotenv
  • API Key Setup: https://docs.anthropic.com/

Prep Reading

  • Install Python 3.10+ (if not already done)
  • Obtain ANTHROPIC_API_KEY from Anthropic console
  • Read SDK installation guide (5 min)

Notes for Daniel

  • Pacing: Setup videos should be quick and clear. People just want to get running.
  • Errors are OK: If pip install has a warning, that's normal. Show that it still works.
  • Copy-paste friendly: Make sure viewers can easily copy code examples.
  • Version note: Mention that SDK versions may update; always check docs for latest.