Loading...
    0
    • 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 resultsStructured outputsGoogle 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 ManagementStructured outputs in the SDKHosting 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 BedrockMicrosoft FoundryVertex 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

    Structured outputs in the SDK

    Get validated JSON results from agent workflows

    Get structured, validated JSON from agent workflows. The Agent SDK supports structured outputs through JSON Schemas, ensuring your agents return data in exactly the format you need.

    When to use structured outputs

    Use structured outputs when you need validated JSON after an agent completes a multi-turn workflow with tools (file searches, command execution, web research, etc.).

    For single API calls without tool use, see API Structured Outputs.

    Why use structured outputs

    Structured outputs provide reliable, type-safe integration with your applications:

    • Validated structure: Always receive valid JSON matching your schema
    • Simplified integration: No parsing or validation code needed
    • Type safety: Use with TypeScript or Python type hints for end-to-end safety
    • Clean separation: Define output requirements separately from task instructions
    • Tool autonomy: Agent chooses which tools to use while guaranteeing output format

    How structured outputs work

    1. 1

      Define your JSON schema

      Create a JSON Schema that describes the structure you want the agent to return. The schema uses standard JSON Schema format.

    2. 2

      Add the outputFormat parameter

      Include the outputFormat parameter in your query options with type: "json_schema" and your schema definition.

    3. 3

      Run your query

      The agent uses any tools it needs to complete the task (file operations, commands, web search, etc.).

    4. 4

      Access validated output

      The agent's final result will be valid JSON matching your schema, available in message.structured_output.

    Supported JSON Schema features

    The Agent SDK supports the same JSON Schema features and limitations as API Structured Outputs.

    Key supported features:

    • All basic types: object, array, string, integer, number, boolean, null
    • enum, const, required, additionalProperties (must be false)
    • String formats: date-time, date, email, uri, uuid, etc.
    • $ref, $def, and definitions

    For complete details on supported features, limitations, and regex pattern support, see JSON Schema limitations in the API documentation.

    Example: TODO tracking agent

    Here's a complete example showing an agent that searches code for TODOs and extracts git blame information:

    import { query } from '@anthropic-ai/claude-agent-sdk'
    
    // Define structure for TODO extraction
    const todoSchema = {
      type: 'object',
      properties: {
        todos: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              text: { type: 'string' },
              file: { type: 'string' },
              line: { type: 'number' },
              author: { type: 'string' },
              date: { type: 'string' }
            },
            required: ['text', 'file', 'line']
          }
        },
        total_count: { type: 'number' }
      },
      required: ['todos', 'total_count']
    }
    
    // Agent uses Grep to find TODOs, Bash to get git blame info
    for await (const message of query({
      prompt: 'Find all TODO comments in src/ and identify who added them',
      options: {
        outputFormat: {
          type: 'json_schema',
          schema: todoSchema
        }
      }
    })) {
      if (message.type === 'result' && message.structured_output) {
        const data = message.structured_output
        console.log(`Found ${data.total_count} TODOs`)
        data.todos.forEach(todo => {
          console.log(`${todo.file}:${todo.line} - ${todo.text}`)
          if (todo.author) {
            console.log(`  Added by ${todo.author} on ${todo.date}`)
          }
        })
      }
    }

    The agent autonomously uses the right tools (Grep, Bash) to gather information and returns validated data.

    Error handling

    If the agent cannot produce valid output matching your schema, you'll receive an error result:

    for await (const msg of query({
      prompt: 'Analyze the data',
      options: {
        outputFormat: {
          type: 'json_schema',
          schema: mySchema
        }
      }
    })) {
      if (msg.type === 'result') {
        if (msg.subtype === 'success' && msg.structured_output) {
          console.log(msg.structured_output)
        } else if (msg.subtype === 'error_max_structured_output_retries') {
          console.error('Could not produce valid output')
        }
      }
    }

    Related resources

    • JSON Schema documentation
    • API Structured Outputs - For single API calls
    • Custom tools - Define tools for your agents
    • TypeScript SDK reference - Full TypeScript API
    • Python SDK reference - Full Python API
    • Why use structured outputs
    • Quick start
    • Defining schemas with Zod
    • Quick start
    • Defining schemas with Pydantic
    • How structured outputs work
    • Supported JSON Schema features
    • Example: TODO tracking agent
    • Error handling
    • Related resources

    Solutions

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

    Partners

    • Amazon Bedrock
    • Google Cloud's Vertex AI

    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

    Learn

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

    Help and security

    • Availability
    • Status
    • Support
    • Discord

    Terms and policies

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