Structured Outputで型安全なAI開発
Structured Outputで型安全にLLMの出力を扱う方法を解説。
問題
LLMの出力はテキスト。パースが面倒で、型安全性がない。
Structured Outputとは
JSONスキーマを指定して、LLMに構造化データを出力させる機能。
実装例
const response = await anthropic.messages.create({
model: "claude-sonnet-4-6",
messages: [{ role: "user", content: "..." }],
tool_use: {
name: "extract_data",
input_schema: {
type: "object",
properties: {
title: { type: "string" },
score: { type: "number" },
tags: { type: "array", items: { type: "string" } }
},
required: ["title", "score"]
}
}
});
メリット
- パースエラーがなくなる
- TypeScriptの型と直接マッピングできる
- バリデーションが不要になる
まとめ
Structured Outputは「LLMをAPIとして使う」ための必須技術。