# Claude Cookbooks Deep Dive

## What Is It?

**Claude Cookbooks** is Anthropic's official collection of Jupyter notebooks demonstrating how to build with Claude. With **30.4k+ stars**, it's the definitive resource for Claude development patterns, from basic capabilities to advanced agent architectures.

**Repository:** [anthropics/claude-cookbooks](https://github.com/anthropics/claude-cookbooks)

---

## The Problem It Solves

Developers learning Claude often:
- Lack practical, runnable examples
- Don't know optimal patterns for common use cases
- Miss best practices for tool use and context management
- Need guidance on advanced features like extended thinking

Claude Cookbooks provides:
- **60+ Jupyter notebooks** with executable code
- **15+ topic directories** covering all Claude capabilities
- **Production patterns** for agents, RAG, and multimodal
- **Skills framework** for document generation

---

## Key Statistics

| Metric | Value |
|--------|-------|
| **Stars** | 30,400 |
| **Notebooks** | 60+ |
| **Topic Directories** | 15+ |
| **License** | MIT |
| **Organization** | Anthropic |

---

## Directory Structure

### Core Capabilities

```
capabilities/
├── pdf_processing/           # PDF upload and analysis
├── token_counting/           # Usage tracking
├── prompt_caching/           # Cost optimization
├── batch_processing/         # High-volume operations
└── extended_thinking/        # Deep reasoning
```

### Tool Use

```
tool_use/
├── intro_tool_use/           # Getting started
├── prompt_caching/           # Cached tool schemas
├── calculator_tool/          # Simple tool example
├── customer_service/         # Multi-tool agent
└── mcp_demos/               # Model Context Protocol
```

### Multimodal

```
multimodal/
├── vision_charts/            # Chart understanding
├── vision_documents/         # Document analysis
├── vision_code/              # Code from screenshots
└── vision_general/           # Image processing
```

### Patterns & Agents

```
patterns/
├── agentic_loop/             # Basic agent loop
├── orchestrator_subagents/   # Multi-agent patterns
├── routing/                  # Intent classification
├── parallelization/          # Concurrent processing
└── evaluator_optimizer/      # Self-improving agents
```

---

## Extended Thinking

One of Claude's most powerful features for complex reasoning:

```python
import anthropic

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=16000,
    thinking={
        "type": "enabled",
        "budget_tokens": 10000  # Thinking token budget
    },
    messages=[{
        "role": "user",
        "content": "Solve this complex math problem step by step..."
    }]
)

# Access thinking and response
for block in response.content:
    if block.type == "thinking":
        print(f"Thinking: {block.thinking}")
    elif block.type == "text":
        print(f"Answer: {block.text}")
```

### Use Cases for Extended Thinking

- Complex mathematical proofs
- Multi-step reasoning problems
- Code architecture decisions
- Strategic planning
- Research analysis

---

## Skills Framework

Generate professional documents with Claude:

### Excel Generation

```python
@skill
def create_excel(data: dict, filename: str) -> str:
    """Generate Excel spreadsheet from structured data"""
    import openpyxl

    wb = openpyxl.Workbook()
    ws = wb.active

    # Headers
    for col, header in enumerate(data["headers"], 1):
        ws.cell(row=1, column=col, value=header)

    # Data rows
    for row_idx, row in enumerate(data["rows"], 2):
        for col_idx, value in enumerate(row, 1):
            ws.cell(row=row_idx, column=col_idx, value=value)

    wb.save(filename)
    return f"Created {filename}"
```

### Available Skills

| Skill | Output |
|-------|--------|
| **Excel** | .xlsx spreadsheets |
| **PowerPoint** | .pptx presentations |
| **PDF** | PDF documents |
| **Word** | .docx documents |
| **Charts** | Matplotlib/Plotly visualizations |

---

## Agent Patterns

### Basic Agentic Loop

```python
def agentic_loop(prompt: str, tools: list):
    """Simple agent that uses tools until task complete"""
    messages = [{"role": "user", "content": prompt}]

    while True:
        response = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=4096,
            tools=tools,
            messages=messages
        )

        # Check for tool use
        if response.stop_reason == "tool_use":
            tool_results = execute_tools(response.content)
            messages.append({"role": "assistant", "content": response.content})
            messages.append({"role": "user", "content": tool_results})
        else:
            return response.content
```

### Orchestrator-Subagents

```
┌─────────────────────────────────┐
│        Orchestrator Agent       │
│   (Plans and delegates tasks)   │
└─────────────┬───────────────────┘
              │
    ┌─────────┼─────────┐
    ▼         ▼         ▼
┌───────┐ ┌───────┐ ┌───────┐
│Research│ │Writing│ │Review │
│ Agent │ │ Agent │ │ Agent │
└───────┘ └───────┘ └───────┘
```

### Evaluator-Optimizer

```python
def evaluate_and_optimize(initial_output: str, criteria: list):
    """Self-improving loop with evaluation"""
    output = initial_output

    for _ in range(3):  # Max iterations
        evaluation = evaluate(output, criteria)

        if evaluation["score"] >= 0.9:
            return output

        output = optimize(output, evaluation["feedback"])

    return output
```

---

## RAG Patterns

### Basic RAG

```python
def rag_query(query: str, documents: list) -> str:
    """Simple RAG with document context"""

    # Retrieve relevant documents
    relevant_docs = semantic_search(query, documents, top_k=5)

    # Format context
    context = "\n\n".join([
        f"<document source=\"{doc['source']}\">\n{doc['content']}\n</document>"
        for doc in relevant_docs
    ])

    # Query with context
    response = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=4096,
        messages=[{
            "role": "user",
            "content": f"""Based on the following documents, answer the question.

Documents:
{context}

Question: {query}"""
        }]
    )

    return response.content[0].text
```

### Contextual Retrieval

Enhanced RAG with document preprocessing:

```python
def add_context_to_chunks(chunks: list) -> list:
    """Add contextual headers to improve retrieval"""
    enriched = []

    for chunk in chunks:
        context = client.messages.create(
            model="claude-haiku-3-20240307",
            max_tokens=200,
            messages=[{
                "role": "user",
                "content": f"""Provide a brief context for this chunk:

{chunk['content']}

Context should explain what document this is from and key topics."""
            }]
        )

        enriched.append({
            "content": f"{context.content[0].text}\n\n{chunk['content']}",
            "metadata": chunk["metadata"]
        })

    return enriched
```

---

## Tool Use Patterns

### Defining Tools

```python
tools = [
    {
        "name": "get_weather",
        "description": "Get current weather for a location",
        "input_schema": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City and country"
                },
                "units": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "default": "celsius"
                }
            },
            "required": ["location"]
        }
    }
]
```

### Tool Execution

```python
def execute_tools(content: list) -> list:
    """Execute tool calls and return results"""
    results = []

    for block in content:
        if block.type == "tool_use":
            result = call_tool(block.name, block.input)
            results.append({
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": str(result)
            })

    return results
```

---

## Prompt Caching

Reduce costs for repeated context:

```python
# First call - caches the system prompt
response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    system=[{
        "type": "text",
        "text": large_system_prompt,
        "cache_control": {"type": "ephemeral"}
    }],
    messages=[{"role": "user", "content": query}]
)

# Cache statistics
print(f"Input tokens: {response.usage.input_tokens}")
print(f"Cache read: {response.usage.cache_read_input_tokens}")
print(f"Cache write: {response.usage.cache_creation_input_tokens}")
```

### Cost Savings

| Scenario | Without Cache | With Cache |
|----------|---------------|------------|
| Large system prompt | Full price | 90% discount |
| Few-shot examples | Full price | 90% discount |
| Document context | Full price | 90% discount |

---

## Multimodal Examples

### Image Analysis

```python
import base64

def analyze_image(image_path: str, prompt: str) -> str:
    """Analyze image with Claude's vision"""

    with open(image_path, "rb") as f:
        image_data = base64.standard_b64encode(f.read()).decode()

    response = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=1024,
        messages=[{
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": "image/png",
                        "data": image_data
                    }
                },
                {
                    "type": "text",
                    "text": prompt
                }
            ]
        }]
    )

    return response.content[0].text
```

### PDF Processing

```python
import anthropic
import base64

def process_pdf(pdf_path: str, query: str) -> str:
    """Process PDF with Claude"""

    with open(pdf_path, "rb") as f:
        pdf_data = base64.standard_b64encode(f.read()).decode()

    response = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=4096,
        messages=[{
            "role": "user",
            "content": [
                {
                    "type": "document",
                    "source": {
                        "type": "base64",
                        "media_type": "application/pdf",
                        "data": pdf_data
                    }
                },
                {
                    "type": "text",
                    "text": query
                }
            ]
        }]
    )

    return response.content[0].text
```

---

## Batch Processing

For high-volume, cost-effective processing:

```python
# Create batch request
batch = client.batches.create(
    requests=[
        {
            "custom_id": f"request-{i}",
            "params": {
                "model": "claude-sonnet-4-20250514",
                "max_tokens": 1024,
                "messages": [{"role": "user", "content": prompt}]
            }
        }
        for i, prompt in enumerate(prompts)
    ]
)

# Check status
status = client.batches.retrieve(batch.id)
print(f"Status: {status.processing_status}")

# Get results when complete
if status.processing_status == "ended":
    results = client.batches.results(batch.id)
```

### Batch Benefits

- **50% cost reduction** vs synchronous
- **High throughput** for bulk processing
- **24-hour completion** SLA
- **Automatic retries** on failures

---

## MCP Integration

Using Model Context Protocol with Claude:

```python
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("cookbook-demo")

@mcp.tool()
def search_recipes(query: str, cuisine: str = None) -> list:
    """Search recipe database"""
    return search_db(query, cuisine)

@mcp.resource("recipe://{recipe_id}")
def get_recipe(recipe_id: str) -> dict:
    """Get recipe details"""
    return fetch_recipe(recipe_id)

if __name__ == "__main__":
    mcp.run()
```

---

## Best Practices from Cookbooks

### Prompt Engineering

1. **Be specific** - Clear instructions get better results
2. **Use examples** - Few-shot improves consistency
3. **Structure output** - Request JSON or specific formats
4. **Chain of thought** - Ask Claude to reason step by step

### Tool Design

1. **Clear descriptions** - Help Claude choose correctly
2. **Minimal parameters** - Don't overwhelm the model
3. **Type hints** - Use proper JSON schema types
4. **Error messages** - Return helpful failure info

### Agent Design

1. **Single responsibility** - One task per agent
2. **Clear termination** - Know when to stop
3. **Error handling** - Graceful recovery
4. **Logging** - Track agent decisions

---

## Running the Notebooks

### Setup

```bash
# Clone repository
git clone https://github.com/anthropics/claude-cookbooks
cd claude-cookbooks

# Create environment
python -m venv venv
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Set API key
export ANTHROPIC_API_KEY=sk-ant-...

# Launch Jupyter
jupyter notebook
```

### Notebook Categories

| Category | Focus | Difficulty |
|----------|-------|------------|
| **Capabilities** | Core Claude features | Beginner |
| **Tool Use** | Function calling | Intermediate |
| **Multimodal** | Images and PDFs | Intermediate |
| **Patterns** | Agent architectures | Advanced |
| **Skills** | Document generation | Advanced |

---

## Key Takeaways

1. **Extended thinking** unlocks complex reasoning
2. **Tool use** follows a consistent pattern
3. **RAG** benefits from contextual preprocessing
4. **Prompt caching** dramatically reduces costs
5. **Agent patterns** are composable building blocks
6. **Skills** enable professional document output
7. **Batch processing** is ideal for bulk workloads

---

## Resources

- **Repository:** https://github.com/anthropics/claude-cookbooks
- **API Documentation:** https://docs.anthropic.com
- **Claude Console:** https://console.anthropic.com
- **MCP Specification:** https://modelcontextprotocol.io

---

*Claude Cookbooks is the essential reference for Claude development. Whether you're building a simple chatbot or complex multi-agent system, these notebooks provide production-ready patterns.*
