結構化輸出讓您定義從代理程式回傳的資料的確切形狀。代理程式可以使用任何需要的工具來完成任務,而您最終仍然能取得符合您 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(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}`)
})
}
}
}優點:
safeParse() 或 model_validate() 進行執行時驗證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 註解,然後查詢每個註解的 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')
}
}
}避免錯誤的技巧:
Was this page helpful?