Loading...
    • Developer Guide
    • API Reference
    • MCP
    • Resources
    • Release Notes
    Search...
    ⌘K

    First steps

    Intro to ClaudeQuickstart

    Models & pricing

    Models overviewChoosing a modelWhat's new in Claude 4.5Migrating to Claude 4.5Model deprecationsPricing

    Build with Claude

    Features overviewUsing the Messages APIContext windowsPrompting best practices

    Capabilities

    Prompt cachingContext editingExtended thinkingStreaming MessagesBatch processingCitationsMultilingual supportToken countingEmbeddingsVisionPDF supportFiles APISearch resultsGoogle Sheets add-on

    Tools

    OverviewHow to implement tool useToken-efficient tool useFine-grained tool streamingBash toolCode execution toolComputer use toolText editor toolWeb fetch toolWeb search toolMemory tool

    Agent Skills

    OverviewQuickstartBest practicesUsing Skills with the API

    Agent SDK

    OverviewTypeScript SDKPython SDK

    Guides

    Streaming InputHandling PermissionsSession ManagementHosting the Agent SDKModifying system promptsMCP in the SDKCustom ToolsSubagents in the SDKSlash Commands in the SDKAgent Skills in the SDKTracking Costs and UsageTodo ListsPlugins in the SDK

    MCP in the API

    MCP connectorRemote MCP servers

    Claude on 3rd-party platforms

    Amazon BedrockVertex AI

    Prompt engineering

    OverviewPrompt generatorUse prompt templatesPrompt improverBe clear and directUse examples (multishot prompting)Let Claude think (CoT)Use XML tagsGive Claude a role (system prompts)Prefill Claude's responseChain complex promptsLong context tipsExtended thinking tips

    Test & evaluate

    Define success criteriaDevelop test casesUsing the Evaluation ToolReducing latency

    Strengthen guardrails

    Reduce hallucinationsIncrease output consistencyMitigate jailbreaksStreaming refusalsReduce prompt leakKeep Claude in character

    Administration and monitoring

    Admin API overviewUsage and Cost APIClaude Code Analytics API
    Console
    Guides

    Streaming Input

    Understanding the two input modes for Claude Agent SDK and when to use each

    Overview

    The Claude Agent SDK supports two distinct input modes for interacting with agents:

    • Streaming Input Mode (Default & Recommended) - A persistent, interactive session
    • Single Message Input - One-shot queries that use session state and resuming

    This guide explains the differences, benefits, and use cases for each mode to help you choose the right approach for your application.

    Streaming Input Mode (Recommended)

    Streaming input mode is the preferred way to use the Claude Agent SDK. It provides full access to the agent's capabilities and enables rich, interactive experiences.

    It allows the agent to operate as a long lived process that takes in user input, handles interruptions, surfaces permission requests, and handles session management.

    How It Works

    %%{init: {"theme": "base", "themeVariables": {"edgeLabelBackground": "#F0F0EB", "lineColor": "#91918D", "primaryColor": "#F0F0EB", "primaryTextColor": "#191919", "primaryBorderColor": "#D9D8D5", "secondaryColor": "#F5E6D8", "tertiaryColor": "#CC785C", "noteBkgColor": "#FAF0E6", "noteBorderColor": "#91918D"}, "sequence": {"actorMargin": 50, "width": 150, "height": 65, "boxMargin": 10, "boxTextMargin": 5, "noteMargin": 10, "messageMargin": 35}}}%%
    sequenceDiagram
        participant App as Your Application
        participant Agent as Claude Agent
        participant Tools as Tools/Hooks
        participant FS as Environment/<br/>File System
        
        App->>Agent: Initialize with AsyncGenerator
        activate Agent
        
        App->>Agent: Yield Message 1
        Agent->>Tools: Execute tools
        Tools->>FS: Read files
        FS-->>Tools: File contents
        Tools->>FS: Write/Edit files
        FS-->>Tools: Success/Error
        Agent-->>App: Stream partial response
        Agent-->>App: Stream more content...
        Agent->>App: Complete Message 1
        
        App->>Agent: Yield Message 2 + Image
        Agent->>Tools: Process image & execute
        Tools->>FS: Access filesystem
        FS-->>Tools: Operation results
        Agent-->>App: Stream response 2
        
        App->>Agent: Queue Message 3
        App->>Agent: Interrupt/Cancel
        Agent->>App: Handle interruption
        
        Note over App,Agent: Session stays alive
        Note over Tools,FS: Persistent file system<br/>state maintained
        
        deactivate Agent

    Benefits

    Image Uploads

    Attach images directly to messages for visual analysis and understanding

    Queued Messages

    Send multiple messages that process sequentially, with ability to interrupt

    Tool Integration

    Full access to all tools and custom MCP servers during the session

    Hooks Support

    Use lifecycle hooks to customize behavior at various points

    Real-time Feedback

    See responses as they're generated, not just final results

    Context Persistence

    Maintain conversation context across multiple turns naturally

    Implementation Example

    import { query } from "@anthropic-ai/claude-agent-sdk";
    import { readFileSync } from "fs";
    
    async function* generateMessages() {
      // First message
      yield {
        type: "user" as const,
        message: {
          role: "user" as const,
          content: "Analyze this codebase for security issues"
        }
      };
      
      // Wait for conditions or user input
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // Follow-up with image
      yield {
        type: "user" as const,
        message: {
          role: "user" as const,
          content: [
            {
              type: "text",
              text: "Review this architecture diagram"
            },
            {
              type: "image",
              source: {
                type: "base64",
                media_type: "image/png",
                data: readFileSync("diagram.png", "base64")
              }
            }
          ]
        }
      };
    }
    
    // Process streaming responses
    for await (const message of query({
      prompt: generateMessages(),
      options: {
        maxTurns: 10,
        allowedTools: ["Read", "Grep"]
      }
    })) {
      if (message.type === "result") {
        console.log(message.result);
      }
    }

    Single Message Input

    Single message input is simpler but more limited.

    When to Use Single Message Input

    Use single message input when:

    • You need a one-shot response
    • You do not need image attachments, hooks, etc.
    • You need to operate in a stateless environment, such as a lambda function

    Limitations

    Single message input mode does not support:

    • Direct image attachments in messages
    • Dynamic message queueing
    • Real-time interruption
    • Hook integration
    • Natural multi-turn conversations

    Implementation Example

    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    // Simple one-shot query
    for await (const message of query({
      prompt: "Explain the authentication flow",
      options: {
        maxTurns: 1,
        allowedTools: ["Read", "Grep"]
      }
    })) {
      if (message.type === "result") {
        console.log(message.result);
      }
    }
    
    // Continue conversation with session management
    for await (const message of query({
      prompt: "Now explain the authorization process",
      options: {
        continue: true,
        maxTurns: 1
      }
    })) {
      if (message.type === "result") {
        console.log(message.result);
      }
    }
    • Overview
    • Streaming Input Mode (Recommended)
    • How It Works
    • Benefits
    • Implementation Example
    • Single Message Input
    • When to Use Single Message Input
    • Limitations
    • Implementation Example
    © 2025 ANTHROPIC PBC

    Products

    • Claude
    • Claude Code
    • Max plan
    • Team plan
    • Enterprise plan
    • Download app
    • Pricing
    • Log in

    Features

    • Claude and Slack
    • Claude in Excel

    Models

    • Opus
    • Sonnet
    • Haiku

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Claude Developer Platform

    • Overview
    • Developer docs
    • Pricing
    • Amazon Bedrock
    • Google Cloud’s Vertex AI
    • Console login

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Help and security

    • Availability
    • Status
    • Support center

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy

    Products

    • Claude
    • Claude Code
    • Max plan
    • Team plan
    • Enterprise plan
    • Download app
    • Pricing
    • Log in

    Features

    • Claude and Slack
    • Claude in Excel

    Models

    • Opus
    • Sonnet
    • Haiku

    Solutions

    • AI agents
    • Code modernization
    • Coding
    • Customer support
    • Education
    • Financial services
    • Government
    • Life sciences

    Claude Developer Platform

    • Overview
    • Developer docs
    • Pricing
    • Amazon Bedrock
    • Google Cloud’s Vertex AI
    • Console login

    Learn

    • Blog
    • Catalog
    • Courses
    • Use cases
    • Connectors
    • Customer stories
    • Engineering at Anthropic
    • Events
    • Powered by Claude
    • Service partners
    • Startups program

    Company

    • Anthropic
    • Careers
    • Economic Futures
    • Research
    • News
    • Responsible Scaling Policy
    • Security and compliance
    • Transparency

    Help and security

    • Availability
    • Status
    • Support center

    Terms and policies

    • Privacy policy
    • Responsible disclosure policy
    • Terms of service: Commercial
    • Terms of service: Consumer
    • Usage policy
    © 2025 ANTHROPIC PBC