에이전트 워크플로우에서 구조화되고 검증된 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 정보를 추출하는 에이전트를 보여주는 완전한 예제입니다:
에이전트는 자율적으로 올바른 도구(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}`)
}
})
}
}