Loading...
    • 開發者指南
    • API 參考
    • MCP
    • 資源
    • 發行說明
    Search...
    ⌘K
    開始使用
    Claude 簡介快速開始
    模型與定價
    模型概覽選擇模型Claude 4.5 新功能遷移至 Claude 4.5模型棄用定價
    使用 Claude 構建
    功能概覽使用 Messages API上下文窗口提示詞最佳實踐
    功能
    提示詞快取上下文編輯擴展思考努力串流消息批次處理引用多語言支援Token 計數嵌入視覺PDF 支援Files API搜尋結果結構化輸出
    工具
    概覽如何實現工具使用細粒度工具串流Bash 工具代碼執行工具程式化工具調用計算機使用工具文字編輯器工具網頁擷取工具網頁搜尋工具記憶體工具工具搜尋工具
    Agent Skills
    概覽快速開始最佳實踐使用 API 的 Skills
    Agent SDK
    概覽快速開始TypeScript SDKTypeScript V2 (預覽)Python SDK遷移指南
    串流輸入處理權限使用鉤子控制執行會話管理檔案檢查點SDK 中的結構化輸出託管 Agent SDK安全部署 AI agents修改系統提示詞SDK 中的 MCP自訂工具SDK 中的子 agentsSDK 中的斜線命令SDK 中的 Agent Skills追蹤成本和使用量待辦事項清單SDK 中的外掛程式
    API 中的 MCP
    MCP 連接器遠端 MCP 伺服器
    第三方平台上的 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    提示詞工程
    概覽提示詞生成器使用提示詞範本提示詞改進器清晰直接使用範例 (多次提示)讓 Claude 思考 (CoT)使用 XML 標籤給 Claude 一個角色 (系統提示詞)預填 Claude 的回應鏈接複雜提示詞長上下文提示擴展思考提示
    測試與評估
    定義成功標準開發測試案例使用評估工具降低延遲
    加強防護欄
    減少幻覺增加輸出一致性緩解越獄串流拒絕減少提示詞洩露保持 Claude 的角色
    管理和監控
    Admin API 概覽使用量和成本 APIClaude Code Analytics API
    Console
    Log in
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...
    Loading...

    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
    指南

    SDK 中的結構化輸出

    從代理工作流程獲取驗證的 JSON 結果
    • 使用 Zod 定義架構
    • 使用 Pydantic 定義架構
    • 支持的 JSON Schema 功能
    • 示例:TODO 跟蹤代理

    從代理工作流程獲取結構化、驗證的 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 信息的代理:

    代理自主使用正確的工具(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
    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}`)
          }
        })
      }
    }