エージェント ワークフローから構造化された検証済みの JSON を取得します。Agent SDK は JSON スキーマを通じて構造化出力をサポートしており、エージェントが必要な形式で正確にデータを返すことを保証します。
構造化出力を使用する場合
エージェントがツール(ファイル検索、コマンド実行、ウェブ検索など)を使用した複数ターンのワークフローを完了した後に検証済みの JSON が必要な場合は、構造化出力を使用します。
ツール使用なしの単一の API 呼び出しについては、API 構造化出力を参照してください。
構造化出力は、アプリケーションとの信頼性の高い、型安全な統合を提供します。
JSON スキーマを定義する
エージェントが返すべき構造を説明する JSON スキーマを作成します。スキーマは標準的な JSON スキーマ形式を使用します。
outputFormat パラメータを追加する
クエリオプションに outputFormat パラメータを含め、type: "json_schema" とスキーマ定義を指定します。
クエリを実行する
エージェントはタスクを完了するために必要なツール(ファイル操作、コマンド、ウェブ検索など)を使用します。
検証済み出力にアクセスする
エージェントの最終結果は、スキーマに一致する有効な JSON となり、message.structured_output で利用可能になります。
Agent SDK は、API 構造化出力と同じ JSON スキーマ機能と制限をサポートしています。
主にサポートされている機能:
enum、const、required、additionalProperties(false である必要があります)date-time、date、email、uri、uuid など$ref、$def、および definitionsサポートされている機能、制限、および正規表現パターンサポートの完全な詳細については、API ドキュメントの JSON スキーマの制限を参照してください。
コードから 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')
}
}
}