Loading...
    • 開發者指南
    • API 參考
    • MCP
    • 資源
    • 發行說明
    Search...
    ⌘K
    入門
    Claude 簡介快速開始
    模型與定價
    模型概覽選擇模型Claude 4.6 新功能遷移指南模型棄用定價
    使用 Claude 構建
    功能概覽使用 Messages API處理停止原因提示最佳實踐
    模型能力
    延伸思考自適應思考思考力度快速模式(研究預覽)結構化輸出引用串流訊息批次處理PDF 支援搜尋結果多語言支援嵌入視覺
    工具
    概覽如何實作工具使用網頁搜尋工具網頁擷取工具程式碼執行工具記憶工具Bash 工具電腦使用工具文字編輯器工具
    工具基礎設施
    工具搜尋程式化工具呼叫細粒度工具串流
    上下文管理
    上下文視窗壓縮上下文編輯提示快取Token 計數
    檔案與資源
    Files API
    Agent 技能
    概覽快速開始最佳實踐企業技能透過 API 使用技能
    Agent SDK
    概覽快速開始TypeScript SDKTypeScript V2(預覽)Python SDK遷移指南
    串流輸入即時串流回應處理停止原因處理權限使用者核准與輸入使用 Hook 控制執行工作階段管理檔案檢查點SDK 中的結構化輸出託管 Agent SDK安全部署 AI 代理修改系統提示SDK 中的 MCP自訂工具SDK 中的子代理SDK 中的斜線命令SDK 中的 Agent 技能追蹤成本與用量待辦清單SDK 中的外掛
    API 中的 MCP
    MCP 連接器遠端 MCP 伺服器
    第三方平台上的 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    提示工程
    概覽提示產生器使用提示範本提示改進器清晰直接使用範例(多範例提示)讓 Claude 思考(CoT)使用 XML 標籤賦予 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
    指南

    從代理程式取得結構化輸出

    使用 JSON Schema、Zod 或 Pydantic 從代理程式工作流程中回傳經過驗證的 JSON。在多輪工具使用後取得型別安全的結構化資料。

    結構化輸出讓您定義從代理程式回傳的資料的確切形狀。代理程式可以使用任何需要的工具來完成任務,而您最終仍然能取得符合您 schema 的經過驗證的 JSON。定義一個 JSON Schema 來描述您需要的結構,SDK 會保證輸出與之匹配。

    若要獲得完整的型別安全性,請使用 Zod(TypeScript)或 Pydantic(Python)來定義您的 schema,並取得強型別的物件。

    為什麼要使用結構化輸出?

    代理程式預設回傳自由格式的文字,這對聊天來說沒問題,但當您需要以程式化方式使用輸出時就不適用了。結構化輸出為您提供型別化的資料,可以直接傳遞給您的應用程式邏輯、資料庫或 UI 元件。

    考慮一個食譜應用程式,其中代理程式搜尋網路並帶回食譜。沒有結構化輸出時,您會得到需要自行解析的自由格式文字。有了結構化輸出,您定義想要的形狀,就能取得可以直接在應用程式中使用的型別化資料。

    快速開始

    要使用結構化輸出,請定義一個 JSON Schema 來描述您想要的資料形狀,然後透過 outputFormat 選項(TypeScript)或 output_format 選項(Python)將其傳遞給 query()。當代理程式完成時,結果訊息會包含一個 structured_output 欄位,其中包含符合您 schema 的經過驗證的資料。

    以下範例要求代理程式研究 Anthropic 並以結構化輸出回傳公司名稱、成立年份和總部位置。

    import { query } from '@anthropic-ai/claude-agent-sdk'
    
    // 定義您想要回傳的資料形狀
    const schema = {
      type: 'object',
      properties: {
        company_name: { type: 'string' },
        founded_year: { type: 'number' },
        headquarters: { type: 'string' }
      },
      required: ['company_name']
    }
    
    for await (const message of query({
      prompt: 'Research Anthropic and provide key company information',
      options: {
        outputFormat: {
          type: 'json_schema',
          schema: schema
        }
      }
    })) {
      // 結果訊息包含帶有經過驗證資料的 structured_output
      if (message.type === 'result' && message.structured_output) {
        console.log(message.structured_output)
        // { company_name: "Anthropic", founded_year: 2021, headquarters: "San Francisco, CA" }
      }
    }

    使用 Zod 和 Pydantic 的型別安全 schema

    您可以使用 Zod(TypeScript)或 Pydantic(Python)來定義您的 schema,而不是手動撰寫 JSON Schema。這些函式庫會為您生成 JSON Schema,並讓您將回應解析為完全型別化的物件,可以在整個程式碼庫中使用自動完成和型別檢查。

    以下範例定義了一個功能實作計畫的 schema,包含摘要、步驟列表(每個步驟都有複雜度等級)和潛在風險。代理程式規劃功能並回傳一個型別化的 FeaturePlan 物件。然後您可以存取 plan.summary 等屬性,並以完整的型別安全性遍歷 plan.steps。

    import { z } from 'zod'
    import { query } from '@anthropic-ai/claude-agent-sdk'
    
    // 使用 Zod 定義 schema
    const FeaturePlan = z.object({
      feature_name: z.string(),
      summary: z.string(),
      steps: z.array(z.object({
        step_number: z.number(),
        description: z.string(),
        estimated_complexity: z.enum(['low', 'medium', 'high'])
      })),
      risks: z.array(z.string())
    })
    
    type FeaturePlan = z.infer<typeof FeaturePlan>
    
    // 轉換為 JSON Schema
    const schema = z.toJSONSchema(FeaturePlan)
    
    // 在查詢中使用
    for await (const message of query({
      prompt: 'Plan how to add dark mode support to a React app. Break it into implementation steps.',
      options: {
        outputFormat: {
          type: 'json_schema',
          schema: schema
        }
      }
    })) {
      if (message.type === 'result' && message.structured_output) {
        // 驗證並取得完全型別化的結果
        const parsed = FeaturePlan.safeParse(message.structured_output)
        if (parsed.success) {
          const plan: FeaturePlan = parsed.data
          console.log(`Feature: ${plan.feature_name}`)
          console.log(`Summary: ${plan.summary}`)
          plan.steps.forEach(step => {
            console.log(`${step.step_number}. [${step.estimated_complexity}] ${step.description}`)
          })
        }
      }
    }

    優點:

    • 完整的型別推斷(TypeScript)和型別提示(Python)
    • 使用 safeParse() 或 model_validate() 進行執行時驗證
    • 更好的錯誤訊息
    • 可組合、可重複使用的 schema

    輸出格式設定

    outputFormat(TypeScript)或 output_format(Python)選項接受一個包含以下內容的物件:

    • type:設定為 "json_schema" 以使用結構化輸出
    • schema:定義您輸出結構的 JSON Schema 物件。您可以使用 z.toJSONSchema() 從 Zod schema 生成,或使用 .model_json_schema() 從 Pydantic 模型生成

    SDK 支援標準 JSON Schema 功能,包括所有基本型別(object、array、string、number、boolean、null)、enum、const、required、巢狀物件和 $ref 定義。有關支援功能和限制的完整列表,請參閱 JSON Schema 限制。

    範例:TODO 追蹤代理程式

    此範例展示了結構化輸出如何與多步驟工具使用配合運作。代理程式需要在程式碼庫中找到 TODO 註解,然後查詢每個註解的 git blame 資訊。它自主決定使用哪些工具(Grep 進行搜尋、Bash 執行 git 命令),並將結果合併為單一的結構化回應。

    此 schema 包含可選欄位(author 和 date),因為 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 this codebase 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}`)
          }
        })
      }
    }

    錯誤處理

    當代理程式無法產生符合您 schema 的有效 JSON 時,結構化輸出生成可能會失敗。這通常發生在 schema 對於任務來說過於複雜、任務本身模糊不清,或代理程式在嘗試修復驗證錯誤時達到重試上限時。

    當發生錯誤時,結果訊息會有一個 subtype 指示出了什麼問題:

    Subtype含義
    success輸出已成功生成並驗證
    error_max_structured_output_retries代理程式在多次嘗試後仍無法產生有效輸出

    以下範例檢查 subtype 欄位以確定輸出是否成功生成,或者您是否需要處理失敗情況:

    for await (const msg of query({
      prompt: 'Extract contact info from the document',
      options: {
        outputFormat: {
          type: 'json_schema',
          schema: contactSchema
        }
      }
    })) {
      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')
        }
      }
    }

    避免錯誤的技巧:

    • 保持 schema 簡潔。 深度巢狀且有許多必填欄位的 schema 更難滿足。從簡單開始,根據需要增加複雜度。
    • 將 schema 與任務匹配。 如果任務可能沒有您 schema 所需的所有資訊,請將那些欄位設為可選。
    • 使用清晰的提示。 模糊的提示會讓代理程式更難知道要產生什麼輸出。

    相關資源

    • JSON Schema 文件:學習 JSON Schema 語法,用於定義包含巢狀物件、陣列、列舉和驗證約束的複雜 schema
    • API 結構化輸出:直接使用 Claude API 的結構化輸出,用於不需要工具使用的單輪請求
    • 自訂工具:為您的代理程式提供自訂工具,在回傳結構化輸出之前於執行期間呼叫

    Was this page helpful?

    • 使用 Zod 和 Pydantic 的型別安全 schema
    • 範例:TODO 追蹤代理程式