Claude Agent SDK Demos

repository·main·Indexed 25 days ago

https://github.com/anthropics/claude-agent-sdk-demos

A collection of demonstration applications showcasing the capabilities of the Claude Agent SDK. Includes examples such as an Email Agent with IMAP integration, an Electron-based Excel Demo for spreadsheet analysis using the xlsx skill, HTML previews for the AskUserQuestion tool, and V2 Session API examples covering multi-turn conversations and session persistence.

Tokens
27.5K
Snippets
64
Records
138
Agent score
83%

What's inside claude-agent-sdk-demos

  1. Overview of Available Demos

    main

    This repository contains several demonstration applications for the Claude Agent SDK:

    • Email Agent: An IMAP email assistant for inbox display, agentic search, and AI assistance.
    • Excel Demo: Demonstrates working with spreadsheets and Excel files.
    • Hello World: A basic getting-started example for the SDK.
    • Hello World V2: Demonstrates the V2 Session API (unstable_v2_*) using separate send()/stream() methods and session persistence.
    • Research Agent: A multi-agent system that breaks research into subtopics, spawns parallel researchers, and synthesizes reports.
    • AskUserQuestion Previews: A branding assistant demonstrating previewFormat: "html" and WebSocket-based HTML previews for tool options.
    • Simple Chat App: A React + Express chat UI demonstrating full conversation loops over WebSocket with streaming.
    • Resume Generator: Generates .docx resumes by web-searching for individuals.

    ⚠️ IMPORTANT: These are demo applications intended for local development only. Do NOT deploy them to production or use them at scale.

  2. Understand the Multi-Agent Workflow and Roles

    main

    The system coordinates several specialized agents to complete a research task:

    1. Lead Agent: Uses the Task tool to coordinate research and delegate to subagents.
    2. Researcher: Uses WebSearch and Write tools to gather information from the web.
    3. Data Analyst: Uses Glob, Read, Bash, and Write tools to extract metrics and generate charts.
    4. Report Writer: Uses Skill, Write, Glob, Read, and Bash tools to create final PDF reports with embedded visuals.
  3. Security Warning for Email Agent Demo

    main

    ⚠️ IMPORTANT: This application is intended for local development only. It should NOT be deployed to production or used at scale because:

    • It stores email credentials in plain text environment variables.
    • It lacks authentication and multi-user support.
    • It does not meet production security standards.
  4. Install and run the Excel Demo application

    main

    The Excel Demo is an Electron-based desktop application that demonstrates AI-powered spreadsheet creation and analysis using the Claude Agent SDK.

    Prerequisites

    • Node.js 18+ or Bun
    • An Anthropic API key
    • Python 3.9+ (required for the Python agent examples)
    • LibreOffice (optional, for formula recalculation)

    Installation Steps

    1. Clone the repository and navigate to the demo directory:
    git clone https://github.com/anthropics/sdk-demos.git
    cd sdk-demos/excel-demo
    1. Install dependencies using npm or bun:
    npm install
    # or
    bun install
    1. Configure your Anthropic API key by setting the ANTHROPIC_API_KEY environment variable. If not set, the application will prompt you on the first run.
    2. Start the application:
    npm start
    # or
    bun start
    git clone https://github.com/anthropics/sdk-demos.git
    cd sdk-demos/excel-demo
    npm install
    npm start
  5. Implement Email Listeners with Recursive AI Spawning

    main

    Email Listeners are TypeScript files that respond to email events. They follow a recursive pattern where your TypeScript code manages control flow and email operations, while delegating nuanced decision-making (like categorization or extraction) to Claude subagents using context.callAgent().

    The Recursive Pattern:

    1. Write Code: Create a listener in TypeScript.
    2. Spawn AI: Your listener calls context.callAgent().
    3. Receive Structured Data: The AI returns a schema-validated response.
    4. Execute Logic: Your code uses the AI output to perform email actions (e.g., adding labels, archiving).
    // agent/custom_scripts/listeners/finance-email-labeler.ts
    export async function handler(email: Email, context: ListenerContext) {
      // ... logic ...
    
      // AI-powered analysis
      const analysis = await context.callAgent({
        prompt: `Analyze this email and determine if it's finance-related: ...`,
        schema: {
          type: "object",
          properties: {
            isFinance: { type: "boolean" },
            category: { type: "string", enum: ["invoice", "payment", "statement"] },
            confidence: { type: "number" }
          }
        }
      });
    
      if (analysis.isFinance && analysis.confidence > 0.8) {
        await context.addLabel(email.messageId, "Finance");
        await context.addLabel(email.messageId, analysis.category);
      }
    }
  6. Use Slash Commands in the Research Agent

    main

    The system supports specific slash commands to trigger specialized research workflows:

    CommandDescription
    /research <topic>Start focused research on any topic
    /competitive-analysis <company>Analyze companies or products
    /market-trends <industry>Research industry trends
    /fact-check <claim>Verify claims and statements
    /summarizeSummarize all current research findings
  7. Understand the Action Lifecycle

    main

    Actions follow a four-step lifecycle:

    1. Creation: The agent identifies a need and generates an ActionInstance (including params and a label) within its chat response.
    2. Rendering: The frontend receives the instance via WebSocket and renders interactive buttons.
    3. Triggering: The user clicks a button, sending an execute_action request containing the instanceId and sessionId to the server.
    4. Execution: The backend loads the template, creates an ActionContext, runs the handler, logs the result to .logs/actions/, and injects the ActionResult back into the chat session.
  8. Best practices for designing Actions

    main

    Follow these principles when developing actions for the Agent SDK:

    • User-Specific Templates: Tailor templates to specific workflows (e.g., send-payment-reminder-to-acme instead of a generic send-email).
    • Descriptive Naming: Use a verb-noun-context format (e.g., forward-bugs-to-engineering).
    • Specific Instances: Ensure the agent creates instances with highly specific labels and descriptions.
    • Parameter Validation: Always validate parameters against the schema before execution.
    • Error Messages: Provide clear, actionable error messages.
    • Logging: Log all executions for audit trails and debugging.
    • Idempotency: Design handlers to be idempotent whenever possible.
    • Resource Cleanup: Periodically prune old action instances.
    • Testing: Test handlers thoroughly with edge cases and real user data.
    • Documentation: Clearly document parameter schemas with examples.
  9. Run the Accounting Email Listener

    main

    To start the listener, activate your virtual environment and run the main script. On the first run, a browser window will open for Gmail authentication. Once authorized, a token.pickle file will be created for future use.

    source venv/bin/activate
    python accounting_email_listener.py
    # Activate virtual environment
    source venv/bin/activate
    
    # Run the listener
    python accounting_email_listener.py
  10. Setup and run Python Excel agent examples

    main

    The agent/ directory contains Python scripts for generating complex spreadsheet structures like workout and budget trackers.

    Setup Python Environment

    Navigate to the agent directory, create a virtual environment, and install the required dependencies:

    cd agent
    python -m venv .venv
    source .venv/bin/activate  # On Windows: .venv\Scripts\activate
    pip install -r requirements.txt

    Run Example Scripts

    Once the environment is active, you can run the following scripts:

    • Workout Tracker: Creates a fitness log with automatic summary statistics and multiple sheets.
    • Budget Tracker: Creates financial tracking with formulas and data validation.
    # Create a workout tracker
    python create_workout_tracker.py
    
    # Create a budget tracker
    python create_budget_tracker.py
    cd agent
    python -m venv .venv
    source .venv/bin/activate
    pip install -r requirements.txt
    python create_workout_tracker.py
  11. Run the Resume Generator

    main

    To generate a professional 1-page resume for a specific person, install the dependencies and run the start command followed by the person's name as a command-line argument. The agent will use web search to research their professional background (LinkedIn, company pages, news, GitHub) and produce a .docx file.

    npm install
    npm start "Person Name"