Claude Quickstarts Reference Implementations

repository·main·Indexed 12 days ago

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

A collection of starter projects and reference implementations for integrating Claude's capabilities. Includes an Autonomous Coding Agent demo utilizing a two-agent pattern with the Claude Code CLI and Claude Agent SDK, a containerized Browser Automation demo using Playwright for DOM-aware web interaction, and best practices for computer use on macOS (v0.1.0).

Tokens
57K
Snippets
164
Records
236
Agent score
97%

What's inside Claude Quickstarts

  1. Overview of Claude Managed Agents Quickstarts

    main
    Claude Managed Agents are agents run by Anthropic that provide server-side sessions, sandboxed tools, and an event stream for your application to consume. This repository contains several complete, runnable quickstart projects that demonstrate how to pair Managed Agents with different product surfaces and UI frameworks.
  2. Overview of Claude Financial Data Analyst features

    main

    The Claude Financial Data Analyst is a Next.js application designed to analyze financial data through chat-based interaction.

    Key Capabilities:

    • Intelligent Analysis: Uses Claude 3 Haiku and Claude 3.5 Sonnet to process data.
    • Multi-Format File Support:
      • Text/Code files (.txt, .md, .html, .py, .csv, etc.)
      • PDF documents (text-based PDFs; scanned documents are not supported)
      • Images
    • Interactive Data Visualization: Automatically generates charts using Recharts based on analyzed data, including:
      • Line Charts (trends/time series)
      • Bar Charts (metric comparisons)
      • Multi-Bar Charts
      • Area Charts & Stacked Area Charts
      • Pie Charts (distribution analysis)
  3. Available Claude Quickstart Projects

    main

    This repository contains several specialized quickstart implementations. Choose a project based on your target use case:

    • Customer Support Agent: Demonstrates natural language understanding and generation with access to a knowledge base.
    • Financial Data Analyst: Demonstrates interactive data visualization and financial data analysis via chat.
    • Computer Use Demo: Provides an environment and tools for Claude to control a desktop computer (supports computer_use_20251124 tool version with zoom actions).
    • Computer Use Best Practices: A native-macOS reference implementation (run in a VM!) demonstrating reliable patterns like explicit tool definitions, image pruning, prompt caching, and trajectory recording.
    • Browser Use Demo: A reference implementation for browser automation using a Playwright-backed browser tool to navigate, inspect DOM, and fill forms.
    • Autonomous Coding Agent: Uses the Claude Agent SDK to demonstrate a two-agent pattern (initializer + coding agent) for building applications with git-persisted progress.
    • Managed Agents: Chat SDK: Pairs Claude Managed Agents with Vercel's Chat SDK for browser-based chat, research analysis, and multi-platform support (Slack, Teams, etc.).
    • Managed Agents with CopilotKit and AG-UI: Demonstrates bridging managed-agent sessions to the AG-UI protocol and rendering tool calls as interactive generative UI components.
    • Managed Agents: Knowledge Wiki: Demonstrates distilling a document corpus into a versioned memory-store knowledge wiki for efficient, provenance-backed querying.
  4. Project File Structure and Core Components

    main

    This project integrates assistant-ui with Claude Managed Agents. The following files represent the core logic and architecture:

    • Configuration & Provisioning:
      • setup/agent-config.ts: Defines the model, system prompt, tools (e.g., always_ask, show_chart), and environment.
      • setup/create-agent.ts: Handles one-time provisioning of the agent and its environment.
    • Managed Agents Logic:
      • lib/managed-agents/reducer.ts: Converts the event log into messages.
      • lib/managed-agents/session-controller.ts: Manages per-session replay, live tail, sending/confirming/interrupting, and batched approvals.
      • lib/managed-agents/session-list-adapter.ts: Provides the RemoteThreadListAdapter for the sidebar.
      • lib/managed-agents/runtime-provider.tsx: Provides useRemoteThreadListRuntime and per-session useExternalStoreRuntime.
      • lib/managed-agents/attachments.ts: Handles Composer attachments via Files API upload and sandbox mounting.
    • API & UI:
      • app/api/sessions/**: Route handlers for list, create, replay, tail, messages, confirm, files, and interrupt.
      • components/tool-uis/: Contains tool cards and the approval bar.
      • app/assistant.tsx: The main composed view containing the Sidebar, thread, toolkit, and suggestions.
    • Security & Setup:
      • lib/owned-session.ts: Implements the session ownership gate for routes.
      • skill.md: Contains setup walkthroughs, debugging, and gotchas.
  5. Project Layout and Module Overview

    main

    The computer-use-best-practices repository is organized into the following key components:

    Core Logic (computer_use/)

    • __main__.py: CLI entrypoint, handles build_tools() and build_system_prompt().
    • loop.py: Manages the streaming sampling loop, retries, and advisor/compaction wiring.
    • trajectory.py: Manages on-disk transcripts, images, and per-run scratch directories.
    • tools/: Contains the tool implementations:
      • base.py: Defines Tool ABC and ToolCollection.
      • computer.py: Uses pyautogui for screen control (includes zoom and key aliasing).
      • browser.py: Uses playwright with headless Chromium.
      • shell.py: Provides a sandboxed bash and python environment with output caps.
      • editor.py: Allows viewing, creating, string replacement, and insertion within the scratch directory.

    Configuration and UI

    • constants.py: Contains the Config dataclass, cfg instance, prompts, and derived sets.
    • config.example.toml: A template for overriding CU_CONFIG.
    • dev_ui/: Contains developer tools like the trajectory_viewer (Streamlit) and tool_panel (FastAPI).
  6. Use hosted vs. explicit computer tools

    main

    By default, this implementation defines tools (name, description, JSON schema) explicitly in computer_use/tools/computer.py. This allows you to edit exactly what the model sees but lacks Anthropic's built-in safety classifier coverage.

    To enable Anthropic's computer-use-specific safety classifiers (including prompt-injection detection on screenshots), you must use the hosted tool by setting:

    • cfg.use_hosted_computer_tool = True
    • OR CU_USE_HOSTED_COMPUTER_TOOL=true (via env var).

    When using the hosted tool, the server supplies the tool's description and schema, while other tools like browser, bash, and computer_batch remain as explicit tools.

  7. How the Two-Agent Pattern works

    main

    The demo implements a long-running autonomous coding workflow using two distinct agent roles:

    1. Initializer Agent (Session 1):

      • Reads app_spec.txt.
      • Creates feature_list.json containing test cases (e.g., 200 cases).
      • Sets up the project structure and initializes a git repository.
    2. Coding Agent (Sessions 2+):

      • Picks up from the state left by the Initializer.
      • Implements features one by one.
      • Marks features as passing in feature_list.json as they are completed.

    Session Management

    • Persistence: Progress is saved via feature_list.json and git commits.
    • Resuming: If you press Ctrl+C to pause, you can resume by running the same command again. The agent auto-continues between sessions with a 3-second delay.
    • Context: Each session runs with a fresh context window.
  8. Mental model: How Chat SDK and Managed Agents relate

    main

    In this architecture, the conversation ID used by the Chat SDK is identical to the Managed Agents session ID.

    • Session Creation: The page creates a session via POST /api/sessions (calling sessions.create()) and passes the returned ID to useChat as the threadId.
    • Storage: The Managed Agents API acts as the entire conversation store.
      • Sidebar lists sessions via sessions.list({ agent_id }).
      • Replaying a chat uses sessions.events.list() to turn user.message and agent.message events back into chat bubbles.
      • The first message of a conversation is used as the title via sessions.update().
    • Data Persistence: The server is stateless regarding Chat SDK internals. createMemoryState() in src/bot.ts handles message dedup and locks, but persistMessageHistory: false ensures the adapter doesn't cache message bodies, leaving the live transcript in the browser and the durable transcript in the Managed Agents session.
  9. Manage context with image pruning and prompt caching

    main

    To manage the high token cost of screenshot-heavy trajectories, the project uses two primary mechanisms:

    Prompt Caching

    loop.py applies cache_control: {"type": "ephemeral"} breakpoints to the system prompt and the final tool-result block of the most recent user turn. This allows subsequent calls to serve the prefix from cache, reducing latency and cost.

    Image Pruning Strategies

    Because prompt caching requires a byte-identical prefix, naive pruning (like keeping only the last N images) causes cache misses every turn. The project provides three strategies via cfg.image_prune_strategy:

    • "interval" (Default): Keeps the image count stable for cfg.image_prune_interval turns. This ensures the prefix remains identical, allowing the cache to hit consistently. This is recommended for long, visual tasks.
    • "none": Disables pruning. Best for short, screenshot-light tasks where the cost of re-processing a few extra images is lower than the cost of a cache invalidation.
    • "simple": Keeps the last N images. This is "cache-hostile" because the prefix changes every turn.

    Pruning vs. Autocompaction (Summarization)

    • Summarization (enable_autocompaction): A server-side event that condenses the conversation into a summary. It is more expensive (extra API turn) and causes a cold cache, but preserves more textual information.
    • Pruning: Faster and cheaper in the short term. It is most effective when it prevents the conversation from hitting the autocompaction_trigger_tokens threshold.
  10. How assistant-ui and Claude Managed Agents work together

    main

    This project pairs a frontend UI framework with a backend agent runtime:

    • assistant-ui (Frontend): Provides the UI primitives including the composer, thread, sidebar, tool cards, and the approval gate. It expects a message array and callbacks to drive the interface.
    • Claude Managed Agents (Backend): Provides a durable session that holds transcripts, runs code (like bash with pandas) in a sandbox, and streams events back to the UI.

    The Integration Layer:

    • lib/managed-agents/reducer.ts is the core logic. It is a pure function that transforms a session's event log into assistant-ui's ThreadMessageLike[] model. This ensures that live streams and historical replays render identically.
    • State Management: There is no separate database; the Managed Agents session itself acts as the source of truth for all conversation history and state.
  11. Security Model and Command Allowlist

    main

    The demo employs a defense-in-depth security model to restrict agent actions. Commands are validated against an allowlist in security.py.

    Security Layers

    1. OS-level Sandbox: Bash commands run in an isolated environment.
    2. Filesystem Restrictions: File operations are restricted strictly to the designated project directory.
    3. Bash Allowlist: Only specific command categories are permitted:
      • File inspection: ls, cat, head, tail, wc, grep
      • Node.js: npm, node
      • Version control: git
      • Process management: ps, lsof, sleep, pkill (for dev processes only)

    Any command not in this allowlist is blocked by the security hook. To add new permitted commands, modify the ALLOWED_COMMANDS list in security.py.

  12. How the Knowledge Wiki pipeline works

    main

    The Knowledge Wiki pattern avoids the 'reading tax' of re-reading a document corpus for every agent query by consolidating a corpus into a single, structured memory store once.

    The Pipeline Steps

    1. Assemble Corpus: Gather documents (data rooms, discovery sets, etc.).
    2. Normalize: Convert all file types (PDF, Word, etc.) to plain text with a [SOURCE: …] header for provenance.
    3. Parallel Extraction: Split the corpus into batches. Run concurrent agent sessions that write structured notes into a shared memory store (the wiki). Each source document should have its own single-writer path to prevent overwrites.
    4. Resolve Open Questions: A cross-reading pass to close gaps left by extraction. Mark missing info as confirmed-unresolvable instead of guessing.
    5. Consolidate (Dreaming): A server-side 'sleep-time' compute pass that reads transcripts and the store to write a new, reorganized store with deduplicated entities, an index, and repaired links. This step uses the POST /v1/dreams endpoint.
    6. Query: Attach the consolidated store read-only to fresh agent sessions. Require provenance for every fact and script specific 'miss' behavior (e.g., naming the missing document).
    7. Operate: Periodically run 'dreaming' over real usage transcripts to reorganize the wiki around actual user queries.
    8. Evaluate: Grade outputs against a rubric to tune extraction rules and prompts.