Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
從代理工作流程獲取結構化、驗證的 JSON。Agent SDK 通過 JSON Schemas 支持結構化輸出,確保您的代理以您需要的確切格式返回數據。
何時使用結構化輸出
當您需要在代理完成包含工具的多輪工作流程(文件搜索、命令執行、網絡研究等)後獲得驗證的 JSON 時,請使用結構化輸出。
對於沒有工具使用的單個 API 調用,請參閱 API 結構化輸出。
結構化輸出為您的應用程序提供可靠的、類型安全的集成:
定義您的 JSON 架構
創建一個 JSON Schema,描述您希望代理返回的結構。該架構使用標準 JSON Schema 格式。
添加 outputFormat 參數
在您的查詢選項中包含 outputFormat 參數,其中 type: "json_schema" 和您的架構定義。
運行您的查詢
代理使用完成任務所需的任何工具(文件操作、命令、網絡搜索等)。
訪問驗證的輸出
代理的最終結果將是與您的架構匹配的有效 JSON,可在 message.structured_output 中獲得。
Agent SDK 支持與 API 結構化輸出 相同的 JSON Schema 功能和限制。
關鍵支持的功能:
enum、const、required、additionalProperties(必須為 false)date-time、date、email、uri、uuid 等$ref、$def 和 definitions有關支持的功能、限制和正則表達式模式支持的完整詳細信息,請參閱 API 文檔中的 JSON Schema 限制。
以下是一個完整示例,展示了一個搜索代碼中的 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')
}
}
}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}`)
}
})
}
}