Anthropic Claude Cookbooks

repository·main·Indexed 32 days ago

https://github.com/anthropics/claude-cookbooks

A collection of notebooks and guides demonstrating advanced AI patterns with Claude, including RAG with contextual embeddings, Knowledge Graph construction, classification, summarization, Text-to-SQL, and autonomous SRE agents using the Claude Agent SDK and Model Context Protocol (MCP).

Tokens
225.4K
Snippets
374
Records
648
Agent score
98%

What's inside anthropic-claude-cookbooks

  1. Overview of Self-Hosted Sandbox variants

    main

    Self-hosted sandboxes allow you to run Claude Managed Agent sessions against compute environments you control. Each implementation follows a standard contract:

    1. Listen for the session.status_run_started webhook (verified using client.beta.webhooks.unwrap()).
    2. Drain the environment work queue to recover missed items.
    3. Launch a per-session sandbox that executes the SDK/CLI tool runner (supporting bash, read, write, edit, glob, and grep), heartbeats the lease, and posts tool_results back to the session.

    Security Note: The runner does not receive the organization API key. Instead, it authenticates using the environment key, which is the single credential used for both the control plane and per-session calls.

  2. Explore Building Effective Agents patterns

    main

    The Building Effective Agents Cookbook provides minimal reference implementations for common agentic workflows described in Anthropic research. These patterns are implemented as interactive Jupyter notebooks (.ipynb) that serve as both implementation examples and evaluation environments.

    Basic Building Blocks

    • Prompt Chaining: Sequencing LLM calls where the output of one step is the input to the next.
    • Routing: Using an LLM to direct a task to a specific specialized workflow or tool.
    • Multi-LLM Parallelization: Running multiple LLM calls simultaneously to improve speed or coverage.

    Advanced Workflows

    • Orchestrator-Subagents: A central agent that decomposes tasks and delegates them to specialized subagents.
    • Evaluator-Optimizer: A loop where one agent generates an output and another agent evaluates it, providing feedback to improve the result.
    • Async Multi-Agent Orchestration: Managing multiple agents running concurrently using asynchronous patterns.
  3. Explore Summarization capabilities with Claude

    main

    The Summarization capability demonstrates how to use Claude to summarize and synthesize information from multiple sources using various techniques. The implementation and evaluation are provided via a Jupyter notebook and evaluation scripts.

    To explore this capability, use the following components:

    • guide.ipynb: The main tutorial notebook containing the implementation.
    • data/: Contains data files used for examples and testing.
    • evaluation/: Contains evaluation scripts using Promptfoo to measure summarization performance.

    For detailed instructions on how to run evaluations, refer to the evaluation/README.md file within this directory.

  4. Understand the Slack × Claude Managed Agent architecture

    main

    The integration uses a webhook-driven architecture where the routing state is maintained entirely within the CMA (Claude Managed Agent) session metadata (specifically slack_channel and slack_thread_ts).

    Workflow Flow:

    1. Slack @mention: Sends an event to /slack/events.
    2. Session Creation: The server calls sessions.create including the routing metadata and returns a 200 to Slack.
    3. Agent Execution: Claude runs on Anthropic infrastructure until the session reaches an idle status.
    4. Webhook Trigger: Once idle, the session.status_idled event triggers the /cma-webhook.
    5. Response: The server calls sessions.retrieve, reads the metadata, and uses chat.postMessage to reply to the original Slack thread.
  5. Explore Retrieval Augmented Generation (RAG) capabilities

    main

    The RAG capability directory provides resources to learn how to enhance Claude's capabilities with domain-specific knowledge. The directory contains:

    • guide.ipynb: The main tutorial notebook for implementing RAG patterns.
    • data/: Data files used for examples and testing.
    • evaluation/: Scripts and configurations for evaluating RAG performance using Promptfoo.

    To learn how to evaluate your RAG implementation, refer to the instructions in evaluation/README.md.

  6. Core concepts of the Claude Agent SDK

    main

    The Claude Agent SDK provides a framework for building sophisticated agentic systems. Key interfaces and patterns include:

    • ClaudeSDKClient & ClaudeAgentOptions: Core Python SDK interfaces for configuring and interacting with the agent.
    • query(): The primary method used for executing agent loops and handling async iteration.
    • Tool Usage: Supports basic tools (e.g., WebSearch, Read) and advanced integration via the Model Context Protocol (MCP).
    • Multi-agent Orchestration: Ability to coordinate specialized subagents.
    • Hooks: Enterprise-grade features for compliance tracking, audit trails, and safety (e.g., PreToolUse hooks to validate write operations).
  7. Understand the Gate Expense Approver example data

    main

    The gate directory contains example data used to demonstrate a Human-in-the-Loop (HITL) expense approval agent implemented in CMA_gate_human_in_the_loop.py.

    Components

    • policy.yaml: Defines the rules for expense approval.
    • inbox/receipts.jsonl: A dataset of twelve receipts designed to test all logic branches of the policy.

    Agent Logic

    The agent classifies receipts using two custom tools:

    1. decide(): Used for clear-cut approvals or rejections.
    2. escalate(): Used for ambiguous cases requiring human intervention.

    Test Coverage

    The provided receipts are engineered to trigger various outcomes:

    • Auto-approvals: Cleanly meeting all policy criteria.
    • Rejections: e.g., missing a required receipt image.
    • Escalations:
      • Items in the manager-approval band.
      • Items exceeding the spending threshold.
      • Specific categories (e.g., travel charges) that always require escalation.
      • Ambiguous categories.
  8. Use CMA as an MCP server

    main

    The Claude Managed Agent (CMA) can be run as a Model Context Protocol (MCP) server to expose Managed Agents session primitives as tools. There are two primary entrypoints depending on your client:

    • Claude Desktop: Use the stdio entrypoint (src/server.ts).
    • claude.ai web (via Connector): Use the Streamable HTTP entrypoint (src/server-http.ts).

    Both entrypoints provide access to the same set of tools for managing agents, sessions, events, and environments.

  9. Explore Claude Capabilities guides

    main

    The capabilities/ directory contains a collection of in-depth guides for implementing specific AI patterns where Claude excels. Each guide is self-contained and includes the necessary code, data, and evaluation scripts to reproduce experiments.

    Available capability guides include:

    • Classification: Handling complex business rules and limited training data using RAG and prompt engineering.
    • Retrieval Augmented Generation (RAG): Building RAG systems from scratch, including optimization techniques like summary indexing and re-ranking.
    • RAG with Contextual Embeddings: Improving retrieval precision by adding relevant context to document chunks before embedding.
    • Summarization: Techniques for multi-shot, domain-based, and chunking-based summarization of long-form or multi-document content.
    • Text-to-SQL: Generating complex SQL queries from natural language using self-improvement and RAG, with evaluations for syntax and correctness.
    • Knowledge Graph Construction: End-to-end construction (NER, relation extraction, entity resolution, and multi-hop querying) using structured outputs and Claude-driven deduplication.
  10. Understand the MongoDB on Claude Managed Agents boilerplate

    main

    This package provides the supporting modules for the Fraud Review Agent with MongoDB Atlas and Claude Managed Agents cookbook. While the core logic (retrieval pipelines, tool handlers, and the requires_action loop) is implemented within the notebook, this package contains the necessary imports to run that logic.

    Module Overview

    • config.py: Contains configuration tunables, index names, and a MongoDB server-version check for supports_rank_fusion.
    • embeddings.py: Provides an embedding and rerank client that adapts the MongoDB Atlas AI endpoint to the voyageai interface, allowing for provider-agnostic implementation.
    • tools.py: Handles MongoDB Atlas setup, including seeding collections, creating vector and Atlas Search indexes, waiting for index synchronization, and providing shared decision/audit document shapers.
    • ap2_mandates.py: Implements Agent Payments Protocol (AP2) mandate signing and verification using ES256 JWTs. The notebook interacts with this via verify_mandates.
    • seed.py: Loads plaintext fixture data from ../example_data/mongodb_on_cma/seed_transactions.jsonl.

    Security Note

    The MongoDB credential (MONGO_URI) is kept secure by only running in host-side handlers via pymongo. It is never exposed to the agent context or its sandbox.

  11. Understand the Road Trip Planner streaming architecture

    main

    The Road Trip Planner uses a Server-Sent Events (SSE) architecture to stream agent activity to the browser.

    Key components include:

    • /api/stream endpoint: A thin, authenticated proxy of the session's SSE tail. The browser manages reconnections, and every new connection re-fetches the event log first to ensure the UI renders the full history.
    • accumulateManagedAgentsEvent (SDK): A client-side function that folds event_start and event_delta previews into a single agent.message snapshot. This ensures that even if a user joins mid-generation, the UI renders a coherent message without jumping.
    • Status Signals: The stream provides real-time status updates:
      • thinking starts: Drives the activity line.
      • span.model_request_*: Drives working state and token statistics.
      • agent.thread_message_sent: Updates the activity line (e.g., "waiting on Plan reviewer...").
      • session.error: Distinguishes between a retry in progress and a dead turn.
    • Interrupting: The user.interrupt verb is used to stop an agent. This is triggered via a POST request, causing the agent to wind down until session.status_idle is received.
  12. Explore Claude Cookbook recipes

    main

    The cookbook is organized into several functional categories to help you implement specific AI capabilities:

    Core Capabilities

    • Classification: Techniques for text and data classification.
    • Retrieval Augmented Generation (RAG): Enhancing responses with external knowledge.
    • Summarization: Effective text summarization techniques.

    Tool Use and Integration

    • Tool Use: Integrating Claude with external tools and functions (e.g., Customer service agents, Calculators, SQL queries).
    • Third-Party Integrations: Using external data sources like Pinecone (Vector databases), Wikipedia, or reading Web pages.
    • Embeddings: Creating embeddings using Voyage AI.

    Multimodal Capabilities

    • Vision: Working with images, interpreting charts/graphs, and extracting content from forms.
    • Image Generation: Using Claude in conjunction with Stable Diffusion to generate illustrated responses.

    Advanced Techniques

    • Sub-agents: Using smaller models (like Haiku) as sub-agents for larger models (like Opus).
    • PDF Processing: Parsing and passing PDF content as text.
    • Automated Evaluations: Using Claude to automate prompt evaluation.
    • JSON Mode: Ensuring consistent JSON output.
    • Moderation: Creating content moderation filters.
    • Prompt Caching: Implementing efficient prompt caching techniques.