Loading...
    0
    • 開發者指南
    • API 參考
    • MCP
    • 資源
    • 發行說明
    Search...
    ⌘K
    第一步
    Claude 介紹快速入門
    模型與定價
    模型概覽選擇模型Claude 4.5 的新功能遷移到 Claude 4.5模型棄用定價
    使用 Claude 建構
    功能概覽使用 Messages API上下文視窗提示詞最佳實踐
    功能
    提示詞快取上下文編輯延伸思考串流訊息批次處理引用多語言支援Token 計數嵌入向量視覺PDF 支援Files API搜尋結果結構化輸出Google Sheets 附加元件
    工具
    概述如何實現工具使用代幣高效工具使用細粒度工具串流Bash 工具代碼執行工具電腦使用工具文字編輯工具網頁擷取工具網路搜尋工具記憶工具
    代理技能
    概述在 API 中開始使用 Agent Skills技能編寫最佳實踐使用 Agent Skills 與 API
    Agent SDK
    概述Agent SDK 參考 - TypeScriptPython SDK
    指南
    串流輸入處理權限會話管理SDK 中的結構化輸出託管 Agent SDK修改系統提示SDK 中的 MCP自訂工具SDK 中的子代理SDK 中的斜線命令SDK 中的代理技能追蹤成本和使用量待辦事項清單SDK 中的外掛程式
    API 中的 MCP
    MCP 連接器遠端 MCP 伺服器
    Claude 在第三方平台上
    Amazon BedrockMicrosoft FoundryVertex AI
    提示詞工程
    概述提示詞生成器使用提示模板提示詞改進器保持清晰和直接使用範例(多樣提示)讓 Claude 思考(思維鏈)使用 XML 標籤給 Claude 分配角色(系統提示詞)預填 Claude 的回應串接複雜提示長文本技巧延伸思考技巧
    測試與評估
    定義成功標準開發測試案例使用評估工具降低延遲
    加強防護措施
    減少幻覺提高輸出一致性防範越獄handle-streaming-refusals減少提示詞洩漏保持 Claude 的角色特性
    管理和監控
    Admin API 概述使用量和成本 APIClaude Code 分析 API
    Console
    指南

    SDK 中的結構化輸出

    從代理工作流程獲取驗證的 JSON 結果

    從代理工作流程獲取結構化、驗證的 JSON。Agent SDK 通過 JSON Schemas 支持結構化輸出,確保您的代理以您需要的確切格式返回數據。

    何時使用結構化輸出

    當您需要在代理完成包含工具的多輪工作流程(文件搜索、命令執行、網絡研究等)後獲得驗證的 JSON 時,請使用結構化輸出。

    對於沒有工具使用的單個 API 調用,請參閱 API 結構化輸出。

    為什麼使用結構化輸出

    結構化輸出為您的應用程序提供可靠的、類型安全的集成:

    • 驗證的結構:始終接收與您的架構匹配的有效 JSON
    • 簡化的集成:無需解析或驗證代碼
    • 類型安全:與 TypeScript 或 Python 類型提示一起使用以實現端到端安全
    • 清晰的分離:將輸出要求與任務指令分開定義
    • 工具自主性:代理選擇使用哪些工具,同時保證輸出格式

    結構化輸出如何工作

    1. 1

      定義您的 JSON 架構

      創建一個 JSON Schema,描述您希望代理返回的結構。該架構使用標準 JSON Schema 格式。

    2. 2

      添加 outputFormat 參數

      在您的查詢選項中包含 outputFormat 參數,其中 type: "json_schema" 和您的架構定義。

    3. 3

      運行您的查詢

      代理使用完成任務所需的任何工具(文件操作、命令、網絡搜索等)。

    4. 4

      訪問驗證的輸出

      代理的最終結果將是與您的架構匹配的有效 JSON,可在 message.structured_output 中獲得。

    支持的 JSON Schema 功能

    Agent SDK 支持與 API 結構化輸出 相同的 JSON Schema 功能和限制。

    關鍵支持的功能:

    • 所有基本類型:object、array、string、integer、number、boolean、null
    • enum、const、required、additionalProperties(必須為 false)
    • 字符串格式:date-time、date、email、uri、uuid 等
    • $ref、$def 和 definitions

    有關支持的功能、限制和正則表達式模式支持的完整詳細信息,請參閱 API 文檔中的 JSON Schema 限制。

    示例:TODO 跟蹤代理

    以下是一個完整示例,展示了一個搜索代碼中的 TODO 並提取 git blame 信息的代理:

    import { query } from '@anthropic-ai/claude-agent-sdk'
    
    // 定義 TODO 提取的結構
    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']
    }
    
    // 代理使用 Grep 查找 TODO,使用 Bash 獲取 git blame 信息
    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}`)
          }
        })
      }
    }

    代理自主使用正確的工具(Grep、Bash)來收集信息並返回驗證的數據。

    錯誤處理

    如果代理無法生成與您的架構匹配的有效輸出,您將收到錯誤結果:

    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')
        }
      }
    }

    相關資源

    • JSON Schema 文檔
    • API 結構化輸出 - 用於單個 API 調用
    • 自定義工具 - 為您的代理定義工具
    • TypeScript SDK 參考 - 完整的 TypeScript API
    • Python SDK 參考 - 完整的 Python API
    • 使用 Zod 定義架構
    • 使用 Pydantic 定義架構
    • 支持的 JSON Schema 功能
    • 示例:TODO 跟蹤代理

    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