claude-cookbooks
Claude AI cookbooks - code examples, tutorials, and best practices for using Claude API. Use when learning Claude API integration, building Claude-powered applications, or exploring Claude capabilities.
Packaged view
This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.
Install command
npx @skill-hub/cli install aiskillstore-marketplace-claude-cookbooks
Repository
Skill path: skills/2025emma/claude-cookbooks
Claude AI cookbooks - code examples, tutorials, and best practices for using Claude API. Use when learning Claude API integration, building Claude-powered applications, or exploring Claude capabilities.
Open repositoryBest for
Primary workflow: Analyze Data & AI.
Technical facets: Full Stack, Backend, Data / AI, Integration.
Target audience: everyone.
License: Unknown.
Original source
Catalog source: SkillHub Club.
Repository owner: aiskillstore.
This is still a mirrored public skill entry. Review the repository before installing into production workflows.
What it helps with
- Install claude-cookbooks into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
- Review https://github.com/aiskillstore/marketplace before adding claude-cookbooks to shared team environments
- Use claude-cookbooks for development workflows
Works across
Favorites: 0.
Sub-skills: 0.
Aggregator: No.
Original source / Raw SKILL.md
---
name: claude-cookbooks
description: Claude AI cookbooks - code examples, tutorials, and best practices for using Claude API. Use when learning Claude API integration, building Claude-powered applications, or exploring Claude capabilities.
---
# Claude Cookbooks Skill
Comprehensive code examples and guides for building with Claude AI, sourced from the official Anthropic cookbooks repository.
## When to Use This Skill
This skill should be triggered when:
- Learning how to use Claude API
- Implementing Claude integrations
- Building applications with Claude
- Working with tool use and function calling
- Implementing multimodal features (vision, image analysis)
- Setting up RAG (Retrieval Augmented Generation)
- Integrating Claude with third-party services
- Building AI agents with Claude
- Optimizing prompts for Claude
- Implementing advanced patterns (caching, sub-agents, etc.)
## Quick Reference
### Basic API Usage
```python
import anthropic
client = anthropic.Anthropic(api_key="your-api-key")
# Simple message
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{
"role": "user",
"content": "Hello, Claude!"
}]
)
```
### Tool Use (Function Calling)
```python
# Define a tool
tools = [{
"name": "get_weather",
"description": "Get current weather for a location",
"input_schema": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
}
}]
# Use the tool
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "What's the weather in San Francisco?"}]
)
```
### Vision (Image Analysis)
```python
# Analyze an image
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": base64_image
}
},
{"type": "text", "text": "Describe this image"}
]
}]
)
```
### Prompt Caching
```python
# Use prompt caching for efficiency
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
system=[{
"type": "text",
"text": "Large system prompt here...",
"cache_control": {"type": "ephemeral"}
}],
messages=[{"role": "user", "content": "Your question"}]
)
```
## Key Capabilities Covered
### 1. Classification
- Text classification techniques
- Sentiment analysis
- Content categorization
- Multi-label classification
### 2. Retrieval Augmented Generation (RAG)
- Vector database integration
- Semantic search
- Context retrieval
- Knowledge base queries
### 3. Summarization
- Document summarization
- Meeting notes
- Article condensing
- Multi-document synthesis
### 4. Text-to-SQL
- Natural language to SQL queries
- Database schema understanding
- Query optimization
- Result interpretation
### 5. Tool Use & Function Calling
- Tool definition and schema
- Parameter validation
- Multi-tool workflows
- Error handling
### 6. Multimodal
- Image analysis and OCR
- Chart/graph interpretation
- Visual question answering
- Image generation integration
### 7. Advanced Patterns
- Agent architectures
- Sub-agent delegation
- Prompt optimization
- Cost optimization with caching
## Repository Structure
The cookbooks are organized into these main categories:
- **capabilities/** - Core AI capabilities (classification, RAG, summarization, text-to-SQL)
- **tool_use/** - Function calling and tool integration examples
- **multimodal/** - Vision and image-related examples
- **patterns/** - Advanced patterns like agents and workflows
- **third_party/** - Integrations with external services (Pinecone, LlamaIndex, etc.)
- **claude_agent_sdk/** - Agent SDK examples and templates
- **misc/** - Additional utilities (PDF upload, JSON mode, evaluations, etc.)
## Reference Files
This skill includes comprehensive documentation in `references/`:
- **main_readme.md** - Main repository overview
- **capabilities.md** - Core capabilities documentation
- **tool_use.md** - Tool use and function calling guides
- **multimodal.md** - Vision and multimodal capabilities
- **third_party.md** - Third-party integrations
- **patterns.md** - Advanced patterns and agents
- **index.md** - Complete reference index
## Common Use Cases
### Building a Customer Service Agent
1. Define tools for CRM access, ticket creation, knowledge base search
2. Use tool use API to handle function calls
3. Implement conversation memory
4. Add fallback mechanisms
See: `references/tool_use.md#customer-service`
### Implementing RAG
1. Create embeddings of your documents
2. Store in vector database (Pinecone, etc.)
3. Retrieve relevant context on query
4. Augment Claude's response with context
See: `references/capabilities.md#rag`
### Processing Documents with Vision
1. Convert document to images or PDF
2. Use vision API to extract content
3. Structure the extracted data
4. Validate and post-process
See: `references/multimodal.md#vision`
### Building Multi-Agent Systems
1. Define specialized agents for different tasks
2. Implement routing logic
3. Use sub-agents for delegation
4. Aggregate results
See: `references/patterns.md#agents`
## Best Practices
### API Usage
- Use appropriate model for task (Sonnet for balance, Haiku for speed, Opus for complex tasks)
- Implement retry logic with exponential backoff
- Handle rate limits gracefully
- Monitor token usage for cost optimization
### Prompt Engineering
- Be specific and clear in instructions
- Provide examples when needed
- Use system prompts for consistent behavior
- Structure outputs with JSON mode when needed
### Tool Use
- Define clear, specific tool schemas
- Validate inputs and outputs
- Handle errors gracefully
- Keep tool descriptions concise but informative
### Multimodal
- Use high-quality images (higher resolution = better results)
- Be specific about what to extract/analyze
- Respect size limits (5MB per image)
- Use appropriate image formats (JPEG, PNG, GIF, WebP)
## Performance Optimization
### Prompt Caching
- Cache large system prompts
- Cache frequently used context
- Monitor cache hit rates
- Balance caching vs. fresh content
### Cost Optimization
- Use Haiku for simple tasks
- Implement prompt caching for repeated context
- Set appropriate max_tokens
- Batch similar requests
### Latency Optimization
- Use streaming for long responses
- Minimize message history
- Optimize image sizes
- Use appropriate timeout values
## Resources
### Official Documentation
- [Anthropic Developer Docs](https://docs.claude.com)
- [API Reference](https://docs.claude.com/claude/reference)
- [Anthropic Support](https://support.anthropic.com)
### Community
- [Anthropic Discord](https://www.anthropic.com/discord)
- [GitHub Cookbooks Repo](https://github.com/anthropics/claude-cookbooks)
### Learning Resources
- [Claude API Fundamentals Course](https://github.com/anthropics/courses/tree/master/anthropic_api_fundamentals)
- [Prompt Engineering Guide](https://docs.claude.com/claude/docs/guide-to-anthropics-prompt-engineering-resources)
## Working with This Skill
### For Beginners
Start with `references/main_readme.md` and explore basic examples in `references/capabilities.md`
### For Specific Features
- Tool use → `references/tool_use.md`
- Vision → `references/multimodal.md`
- RAG → `references/capabilities.md#rag`
- Agents → `references/patterns.md#agents`
### For Code Examples
Each reference file contains practical, copy-pasteable code examples
## Examples Available
The cookbook includes 50+ practical examples including:
- Customer service chatbot with tool use
- RAG with Pinecone vector database
- Document summarization
- Image analysis and OCR
- Chart/graph interpretation
- Natural language to SQL
- Content moderation filter
- Automated evaluations
- Multi-agent systems
- Prompt caching optimization
## Notes
- All examples use official Anthropic Python SDK
- Code is production-ready with error handling
- Examples follow current API best practices
- Regular updates from Anthropic team
- Community contributions welcome
## Skill Source
This skill was created from the official Anthropic Claude Cookbooks repository:
https://github.com/anthropics/claude-cookbooks
Repository cloned and processed on: 2025-10-29
---
## Referenced Files
> The following files are referenced in this skill and included for context.
### references/main_readme.md
```markdown
# Claude Cookbooks
The Claude Cookbooks provide code and guides designed to help developers build with Claude, offering copy-able code snippets that you can easily integrate into your own projects.
## Prerequisites
To make the most of the examples in this cookbook, you'll need an Claude API key (sign up for free [here](https://www.anthropic.com)).
While the code examples are primarily written in Python, the concepts can be adapted to any programming language that supports interaction with the Claude API.
If you're new to working with the Claude API, we recommend starting with our [Claude API Fundamentals course](https://github.com/anthropics/courses/tree/master/anthropic_api_fundamentals) to get a solid foundation.
## Explore Further
Looking for more resources to enhance your experience with Claude and AI assistants? Check out these helpful links:
- [Anthropic developer documentation](https://docs.claude.com/claude/docs/guide-to-anthropics-prompt-engineering-resources)
- [Anthropic support docs](https://support.anthropic.com)
- [Anthropic Discord community](https://www.anthropic.com/discord)
## Contributing
The Claude Cookbooks thrives on the contributions of the developer community. We value your input, whether it's submitting an idea, fixing a typo, adding a new guide, or improving an existing one. By contributing, you help make this resource even more valuable for everyone.
To avoid duplication of efforts, please review the existing issues and pull requests before contributing.
If you have ideas for new examples or guides, share them on the [issues page](https://github.com/anthropics/anthropic-cookbook/issues).
## Table of recipes
### Capabilities
- [Classification](https://github.com/anthropics/anthropic-cookbook/tree/main/capabilities/classification): Explore techniques for text and data classification using Claude.
- [Retrieval Augmented Generation](https://github.com/anthropics/anthropic-cookbook/tree/main/capabilities/retrieval_augmented_generation): Learn how to enhance Claude's responses with external knowledge.
- [Summarization](https://github.com/anthropics/anthropic-cookbook/tree/main/capabilities/summarization): Discover techniques for effective text summarization with Claude.
### Tool Use and Integration
- [Tool use](https://github.com/anthropics/anthropic-cookbook/tree/main/tool_use): Learn how to integrate Claude with external tools and functions to extend its capabilities.
- [Customer service agent](https://github.com/anthropics/anthropic-cookbook/blob/main/tool_use/customer_service_agent.ipynb)
- [Calculator integration](https://github.com/anthropics/anthropic-cookbook/blob/main/tool_use/calculator_tool.ipynb)
- [SQL queries](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/how_to_make_sql_queries.ipynb)
### Third-Party Integrations
- [Retrieval augmented generation](https://github.com/anthropics/anthropic-cookbook/tree/main/third_party): Supplement Claude's knowledge with external data sources.
- [Vector databases (Pinecone)](https://github.com/anthropics/anthropic-cookbook/blob/main/third_party/Pinecone/rag_using_pinecone.ipynb)
- [Wikipedia](https://github.com/anthropics/anthropic-cookbook/blob/main/third_party/Wikipedia/wikipedia-search-cookbook.ipynb/)
- [Web pages](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/read_web_pages_with_haiku.ipynb)
- [Embeddings with Voyage AI](https://github.com/anthropics/anthropic-cookbook/blob/main/third_party/VoyageAI/how_to_create_embeddings.md)
### Multimodal Capabilities
- [Vision with Claude](https://github.com/anthropics/anthropic-cookbook/tree/main/multimodal):
- [Getting started with images](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/getting_started_with_vision.ipynb)
- [Best practices for vision](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/best_practices_for_vision.ipynb)
- [Interpreting charts and graphs](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/reading_charts_graphs_powerpoints.ipynb)
- [Extracting content from forms](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/how_to_transcribe_text.ipynb)
- [Generate images with Claude](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/illustrated_responses.ipynb): Use Claude with Stable Diffusion for image generation.
### Advanced Techniques
- [Sub-agents](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/using_sub_agents.ipynb): Learn how to use Haiku as a sub-agent in combination with Opus.
- [Upload PDFs to Claude](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/pdf_upload_summarization.ipynb): Parse and pass PDFs as text to Claude.
- [Automated evaluations](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/building_evals.ipynb): Use Claude to automate the prompt evaluation process.
- [Enable JSON mode](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/how_to_enable_json_mode.ipynb): Ensure consistent JSON output from Claude.
- [Create a moderation filter](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/building_moderation_filter.ipynb): Use Claude to create a content moderation filter for your application.
- [Prompt caching](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/prompt_caching.ipynb): Learn techniques for efficient prompt caching with Claude.
## Additional Resources
- [Anthropic on AWS](https://github.com/aws-samples/anthropic-on-aws): Explore examples and solutions for using Claude on AWS infrastructure.
- [AWS Samples](https://github.com/aws-samples/): A collection of code samples from AWS which can be adapted for use with Claude. Note that some samples may require modification to work optimally with Claude.
```
### references/capabilities.md
```markdown
# Claude Capabilities
Welcome to the Capabilities section of the Claude Cookbooks! This directory contains a collection of guides that showcase specific capabilities where Claude excels. Each guide provides an in-depth exploration of a particular capability, discussing potential use cases, prompt engineering techniques to optimize results, and approaches for evaluating Claude's performance.
## Guides
- **[Classification with Claude](./classification/guide.ipynb)**: Discover how Claude can revolutionize classification tasks, especially in scenarios with complex business rules and limited training data. This guide walks you through data preparation, prompt engineering with retrieval-augmented generation (RAG), testing, and evaluation.
- **[Retrieval Augmented Generation with Claude](./retrieval_augmented_generation/guide.ipynb)**: Learn how to enhance Claude's capabilities with domain-specific knowledge using RAG. This guide demonstrates how to build a RAG system from scratch, optimize its performance, and create an evaluation suite. You'll learn how techniques like summary indexing and re-ranking can significantly improve precision, recall, and overall accuracy in question-answering tasks.
- **[Retrieval Augmented Generation with Contextual Embeddings](./contextual-embeddings/guide.ipynb)**: Learn how to use a new technique to improve the performance of your RAG system. In traditional RAG, documents are typically split into smaller chunks for efficient retrieval. While this approach works well for many applications, it can lead to problems when individual chunks lack sufficient context. Contextual Embeddings solve this problem by adding relevant context to each chunk before embedding. You'll learn how to use contextual embeddings with semantic search, BM25 search, and reranking to improve performance.
- **[Summarization with Claude](./summarization/guide.ipynb)**: Explore Claude's ability to summarize and synthesize information from multiple sources. This guide covers a variety of summarization techniques, including multi-shot, domain-based, and chunking methods, as well as strategies for handling long-form content and multiple documents. We also explore evaluating summaries, which can be a balance of art, subjectivity, and the right approach!
- **[Text-to-SQL with Claude](./text_to_sql/guide.ipynb)**: This guide covers how to generate complex SQL queries from natural language using prompting techniques, self-improvement, and RAG. We'll also explore how to evaluate and improve the accuracy of generated SQL queries, with evals that test for syntax, data correctness, row count, and more.
## Getting Started
To get started with these guides, simply navigate to the desired guide's directory and follow the instructions provided in the `guide.ipynb` file. Each guide is self-contained and includes all the necessary code, data, and evaluation scripts to reproduce the examples and experiments.
```
### references/tool_use.md
```markdown
# Tool Use with Claude
Source: anthropics/claude-cookbooks/tool_use
## Overview
Learn how to integrate Claude with external tools and functions to extend its capabilities.
## Key Examples
### Customer Service Agent
- **Location**: `tool_use/customer_service_agent.ipynb`
- **Description**: Build an intelligent customer service agent using Claude with tool integration
- **Key Concepts**: Function calling, state management, conversation flow
### Calculator Integration
- **Location**: `tool_use/calculator_tool.ipynb`
- **Description**: Integrate external calculation tools with Claude
- **Key Concepts**: Tool definitions, parameter passing, result handling
### Memory Demo
- **Location**: `tool_use/memory_demo/`
- **Description**: Implement persistent memory for Claude conversations
- **Key Concepts**: Context management, state persistence
## Best Practices
1. **Tool Definition**: Define clear, specific tool schemas
2. **Error Handling**: Implement robust error handling for tool calls
3. **Validation**: Validate tool inputs and outputs
4. **Context**: Maintain context across tool interactions
## Common Patterns
```python
# Tool definition example
tools = [{
"name": "calculator",
"description": "Performs basic arithmetic operations",
"input_schema": {
"type": "object",
"properties": {
"operation": {"type": "string"},
"a": {"type": "number"},
"b": {"type": "number"}
},
"required": ["operation", "a", "b"]
}
}]
```
## Related Resources
- [Anthropic Tool Use Documentation](https://docs.claude.com/claude/docs/tool-use)
- [API Reference](https://docs.claude.com/claude/reference)
```
### references/multimodal.md
```markdown
# Multimodal Capabilities with Claude
Source: anthropics/claude-cookbooks/multimodal
## Vision Capabilities
### Getting Started with Images
- **Location**: `multimodal/getting_started_with_vision.ipynb`
- **Topics**: Image upload, analysis, OCR, visual question answering
### Best Practices for Vision
- **Location**: `multimodal/best_practices_for_vision.ipynb`
- **Topics**: Image quality, prompt engineering for vision, error handling
### Charts and Graphs
- **Location**: `multimodal/reading_charts_graphs_powerpoints.ipynb`
- **Topics**: Data extraction from charts, graph interpretation, PowerPoint analysis
### Form Extraction
- **Location**: `multimodal/how_to_transcribe_text.ipynb`
- **Topics**: OCR, structured data extraction, form processing
## Image Generation
### Illustrated Responses
- **Location**: `misc/illustrated_responses.ipynb`
- **Topics**: Integration with Stable Diffusion, image generation prompts
## Code Examples
```python
# Vision API example
import anthropic
client = anthropic.Anthropic()
# Analyze an image
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": image_base64
}
},
{
"type": "text",
"text": "What's in this image?"
}
]
}]
)
```
## Tips
1. **Image Quality**: Higher resolution images provide better results
2. **Prompt Clarity**: Be specific about what you want to extract or analyze
3. **Format Support**: JPEG, PNG, GIF, WebP supported
4. **Size Limits**: Max 5MB per image
```
---
## Skill Companion Files
> Additional files collected from the skill directory layout.
### references/CONTRIBUTING.md
```markdown
# Contributing to Claude Cookbooks
Thank you for your interest in contributing to the Claude Cookbooks! This guide will help you get started with development and ensure your contributions meet our quality standards.
## Development Setup
### Prerequisites
- Python 3.11 or higher
- [uv](https://docs.astral.sh/uv/) package manager (recommended) or pip
### Quick Start
1. **Install uv** (recommended package manager):
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```
Or with Homebrew:
```bash
brew install uv
```
2. **Clone the repository**:
```bash
git clone https://github.com/anthropics/anthropic-cookbook.git
cd anthropic-cookbook
```
3. **Set up the development environment**:
```bash
# Create virtual environment and install dependencies
uv sync --all-extras
# Or with pip:
pip install -e ".[dev]"
```
4. **Install pre-commit hooks**:
```bash
uv run pre-commit install
# Or: pre-commit install
```
5. **Set up your API key**:
```bash
cp .env.example .env
# Edit .env and add your Claude API key
```
## Quality Standards
This repository uses automated tools to maintain code quality:
### The Notebook Validation Stack
- **[nbconvert](https://nbconvert.readthedocs.io/)**: Notebook execution for testing
- **[ruff](https://docs.astral.sh/ruff/)**: Fast Python linter and formatter with native Jupyter support
- **Claude AI Review**: Intelligent code review using Claude
**Note**: Notebook outputs are intentionally kept in this repository as they demonstrate expected results for users.
### Claude Code Slash Commands
This repository includes slash commands that work in both Claude Code (for local development) and GitHub Actions CI. These commands are automatically available when you work in this repository with Claude Code.
**Available Commands**:
- `/link-review` - Validate links in markdown and notebooks
- `/model-check` - Verify Claude model usage is current
- `/notebook-review` - Comprehensive notebook quality check
**Usage in Claude Code**:
```bash
# Run the same validations that CI will run
/notebook-review skills/my-notebook.ipynb
/model-check
/link-review README.md
```
These commands use the exact same validation logic as our CI pipeline, helping you catch issues before pushing. The command definitions are stored in `.claude/commands/` for both local and CI use.
### Before Committing
1. **Run quality checks**:
```bash
uv run ruff check skills/ --fix
uv run ruff format skills/
uv run python scripts/validate_notebooks.py
```
3. **Test notebook execution** (optional, requires API key):
```bash
uv run jupyter nbconvert --to notebook \
--execute skills/classification/guide.ipynb \
--ExecutePreprocessor.kernel_name=python3 \
--output test_output.ipynb
```
### Pre-commit Hooks
Pre-commit hooks will automatically run before each commit to ensure code quality:
- Format code with ruff
- Validate notebook structure
If a hook fails, fix the issues and try committing again.
## Contribution Guidelines
### Notebook Best Practices
1. **Use environment variables for API keys**:
```python
import os
api_key = os.environ.get("ANTHROPIC_API_KEY")
```
2. **Use current Claude models**:
- Use model aliases for better maintainability when available
- Latest Haiku model: `claude-haiku-4-5-20251001` (Haiku 4.5)
- Check current models at: https://docs.claude.com/en/docs/about-claude/models/overview
- Claude will automatically validate model usage in PR reviews
3. **Keep notebooks focused**:
- One concept per notebook
- Clear explanations and comments
- Include expected outputs as markdown cells
4. **Test your notebooks**:
- Ensure they run from top to bottom without errors
- Use minimal tokens for example API calls
- Include error handling
### Git Workflow
1. **Create a feature branch**:
```bash
git checkout -b <your-name>/<feature-description>
# Example: git checkout -b alice/add-rag-example
```
2. **Use conventional commits**:
```bash
# Format: <type>(<scope>): <subject>
# Types:
feat # New feature
fix # Bug fix
docs # Documentation
style # Formatting
refactor # Code restructuring
test # Tests
chore # Maintenance
ci # CI/CD changes
# Examples:
git commit -m "feat(skills): add text-to-sql notebook"
git commit -m "fix(api): use environment variable for API key"
git commit -m "docs(readme): update installation instructions"
```
3. **Keep commits atomic**:
- One logical change per commit
- Write clear, descriptive messages
- Reference issues when applicable
4. **Push and create PR**:
```bash
git push -u origin your-branch-name
gh pr create # Or use GitHub web interface
```
### Pull Request Guidelines
1. **PR Title**: Use conventional commit format
2. **Description**: Include:
- What changes you made
- Why you made them
- How to test them
- Related issue numbers
3. **Keep PRs focused**: One feature/fix per PR
4. **Respond to feedback**: Address review comments promptly
## Testing
### Local Testing
Run the validation suite:
```bash
# Check all notebooks
uv run python scripts/validate_notebooks.py
# Run pre-commit on all files
uv run pre-commit run --all-files
```
### CI/CD
Our GitHub Actions workflows will automatically:
- Validate notebook structure
- Lint code with ruff
- Test notebook execution (for maintainers)
- Check links
- Claude reviews code and model usage
External contributors will have limited API testing to conserve resources.
## Getting Help
- **Issues**: [GitHub Issues](https://github.com/anthropics/anthropic-cookbook/issues)
- **Discussions**: [GitHub Discussions](https://github.com/anthropics/anthropic-cookbook/discussions)
- **Discord**: [Anthropic Discord](https://www.anthropic.com/discord)
## Security
- Never commit API keys or secrets
- Use environment variables for sensitive data
- Report security issues privately to [email protected]
## License
By contributing, you agree that your contributions will be licensed under the same license as the project (MIT License).
```
### references/README.md
```markdown
# Claude Cookbooks
The Claude Cookbooks provide code and guides designed to help developers build with Claude, offering copy-able code snippets that you can easily integrate into your own projects.
## Prerequisites
To make the most of the examples in this cookbook, you'll need an Claude API key (sign up for free [here](https://www.anthropic.com)).
While the code examples are primarily written in Python, the concepts can be adapted to any programming language that supports interaction with the Claude API.
If you're new to working with the Claude API, we recommend starting with our [Claude API Fundamentals course](https://github.com/anthropics/courses/tree/master/anthropic_api_fundamentals) to get a solid foundation.
## Explore Further
Looking for more resources to enhance your experience with Claude and AI assistants? Check out these helpful links:
- [Anthropic developer documentation](https://docs.claude.com/claude/docs/guide-to-anthropics-prompt-engineering-resources)
- [Anthropic support docs](https://support.anthropic.com)
- [Anthropic Discord community](https://www.anthropic.com/discord)
## Contributing
The Claude Cookbooks thrives on the contributions of the developer community. We value your input, whether it's submitting an idea, fixing a typo, adding a new guide, or improving an existing one. By contributing, you help make this resource even more valuable for everyone.
To avoid duplication of efforts, please review the existing issues and pull requests before contributing.
If you have ideas for new examples or guides, share them on the [issues page](https://github.com/anthropics/anthropic-cookbook/issues).
## Table of recipes
### Capabilities
- [Classification](https://github.com/anthropics/anthropic-cookbook/tree/main/capabilities/classification): Explore techniques for text and data classification using Claude.
- [Retrieval Augmented Generation](https://github.com/anthropics/anthropic-cookbook/tree/main/capabilities/retrieval_augmented_generation): Learn how to enhance Claude's responses with external knowledge.
- [Summarization](https://github.com/anthropics/anthropic-cookbook/tree/main/capabilities/summarization): Discover techniques for effective text summarization with Claude.
### Tool Use and Integration
- [Tool use](https://github.com/anthropics/anthropic-cookbook/tree/main/tool_use): Learn how to integrate Claude with external tools and functions to extend its capabilities.
- [Customer service agent](https://github.com/anthropics/anthropic-cookbook/blob/main/tool_use/customer_service_agent.ipynb)
- [Calculator integration](https://github.com/anthropics/anthropic-cookbook/blob/main/tool_use/calculator_tool.ipynb)
- [SQL queries](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/how_to_make_sql_queries.ipynb)
### Third-Party Integrations
- [Retrieval augmented generation](https://github.com/anthropics/anthropic-cookbook/tree/main/third_party): Supplement Claude's knowledge with external data sources.
- [Vector databases (Pinecone)](https://github.com/anthropics/anthropic-cookbook/blob/main/third_party/Pinecone/rag_using_pinecone.ipynb)
- [Wikipedia](https://github.com/anthropics/anthropic-cookbook/blob/main/third_party/Wikipedia/wikipedia-search-cookbook.ipynb/)
- [Web pages](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/read_web_pages_with_haiku.ipynb)
- [Embeddings with Voyage AI](https://github.com/anthropics/anthropic-cookbook/blob/main/third_party/VoyageAI/how_to_create_embeddings.md)
### Multimodal Capabilities
- [Vision with Claude](https://github.com/anthropics/anthropic-cookbook/tree/main/multimodal):
- [Getting started with images](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/getting_started_with_vision.ipynb)
- [Best practices for vision](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/best_practices_for_vision.ipynb)
- [Interpreting charts and graphs](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/reading_charts_graphs_powerpoints.ipynb)
- [Extracting content from forms](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/how_to_transcribe_text.ipynb)
- [Generate images with Claude](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/illustrated_responses.ipynb): Use Claude with Stable Diffusion for image generation.
### Advanced Techniques
- [Sub-agents](https://github.com/anthropics/anthropic-cookbook/blob/main/multimodal/using_sub_agents.ipynb): Learn how to use Haiku as a sub-agent in combination with Opus.
- [Upload PDFs to Claude](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/pdf_upload_summarization.ipynb): Parse and pass PDFs as text to Claude.
- [Automated evaluations](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/building_evals.ipynb): Use Claude to automate the prompt evaluation process.
- [Enable JSON mode](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/how_to_enable_json_mode.ipynb): Ensure consistent JSON output from Claude.
- [Create a moderation filter](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/building_moderation_filter.ipynb): Use Claude to create a content moderation filter for your application.
- [Prompt caching](https://github.com/anthropics/anthropic-cookbook/blob/main/misc/prompt_caching.ipynb): Learn techniques for efficient prompt caching with Claude.
## Additional Resources
- [Anthropic on AWS](https://github.com/aws-samples/anthropic-on-aws): Explore examples and solutions for using Claude on AWS infrastructure.
- [AWS Samples](https://github.com/aws-samples/): A collection of code samples from AWS which can be adapted for use with Claude. Note that some samples may require modification to work optimally with Claude.
```
### references/index.md
```markdown
# Claude Cookbooks - Reference Index
This skill contains code and guides for building with Claude AI.
## Categories
### Capabilities
- [Classification](capabilities.md#classification)
- [Retrieval Augmented Generation](capabilities.md#rag)
- [Summarization](capabilities.md#summarization)
- [Text to SQL](capabilities.md#text-to-sql)
### Tool Use and Integration
- [Tool Use Basics](tool_use.md#basics)
- [Customer Service Agent](tool_use.md#customer-service)
- [Calculator Integration](tool_use.md#calculator)
### Multimodal
- [Vision with Claude](multimodal.md#vision)
- [Image Generation](multimodal.md#generation)
- [Charts and Graphs](multimodal.md#charts)
### Advanced Patterns
- [Agents](patterns.md#agents)
- [Sub-agents](patterns.md#sub-agents)
- [Prompt Caching](patterns.md#caching)
### Third Party Integrations
- [Vector Databases](third_party.md#vector-db)
- [Embeddings](third_party.md#embeddings)
- [LlamaIndex](third_party.md#llamaindex)
```
### references/patterns.md
```markdown
# Building Effective Agents Cookbook
Reference implementation for [Building Effective Agents](https://anthropic.com/research/building-effective-agents) by Erik Schluntz and Barry Zhang.
This repository contains example minimal implementations of common agent workflows discussed in the blog:
- Basic Building Blocks
- Prompt Chaining
- Routing
- Multi-LLM Parallelization
- Advanced Workflows
- Orchestrator-Subagents
- Evaluator-Optimizer
## Getting Started
See the Jupyter notebooks for detailed examples:
- [Basic Workflows](basic_workflows.ipynb)
- [Evaluator-Optimizer Workflow](evaluator_optimizer.ipynb)
- [Orchestrator-Workers Workflow](orchestrator_workers.ipynb)
```
### references/third_party.md
```markdown
# Third Party Integrations
Source: anthropics/claude-cookbooks/third_party
## Vector Databases
### Pinecone
- **Location**: `third_party/Pinecone/rag_using_pinecone.ipynb`
- **Use Case**: Retrieval Augmented Generation with vector search
- **Key Concepts**: Embeddings, similarity search, RAG pipeline
## Embeddings
### Voyage AI
- **Location**: `third_party/VoyageAI/how_to_create_embeddings.md`
- **Use Case**: Creating high-quality embeddings for semantic search
- **Key Concepts**: Embedding models, dimensionality, similarity metrics
## Search Integrations
### Wikipedia
- **Location**: `third_party/Wikipedia/wikipedia-search-cookbook.ipynb`
- **Use Case**: Augment Claude with Wikipedia knowledge
- **Key Concepts**: API integration, knowledge retrieval
### Web Pages
- **Location**: `misc/read_web_pages_with_haiku.ipynb`
- **Use Case**: Extract and analyze web page content
- **Key Concepts**: Web scraping, content extraction
## LlamaIndex
- **Location**: `third_party/LlamaIndex/`
- **Use Case**: Advanced document indexing and retrieval
- **Key Concepts**: Index creation, query engines, document loaders
## Deepgram
- **Location**: `third_party/Deepgram/`
- **Use Case**: Audio transcription integration
- **Key Concepts**: Speech-to-text, audio processing
```
### scripts/memory_tool.py
```python
"""
Production-ready memory tool handler for Claude's memory_20250818 tool.
This implementation provides secure, client-side execution of memory operations
with path validation, error handling, and comprehensive security measures.
"""
import shutil
from pathlib import Path
from typing import Any
class MemoryToolHandler:
"""
Handles execution of Claude's memory tool commands.
The memory tool enables Claude to read, write, and manage files in a memory
system through a standardized tool interface. This handler provides client-side
implementation with security controls.
Attributes:
base_path: Root directory for memory storage
memory_root: The /memories directory within base_path
"""
def __init__(self, base_path: str = "./memory_storage"):
"""
Initialize the memory tool handler.
Args:
base_path: Root directory for all memory operations
"""
self.base_path = Path(base_path).resolve()
self.memory_root = self.base_path / "memories"
self.memory_root.mkdir(parents=True, exist_ok=True)
def _validate_path(self, path: str) -> Path:
"""
Validate and resolve memory paths to prevent directory traversal attacks.
Args:
path: The path to validate (must start with /memories)
Returns:
Resolved absolute Path object within memory_root
Raises:
ValueError: If path is invalid or attempts to escape memory directory
"""
if not path.startswith("/memories"):
raise ValueError(
f"Path must start with /memories, got: {path}. "
"All memory operations must be confined to the /memories directory."
)
# Remove /memories prefix and any leading slashes
relative_path = path[len("/memories") :].lstrip("/")
# Resolve to absolute path within memory_root
if relative_path:
full_path = (self.memory_root / relative_path).resolve()
else:
full_path = self.memory_root.resolve()
# Verify the resolved path is still within memory_root
try:
full_path.relative_to(self.memory_root.resolve())
except ValueError as e:
raise ValueError(
f"Path '{path}' would escape /memories directory. "
"Directory traversal attempts are not allowed."
) from e
return full_path
def execute(self, **params: Any) -> dict[str, str]:
"""
Execute a memory tool command.
Args:
**params: Command parameters from Claude's tool use
Returns:
Dict with either 'success' or 'error' key
Supported commands:
- view: Show directory contents or file contents
- create: Create or overwrite a file
- str_replace: Replace text in a file
- insert: Insert text at a specific line
- delete: Delete a file or directory
- rename: Rename or move a file/directory
"""
command = params.get("command")
try:
if command == "view":
return self._view(params)
elif command == "create":
return self._create(params)
elif command == "str_replace":
return self._str_replace(params)
elif command == "insert":
return self._insert(params)
elif command == "delete":
return self._delete(params)
elif command == "rename":
return self._rename(params)
else:
return {
"error": f"Unknown command: '{command}'. "
"Valid commands are: view, create, str_replace, insert, delete, rename"
}
except ValueError as e:
return {"error": str(e)}
except Exception as e:
return {"error": f"Unexpected error executing {command}: {e}"}
def _view(self, params: dict[str, Any]) -> dict[str, str]:
"""View directory contents or file contents."""
path = params.get("path")
view_range = params.get("view_range")
if not path:
return {"error": "Missing required parameter: path"}
full_path = self._validate_path(path)
# Handle directory listing
if full_path.is_dir():
try:
items = []
for item in sorted(full_path.iterdir()):
if item.name.startswith("."):
continue
items.append(f"{item.name}/" if item.is_dir() else item.name)
if not items:
return {"success": f"Directory: {path}\n(empty)"}
return {
"success": f"Directory: {path}\n" + "\n".join([f"- {item}" for item in items])
}
except Exception as e:
return {"error": f"Cannot read directory {path}: {e}"}
# Handle file reading
elif full_path.is_file():
try:
content = full_path.read_text(encoding="utf-8")
lines = content.splitlines()
# Apply view range if specified
if view_range:
start_line = max(1, view_range[0]) - 1 # Convert to 0-indexed
end_line = len(lines) if view_range[1] == -1 else view_range[1]
lines = lines[start_line:end_line]
start_num = start_line + 1
else:
start_num = 1
# Format with line numbers
numbered_lines = [f"{i + start_num:4d}: {line}" for i, line in enumerate(lines)]
return {"success": "\n".join(numbered_lines)}
except UnicodeDecodeError:
return {"error": f"Cannot read {path}: File is not valid UTF-8 text"}
except Exception as e:
return {"error": f"Cannot read file {path}: {e}"}
else:
return {"error": f"Path not found: {path}"}
def _create(self, params: dict[str, Any]) -> dict[str, str]:
"""Create or overwrite a file."""
path = params.get("path")
file_text = params.get("file_text", "")
if not path:
return {"error": "Missing required parameter: path"}
full_path = self._validate_path(path)
# Don't allow creating directories directly
if not path.endswith((".txt", ".md", ".json", ".py", ".yaml", ".yml")):
return {
"error": f"Cannot create {path}: Only text files are supported. "
"Use file extensions: .txt, .md, .json, .py, .yaml, .yml"
}
try:
# Create parent directories if needed
full_path.parent.mkdir(parents=True, exist_ok=True)
# Write the file
full_path.write_text(file_text, encoding="utf-8")
return {"success": f"File created successfully at {path}"}
except Exception as e:
return {"error": f"Cannot create file {path}: {e}"}
def _str_replace(self, params: dict[str, Any]) -> dict[str, str]:
"""Replace text in a file."""
path = params.get("path")
old_str = params.get("old_str")
new_str = params.get("new_str", "")
if not path or old_str is None:
return {"error": "Missing required parameters: path, old_str"}
full_path = self._validate_path(path)
if not full_path.is_file():
return {"error": f"File not found: {path}"}
try:
content = full_path.read_text(encoding="utf-8")
# Check if old_str exists
count = content.count(old_str)
if count == 0:
return {
"error": f"String not found in {path}. The exact text must exist in the file."
}
elif count > 1:
return {
"error": f"String appears {count} times in {path}. "
"The string must be unique. Use more specific context."
}
# Perform replacement
new_content = content.replace(old_str, new_str, 1)
full_path.write_text(new_content, encoding="utf-8")
return {"success": f"File {path} has been edited successfully"}
except Exception as e:
return {"error": f"Cannot edit file {path}: {e}"}
def _insert(self, params: dict[str, Any]) -> dict[str, str]:
"""Insert text at a specific line."""
path = params.get("path")
insert_line = params.get("insert_line")
insert_text = params.get("insert_text", "")
if not path or insert_line is None:
return {"error": "Missing required parameters: path, insert_line"}
full_path = self._validate_path(path)
if not full_path.is_file():
return {"error": f"File not found: {path}"}
try:
lines = full_path.read_text(encoding="utf-8").splitlines()
# Validate insert_line
if insert_line < 0 or insert_line > len(lines):
return {
"error": f"Invalid insert_line {insert_line}. "
f"Must be between 0 and {len(lines)}"
}
# Insert the text
lines.insert(insert_line, insert_text.rstrip("\n"))
# Write back
full_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
return {"success": f"Text inserted at line {insert_line} in {path}"}
except Exception as e:
return {"error": f"Cannot insert into {path}: {e}"}
def _delete(self, params: dict[str, Any]) -> dict[str, str]:
"""Delete a file or directory."""
path = params.get("path")
if not path:
return {"error": "Missing required parameter: path"}
# Prevent deletion of root memories directory
if path == "/memories":
return {"error": "Cannot delete the /memories directory itself"}
full_path = self._validate_path(path)
# Verify the path is within /memories to prevent accidental deletion outside the memory directory
# This provides an additional safety check beyond _validate_path
try:
full_path.relative_to(self.memory_root.resolve())
except ValueError:
return {
"error": f"Invalid operation: Path '{path}' is not within /memories directory. "
"Only paths within /memories can be deleted."
}
if not full_path.exists():
return {"error": f"Path not found: {path}"}
try:
if full_path.is_file():
full_path.unlink()
return {"success": f"File deleted: {path}"}
elif full_path.is_dir():
shutil.rmtree(full_path)
return {"success": f"Directory deleted: {path}"}
except Exception as e:
return {"error": f"Cannot delete {path}: {e}"}
def _rename(self, params: dict[str, Any]) -> dict[str, str]:
"""Rename or move a file/directory."""
old_path = params.get("old_path")
new_path = params.get("new_path")
if not old_path or not new_path:
return {"error": "Missing required parameters: old_path, new_path"}
old_full_path = self._validate_path(old_path)
new_full_path = self._validate_path(new_path)
if not old_full_path.exists():
return {"error": f"Source path not found: {old_path}"}
if new_full_path.exists():
return {
"error": f"Destination already exists: {new_path}. "
"Cannot overwrite existing files/directories."
}
try:
# Create parent directories if needed
new_full_path.parent.mkdir(parents=True, exist_ok=True)
# Perform rename/move
old_full_path.rename(new_full_path)
return {"success": f"Renamed {old_path} to {new_path}"}
except Exception as e:
return {"error": f"Cannot rename {old_path} to {new_path}: {e}"}
def clear_all_memory(self) -> dict[str, str]:
"""
Clear all memory files (useful for testing or starting fresh).
⚠️ WARNING: This method is for demonstration and testing purposes only.
In production, you should carefully consider whether you need to delete
all memory files, as this will permanently remove all learned patterns
and stored knowledge. Consider using selective deletion instead.
Returns:
Dict with success message
"""
try:
if self.memory_root.exists():
shutil.rmtree(self.memory_root)
self.memory_root.mkdir(parents=True, exist_ok=True)
return {"success": "All memory cleared successfully"}
except Exception as e:
return {"error": f"Cannot clear memory: {e}"}
```