概要

Claude APIの構造化出力機能は、指定したJSONスキーマに完全に準拠したレスポンスを保証する強力な機能です。 従来のAI APIでは、レスポンスの形式が不整合だったり、必須フィールドが欠落したりする問題が頻発していましたが、構造化出力により確実で型安全なAPI応答を実現できます。 この機能により、下流システムとの連携が大幅に改善され、エラーハンドリングや再試行ロジックの複雑さを排除できます。

構造化出力は2つの独立した機能から構成されています。 JSON出力機能では、Claude の応答を指定したJSON形式に制約し、厳密ツール使用機能では、ツール呼び出し時のパラメータ検証を保証します。 これらは単独でも組み合わせても利用でき、用途に応じて柔軟に選択できます。

構造化出力の概要

構造化出力とは

構造化出力は、Claude の応答が事前定義されたスキーマに厳密に従うことを制約サンプリングによって保証する機能です。 この機能により、JSON.parse エラーの発生やフィールドの型不整合、必須プロパティの欠落といった従来の問題が完全に解決されます。 制約サンプリングにより、Claude は指定されたスキーマに適合する応答のみを生成するため、後続のシステムで安全に処理できます。

従来の方法では、プロンプトで「JSON形式で応答してください」と指示しても、構文エラーのあるJSONや不完全な構造が返される場合がありました。 構造化出力では、このような問題が技術的に発生しえないため、確実性の高いシステム構築が可能になります。

主要機能の種類

構造化出力機能は2つの独立した機能で構成されています。

JSON出力機能は、Claude の応答形式を制御し、指定したJSONスキーマに完全に適合するレスポンスを保証します。 この機能は、画像やテキストからのデータ抽出、構造化レポートの生成、API応答のフォーマット設定などの用途に適用できます。 output_format パラメータを使用して、Claude の直接的な応答内容を制約します。

厳密ツール使用機能は、ツール呼び出し時のパラメータ検証を保証し、関数が常に正しい型の引数を受け取ることを確実にします。 この機能は、エージェントワークフローの構築、型安全な関数呼び出し、複雑なツールでのネストされたプロパティ処理などに威力を発揮します。 各ツール定義で strict: true を設定することで、スキーマ準拠を強制できます。

対応モデルとベータ版について

構造化出力機能は、現在パブリックベータとして提供されており、以下のモデルで利用可能です。

対応モデルは、Claude Sonnet 4.5、Claude Opus 4.1、Claude Opus 4.5、Claude Haiku 4.5です。 これらのモデルでは、JSON出力と厳密ツール使用の両方の機能をフルサポートしています。 ベータ機能のため、継続的な改良が行われており、フィードバックに基づいて機能拡張が進められています。

この機能を利用するには、APIリクエストにベータヘッダー anthropic-beta: structured-outputs-2025-11-13 を含める必要があります。 このヘッダーにより、構造化出力機能が有効化され、JSONスキーマの制約や厳密ツール使用が適用されます。 ベータ期間中は機能改善が継続的に行われるため、最新の仕様については公式ドキュメントを定期的に確認することを推奨します。

JSON出力機能

JSON出力の基本概念

JSON出力機能は、Claude の応答をユーザー定義のJSONスキーマに厳密に適合させる機能です。 この機能により、従来の「JSONで返答してください」という曖昧な指示から、技術的に保証された構造化データ取得へと進化します。 制約サンプリング技術によって、指定されたスキーマに違反する応答は生成段階で排除されるため、100%の形式準拠が保証されます。

この機能は特に、下流システムでの自動処理が必要な場面で威力を発揮します。 例えば、顧客情報の抽出、商品データの分類、財務データの構造化などにおいて、手動でのデータ検証や例外処理が不要になります。 また、マイクロサービス間の通信や、フロントエンドでの動的UI生成においても、型安全性が保証されたデータを安心して利用できます。

クイックスタート

JSON出力機能の基本的な使用方法を、顧客情報抽出の例で説明します。 この例では、メールテキストから構造化された顧客データを抽出します。

python
import anthropic

# Claude APIクライアントを初期化
client = anthropic.Anthropic()

# JSON出力でメール情報を抽出
response = client.beta.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    betas=["structured-outputs-2025-11-13"],
    messages=[
        {
            "role": "user",
            "content": "以下のメール内容から重要情報を抽出してください:山田太郎(yamada@example.com)様より、エンタープライズプランに興味があり、来週火曜日の午後2時にデモの予約を希望するとの連絡をいただきました。"
        }
    ],
    output_format={
        "type": "json_schema",
        "schema": {
            "type": "object",
            "properties": {
                "name": {"type": "string", "description": "顧客名"},
                "email": {"type": "string", "description": "メールアドレス"},
                "plan_interest": {"type": "string", "description": "興味のあるプラン"},
                "demo_requested": {"type": "boolean", "description": "デモ希望の有無"},
                "preferred_time": {"type": "string", "description": "希望時間"}
            },
            "required": ["name", "email", "plan_interest", "demo_requested"],
            "additionalProperties": false
        }
    }
)

# 結果を表示
import json
result = json.loads(response.content[0].text)
print(json.dumps(result, ensure_ascii=False, indent=2))

このコードでは、メールテキストから顧客情報を構造化して抽出しています。 output_format パラメータで詳細なJSONスキーマを定義し、type: "json_schema" でJSON出力モードを指定しています。 required フィールドで必須項目を指定し、additionalProperties: false で定義されていないプロパティの追加を禁止しています。

実行すると、以下のような完璧に構造化されたJSONが返されます。

json
{
  "name": "山田太郎",
  "email": "yamada@example.com",
  "plan_interest": "エンタープライズプラン",
  "demo_requested": true,
  "preferred_time": "来週火曜日の午後2時"
}

このレスポンスは常にスキーマに準拠しており、パースエラーや型不整合は技術的に発生しません。 name、email、plan_interest、demo_requested は必須フィールドとして確実に含まれ、すべてのフィールドが指定された型で返されます。 この確実性により、下流システムでの例外処理が大幅に簡素化され、安定したアプリケーション構築が可能になります。

JSONスキーマの定義

効果的なJSON出力を実現するには、適切なJSONスキーマの設計が重要です。 構造化出力では標準的なJSON Schemaフォーマットを使用しますが、いくつかの制限があります。

基本的なスキーマ要素として、type、properties、required、additionalProperties が核となります。 type では object、array、string、integer、number、boolean、null の基本型を指定できます。 properties では各フィールドの詳細定義を行い、required で必須フィールドを明示し、additionalProperties: false で未定義プロパティを禁止します。

typescript
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY
});

// 複雑な商品データ抽出スキーマの定義
const productExtractionSchema = {
  type: "json_schema",
  schema: {
    type: "object",
    properties: {
      product_id: {
        type: "string",
        description: "商品ID"
      },
      name: {
        type: "string",
        description: "商品名"
      },
      price: {
        type: "number",
        description: "価格(税込)"
      },
      category: {
        type: "string",
        enum: ["electronics", "clothing", "food", "books", "other"],
        description: "商品カテゴリ"
      },
      tags: {
        type: "array",
        items: {
          type: "string"
        },
        description: "関連タグ一覧"
      },
      specifications: {
        type: "object",
        properties: {
          weight: { type: "number", description: "重量(kg)" },
          dimensions: {
            type: "object",
            properties: {
              width: { type: "number" },
              height: { type: "number" },
              depth: { type: "number" }
            },
            required: ["width", "height", "depth"],
            additionalProperties: false
          },
          color: { type: "string", description: "色" }
        },
        additionalProperties: false,
        description: "商品仕様"
      },
      availability: {
        type: "object",
        properties: {
          in_stock: { type: "boolean", description: "在庫の有無" },
          quantity: { type: "integer", description: "在庫数量" },
          estimated_restock_date: { type: "string", format: "date", description: "入荷予定日" }
        },
        required: ["in_stock"],
        additionalProperties: false,
        description: "在庫状況"
      }
    },
    required: ["product_id", "name", "price", "category"],
    additionalProperties: false
  }
};

// スキーマを使用した商品データ抽出
async function extractProductData(productDescription: string) {
  const response = await client.beta.messages.create({
    model: "claude-sonnet-4-5",
    max_tokens: 2048,
    betas: ["structured-outputs-2025-11-13"],
    messages: [
      {
        role: "user",
        content: `以下の商品説明から構造化データを抽出してください:\n\n${productDescription}`
      }
    ],
    output_format: productExtractionSchema
  });

  return JSON.parse(response.content[0].text);
}

// 使用例
const productText = `
新商品「ワイヤレスイヤホン XZ-100」が入荷しました。
価格は12,800円(税込)、エレクトロニクス製品です。
サイズは幅2.5cm、高さ1.8cm、奥行き3.2cm、重量は8.5gです。
カラーは黒、白、青の3色展開。
現在在庫あり(15個)、次回入荷は2024年3月15日予定です。
`;

extractProductData(productText)
  .then(result => {
    console.log('抽出された商品データ:', JSON.stringify(result, null, 2));
  })
  .catch(error => {
    console.error('エラー:', error);
  });

このコードでは、複雑な商品データを抽出するための包括的なスキーマを定義しています。 ネストしたオブジェクト(specifications、dimensions、availability)、配列(tags)、列挙型(category)、日付フォーマット(estimated_restock_date)など、多様なデータ型を適切に処理できます。 各オブジェクトレベルで additionalProperties: false を設定し、予期しないプロパティの混入を防いでいます。

実行すると、非構造化テキストから以下のような精密に構造化されたデータが抽出されます。

json
{
  "product_id": "XZ-100",
  "name": "ワイヤレスイヤホン XZ-100",
  "price": 12800,
  "category": "electronics",
  "tags": ["ワイヤレス", "イヤホン", "音楽"],
  "specifications": {
    "weight": 0.0085,
    "dimensions": {
      "width": 2.5,
      "height": 1.8,
      "depth": 3.2
    },
    "color": "黒、白、青"
  },
  "availability": {
    "in_stock": true,
    "quantity": 15,
    "estimated_restock_date": "2024-03-15"
  }
}

このスキーマ設計により、複雑な商品情報も確実に構造化でき、ECサイトのデータベース更新やAPI連携で直接活用できます。 型安全性が保証されているため、price は必ず数値型、in_stock は必ずブール型で返され、フロントエンドでの型チェックや計算処理が安全に実行できます。

SDK活用方法

PythonやTypeScriptの開発者向けに、より使いやすいSDKヘルパーが提供されています。 PydanticやZodなどの人気スキーマライブラリと統合することで、手書きJSONスキーマの作成を大幅に簡略化できます。

Pydanticを使用したPython実装

Pydanticモデルを直接使用することで、型安全性とコード可読性を両立できます。

python
from pydantic import BaseModel, Field
from typing import List, Optional
from datetime import date
from anthropic import Anthropic

class CustomerFeedback(BaseModel):
    customer_name: str = Field(description="顧客名")
    email: str = Field(description="メールアドレス")
    rating: int = Field(description="評価点数", ge=1, le=5)  # 1-5の範囲
    category: str = Field(description="フィードバックカテゴリ")
    sentiment: str = Field(description="感情分析結果", enum=["positive", "neutral", "negative"])
    issues: List[str] = Field(description="指摘された問題点", default=[])
    suggestions: List[str] = Field(description="改善提案", default=[])
    follow_up_required: bool = Field(description="フォローアップが必要か")
    priority_level: str = Field(description="優先度", enum=["low", "medium", "high"])
    contact_date: Optional[date] = Field(description="連絡希望日", default=None)

class FeedbackAnalyzer:
    def __init__(self, api_key: str):
        self.client = Anthropic(api_key=api_key)

    def analyze_feedback(self, feedback_text: str) -> CustomerFeedback:
        """顧客フィードバックを分析して構造化データを返す"""

        response = self.client.beta.messages.parse(
            model="claude-sonnet-4-5",
            max_tokens=1024,
            betas=["structured-outputs-2025-11-13"],
            messages=[
                {
                    "role": "user",
                    "content": f"""
以下の顧客フィードバックを分析し、構造化データとして抽出してください:

{feedback_text}

感情分析、問題点の特定、改善提案の抽出、優先度判定を行ってください。
                    """
                }
            ],
            output_format=CustomerFeedback,  # Pydanticモデルを直接指定
        )

        return response.parsed_output  # 自動的にPydanticモデルに変換される

# 使用例
analyzer = FeedbackAnalyzer(api_key="your-api-key")

feedback_text = """
田中と申します(tanaka@example.co.jp)。
先日購入した商品についてフィードバックします。
全体的には満足していますが(4点)、配送が予定より2日遅れたのが残念でした。
梱包は丁寧で良かったです。今後は配送スピードの改善をお願いします。
来週木曜日までに返事をいただけると助かります。
"""

try:
    result = analyzer.analyze_feedback(feedback_text)

    # Pydanticモデルとして扱える
    print(f"顧客名: {result.customer_name}")
    print(f"評価: {result.rating}/5")
    print(f"感情: {result.sentiment}")
    print(f"優先度: {result.priority_level}")
    print(f"フォローアップ必要: {result.follow_up_required}")

    if result.issues:
        print("指摘された問題点:")
        for issue in result.issues:
            print(f"  - {issue}")

    if result.suggestions:
        print("改善提案:")
        for suggestion in result.suggestions:
            print(f"  - {suggestion}")

except Exception as e:
    print(f"分析エラー: {e}")

このコードでは、Pydanticモデル CustomerFeedback を定義し、client.beta.messages.parse() メソッドで直接使用しています。 Field() でバリデーションルール(ge=1, le=5 で1-5の範囲制限、enum で選択肢制限)を設定し、型安全性を強化しています。 parse() メソッドは自動的にスキーマ変換、レスポンス検証、Pydanticオブジェクト生成を行うため、開発効率が大幅に向上します。

実行すると、構造化されたフィードバック分析結果が Pydantic モデルとして返されます。 型ヒント、自動補完、IDEサポートがフルに活用でき、プロパティアクセスも result.customer_name のように直感的に行えます。

Zodを使用したTypeScript実装

TypeScript環境では、Zodスキーマを使用して同等の型安全性を実現できます。

typescript
import { z } from 'zod';
import Anthropic from '@anthropic-ai/sdk';
import { betaZodOutputFormat } from '@anthropic-ai/sdk/helpers/beta/zod';

// Zodスキーマの定義
const EventRegistrationSchema = z.object({
  participant_name: z.string().min(1).describe("参加者名"),
  email: z.string().email().describe("メールアドレス"),
  phone: z.string().optional().describe("電話番号"),
  age_group: z.enum(["18-25", "26-35", "36-45", "46-55", "56+"]).describe("年齢層"),
  event_type: z.enum(["workshop", "seminar", "conference", "networking"]).describe("イベント種別"),
  dietary_restrictions: z.array(z.string()).default([]).describe("食事制限"),
  accessibility_needs: z.array(z.string()).default([]).describe("アクセシビリティ要件"),
  experience_level: z.enum(["beginner", "intermediate", "advanced"]).describe("経験レベル"),
  topics_of_interest: z.array(z.string()).min(1).describe("関心トピック"),
  payment_method: z.enum(["credit_card", "bank_transfer", "cash"]).describe("支払い方法"),
  special_requests: z.string().optional().describe("特別な要求"),
  marketing_consent: z.boolean().describe("マーケティング同意"),
  registration_source: z.string().describe("申し込み経路")
});

type EventRegistration = z.infer<typeof EventRegistrationSchema>;

class EventRegistrationProcessor {
  private client: Anthropic;

  constructor(apiKey: string) {
    this.client = new Anthropic({ apiKey });
  }

  async processRegistration(registrationText: string): Promise<EventRegistration> {
    const response = await this.client.beta.messages.parse({
      model: "claude-sonnet-4-5",
      max_tokens: 1024,
      betas: ["structured-outputs-2025-11-13"],
      messages: [
        {
          role: "user",
          content: `
以下のイベント参加申し込み情報から、構造化データを抽出してください:

${registrationText}

参加者情報、イベント詳細、特別な要求などをすべて抽出し、適切にカテゴライズしてください。
          `
        }
      ],
      output_format: betaZodOutputFormat(EventRegistrationSchema),
    });

    return response.parsed_output;
  }

  async batchProcessRegistrations(registrations: string[]): Promise<EventRegistration[]> {
    const results: EventRegistration[] = [];

    for (const registration of registrations) {
      try {
        const processed = await this.processRegistration(registration);
        results.push(processed);
      } catch (error) {
        console.error(`登録処理エラー:`, error);
        // エラーログ記録後、処理継続
      }
    }

    return results;
  }

  generateRegistrationReport(registrations: EventRegistration[]): void {
    // 年齢層分布
    const ageDistribution = registrations.reduce((acc, reg) => {
      acc[reg.age_group] = (acc[reg.age_group] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    // 経験レベル分布
    const experienceDistribution = registrations.reduce((acc, reg) => {
      acc[reg.experience_level] = (acc[reg.experience_level] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    console.log("=== 参加者登録分析レポート ===");
    console.log(`総参加者数: ${registrations.length}名`);
    console.log("\n年齢層分布:");
    Object.entries(ageDistribution).forEach(([age, count]) => {
      console.log(`  ${age}: ${count}名`);
    });

    console.log("\n経験レベル分布:");
    Object.entries(experienceDistribution).forEach(([level, count]) => {
      console.log(`  ${level}: ${count}名`);
    });
  }
}

// 使用例
async function main() {
  const processor = new EventRegistrationProcessor(process.env.ANTHROPIC_API_KEY!);

  const registrationTexts = [
    `
    佐藤花子(sato@example.com、090-1234-5678)です。
    32歳、AIワークショップに参加希望。
    プログラミング経験は中級レベル、機械学習とデータ分析に興味があります。
    ベジタリアン対応をお願いします。
    クレジットカードで支払い予定。
    WebサイトのSNS投稿から知りました。
    マーケティング情報の受け取りに同意します。
    `,
    `
    田中太郎(tanaka@company.jp)、28歳です。
    テックカンファレンスに参加したいです。
    初心者レベルですが、クラウド技術とDevOpsを学びたい。
    車椅子での参加のため、アクセシブルな会場をお願いします。
    銀行振込で支払います。
    同僚の紹介で知りました。
    `
  ];

  try {
    console.log("参加登録を処理中...");
    const results = await processor.batchProcessRegistrations(registrationTexts);

    console.log(`${results.length}件の登録が正常に処理されました。\n`);

    // 各登録の詳細表示
    results.forEach((registration, index) => {
      console.log(`--- 登録 ${index + 1} ---`);
      console.log(`名前: ${registration.participant_name}`);
      console.log(`メール: ${registration.email}`);
      console.log(`年齢層: ${registration.age_group}`);
      console.log(`経験レベル: ${registration.experience_level}`);
      console.log(`関心分野: ${registration.topics_of_interest.join(', ')}`);
      if (registration.dietary_restrictions.length > 0) {
        console.log(`食事制限: ${registration.dietary_restrictions.join(', ')}`);
      }
      if (registration.accessibility_needs.length > 0) {
        console.log(`アクセシビリティ: ${registration.accessibility_needs.join(', ')}`);
      }
      console.log();
    });

    // 集計レポート生成
    processor.generateRegistrationReport(results);

  } catch (error) {
    console.error("処理中にエラーが発生しました:", error);
  }
}

main();

このTypeScriptコードでは、Zodスキーマで複雑なイベント登録データを定義し、betaZodOutputFormat() ヘルパーでClaude APIと統合しています。 バリデーションルール(.min(1) で最小文字数、.email() でメール形式チェック、.enum() で選択肢制限)が自動的に適用され、型安全性が保証されます。 バッチ処理機能と集計レポート生成機能により、大量の申し込みデータを効率的に処理できます。

実行すると、非構造化テキストから正確に構造化された登録データが抽出され、TypeScriptの型システムによって安全にアクセスできます。

厳密ツール使用

構造化出力のもう一つの重要な機能が厳密ツール使用(Strict Tool Use)です。 この機能により、Claude がツールを呼び出す際のパラメータも、JSON スキーマに基づいて厳密に制御できます。 従来の通常ツール使用では、Claude が時折不正な形式でツールパラメータを生成することがありましたが、厳密ツール使用ではこの問題を根本的に解決します。

基本的な設定方法

厳密ツール使用を有効にするには、tool_choice パラメータで特定のツールを指定し、そのツールの入力スキーマに準拠した形式でレスポンスを強制します。

python
import json
from anthropic import Anthropic

client = Anthropic()

# ユーザー情報検索ツールの定義
search_user_tool = {
    "name": "search_user",
    "description": "データベースからユーザー情報を検索します",
    "input_schema": {
        "type": "object",
        "properties": {
            "search_type": {
                "type": "string",
                "enum": ["email", "username", "user_id", "phone"],
                "description": "検索方法を指定"
            },
            "query": {
                "type": "string",
                "minLength": 1,
                "maxLength": 100,
                "description": "検索クエリ"
            },
            "include_inactive": {
                "type": "boolean",
                "default": false,
                "description": "無効化されたユーザーも含めるか"
            },
            "limit": {
                "type": "integer",
                "minimum": 1,
                "maximum": 100,
                "default": 10,
                "description": "最大取得件数"
            }
        },
        "required": ["search_type", "query"],
        "additionalProperties": false
    }
}

# 厳密ツール使用でのリクエスト実行
response = client.beta.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    betas=["structured-outputs-2025-11-13"],
    tools=[search_user_tool],
    tool_choice={"type": "tool", "name": "search_user"},  # 厳密モードを有効化
    messages=[
        {
            "role": "user",
            "content": "田中太郎さんのメールアドレス tanaka@example.com でユーザー情報を検索して。無効化されたアカウントも含めて最大5件まで取得したい"
        }
    ]
)

# ツール使用結果の処理
tool_call = response.content[0]
if tool_call.type == "tool_use":
    params = tool_call.input
    print(f"ツール: {tool_call.name}")
    print(f"検索タイプ: {params['search_type']}")
    print(f"クエリ: {params['query']}")
    print(f"無効ユーザー含む: {params['include_inactive']}")
    print(f"取得上限: {params['limit']}")

このコードでは、tool_choice に特定のツール名を指定することで厳密モードを有効化しています。 Claude は必ず search_user ツールを呼び出し、そのパラメータは定義したスキーマに厳密に準拠します。 enum による選択肢制限、minLength/maxLength による文字数制限、minimum/maximum による数値範囲制限がすべて適用され、不正なパラメータが生成される心配がありません。

複雑な業務ツールでの活用

実際の業務システムでは、複数のパラメータを持つ複雑なツールを厳密に制御することが重要です。 以下は、顧客管理システムでの顧客情報更新ツールの例です。

python
from datetime import datetime
from typing import Optional, List

# 顧客情報更新ツールの詳細スキーマ定義
update_customer_tool = {
    "name": "update_customer",
    "description": "顧客情報をデータベースで更新します",
    "input_schema": {
        "type": "object",
        "properties": {
            "customer_id": {
                "type": "string",
                "pattern": "^CU[0-9]{8}$",
                "description": "顧客ID(CU + 8桁数字の形式)"
            },
            "update_fields": {
                "type": "object",
                "properties": {
                    "company_name": {
                        "type": "string",
                        "minLength": 1,
                        "maxLength": 200,
                        "description": "会社名"
                    },
                    "contact_person": {
                        "type": "string",
                        "minLength": 1,
                        "maxLength": 100,
                        "description": "担当者名"
                    },
                    "email": {
                        "type": "string",
                        "format": "email",
                        "description": "メールアドレス"
                    },
                    "phone": {
                        "type": "string",
                        "pattern": "^[0-9\\-+()\\s]+$",
                        "description": "電話番号"
                    },
                    "industry": {
                        "type": "string",
                        "enum": ["IT", "製造業", "小売業", "金融業", "医療", "教育", "その他"],
                        "description": "業界分類"
                    },
                    "company_size": {
                        "type": "string",
                        "enum": ["1-10名", "11-50名", "51-200名", "201-1000名", "1000名以上"],
                        "description": "会社規模"
                    },
                    "contract_status": {
                        "type": "string",
                        "enum": ["見込み", "商談中", "契約済み", "休眠", "解約"],
                        "description": "契約状況"
                    },
                    "tags": {
                        "type": "array",
                        "items": {"type": "string"},
                        "maxItems": 10,
                        "description": "タグ(最大10個)"
                    }
                },
                "additionalProperties": false,
                "minProperties": 1,
                "description": "更新するフィールド(最低1つは必須)"
            },
            "update_reason": {
                "type": "string",
                "minLength": 10,
                "maxLength": 500,
                "description": "更新理由(10文字以上500文字以内)"
            },
            "notify_stakeholders": {
                "type": "boolean",
                "default": true,
                "description": "関係者に通知するか"
            },
            "schedule_follow_up": {
                "type": "object",
                "properties": {
                    "enabled": {"type": "boolean"},
                    "days_later": {
                        "type": "integer",
                        "minimum": 1,
                        "maximum": 365
                    },
                    "follow_up_type": {
                        "type": "string",
                        "enum": ["電話", "メール", "訪問", "その他"]
                    }
                },
                "required": ["enabled"],
                "if": {"properties": {"enabled": {"const": true}}},
                "then": {"required": ["days_later", "follow_up_type"]},
                "description": "フォローアップスケジュール"
            }
        },
        "required": ["customer_id", "update_fields", "update_reason"],
        "additionalProperties": false
    }
}

def process_customer_update_request(user_request: str):
    """顧客更新リクエストを処理する関数"""

    response = client.beta.messages.create(
        model="claude-sonnet-4-5",
        max_tokens=2048,
        betas=["structured-outputs-2025-11-13"],
        tools=[update_customer_tool],
        tool_choice={"type": "tool", "name": "update_customer"},
        messages=[
            {
                "role": "user",
                "content": f"""
以下の顧客情報更新要求を解析し、適切なパラメータで update_customer ツールを実行してください。

{user_request}

注意事項:
- 顧客IDは CU + 8桁数字の形式で指定してください
- 更新理由は具体的に10文字以上で記述してください
- フォローアップが必要な場合は適切な日数と方法を設定してください
"""
            }
        ]
    )

    return response.content[0].input if response.content[0].type == "tool_use" else None

# 使用例
customer_requests = [
    """
    顧客ID CU12345678 の株式会社テクノロジーの担当者が変更になりました。
    新担当者は佐藤花子さん(hanako.sato@techno.co.jp、03-1234-5678)です。
    また、最近大型案件の受注が決まったため、契約ステータスを「契約済み」に更新し、
    「大口顧客」タグを追加してください。1週間後にお礼の電話をする予定です。
    """,

    """
    顧客CU87654321のABC商事について、業界を「小売業」に変更し、
    会社規模を「201-1000名」に更新してください。
    先日の商談で詳細な企業情報を確認できたためです。
    """
]

print("顧客情報更新処理を開始...")
for i, request in enumerate(customer_requests, 1):
    print(f"\n--- リクエスト {i} ---")
    try:
        params = process_customer_update_request(request)
        if params:
            print(f"顧客ID: {params['customer_id']}")
            print("更新フィールド:")
            for field, value in params['update_fields'].items():
                print(f"  {field}: {value}")
            print(f"更新理由: {params['update_reason']}")
            print(f"関係者通知: {params['notify_stakeholders']}")

            if params.get('schedule_follow_up', {}).get('enabled'):
                follow_up = params['schedule_follow_up']
                print(f"フォローアップ: {follow_up['days_later']}日後に{follow_up['follow_up_type']}")
            else:
                print("フォローアップ: なし")

        else:
            print("パラメータの解析に失敗しました")

    except Exception as e:
        print(f"エラー: {e}")

この例では、複雑な顧客管理ツールのスキーマを定義し、厳密ツール使用で正確なパラメータ生成を保証しています。 正規表現パターン(顧客ID形式)、条件分岐バリデーション(フォローアップ設定)、ネストしたオブジェクト構造など、実際の業務システムで必要となる複雑な制約をすべてスキーマで表現できます。

エラーハンドリングとバリデーション

厳密ツール使用では、スキーマ違反が発生した場合に適切なエラーハンドリングが重要です。

python
def safe_tool_execution(user_input: str, tool_definition: dict):
    """安全なツール実行とエラーハンドリング"""

    max_retries = 3
    retry_count = 0

    while retry_count < max_retries:
        try:
            response = client.beta.messages.create(
                model="claude-sonnet-4-5",
                max_tokens=1024,
                betas=["structured-outputs-2025-11-13"],
                tools=[tool_definition],
                tool_choice={"type": "tool", "name": tool_definition["name"]},
                messages=[
                    {"role": "user", "content": user_input}
                ]
            )

            # ツール呼び出し成功時の処理
            tool_call = response.content[0]
            if tool_call.type == "tool_use":
                return {
                    "success": True,
                    "tool_name": tool_call.name,
                    "parameters": tool_call.input,
                    "retry_count": retry_count
                }

        except Exception as e:
            retry_count += 1
            print(f"試行 {retry_count}/{max_retries} 失敗: {str(e)}")

            if retry_count >= max_retries:
                return {
                    "success": False,
                    "error": str(e),
                    "retry_count": retry_count
                }

            # リトライ間隔(指数バックオフ)
            import time
            time.sleep(2 ** retry_count)

    return {"success": False, "error": "Maximum retries exceeded"}

# バリデーション結果の検証
def validate_tool_parameters(params: dict, schema: dict) -> bool:
    """ツールパラメータのスキーマ適合性をチェック"""
    import jsonschema

    try:
        jsonschema.validate(params, schema)
        return True
    except jsonschema.ValidationError as e:
        print(f"スキーマバリデーションエラー: {e.message}")
        return False
    except Exception as e:
        print(f"予期しないエラー: {e}")
        return False

# 使用例
tool_definition = update_customer_tool
user_request = "顧客CU12345678の会社名をテクノロジー株式会社に変更してください"

result = safe_tool_execution(user_request, tool_definition)

if result["success"]:
    # パラメータの二重チェック
    if validate_tool_parameters(result["parameters"], tool_definition["input_schema"]):
        print("ツール実行パラメータが正常に生成されました")
        print(f"実行回数: {result['retry_count'] + 1}")
        # 実際のツール実行処理
        # execute_actual_tool(result["parameters"])
    else:
        print("生成されたパラメータがスキーマに適合していません")
else:
    print(f"ツール実行に失敗しました: {result['error']}")

このエラーハンドリング機構により、ネットワークエラーや一時的なAPI障害にも堅牢に対応できます。 リトライ機構と指数バックオフにより、安定した処理が実現されます。

両機能の組み合わせ活用

JSON出力と厳密ツール使用を組み合わせることで、より高度で複雑な業務自動化システムを構築できます。 この組み合わせにより、Claude が複数のツールを連続して呼び出し、各段階で構造化された結果を生成する sophisticated なワークフローが実現できます。

マルチステップ分析パイプライン

以下は、顧客フィードバック分析から改善提案生成まで、複数のステップを自動化する例です。

python
from typing import List, Dict, Any
from dataclasses import dataclass
import json

@dataclass
class AnalysisResult:
    feedback_analysis: dict
    sentiment_summary: dict
    improvement_plan: dict
    priority_actions: list

class FeedbackAnalysisPipeline:
    def __init__(self):
        self.client = Anthropic()

    def analyze_feedback(self, feedback_text: str) -> dict:
        """ステップ1: フィードバックの詳細分析"""

        # フィードバック分析用のJSON出力スキーマ
        analysis_schema = {
            "type": "object",
            "properties": {
                "overall_sentiment": {
                    "type": "string",
                    "enum": ["very_positive", "positive", "neutral", "negative", "very_negative"]
                },
                "key_issues": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "category": {"type": "string", "enum": ["product", "service", "price", "delivery", "support"]},
                            "severity": {"type": "string", "enum": ["low", "medium", "high", "critical"]},
                            "description": {"type": "string"},
                            "frequency_mentioned": {"type": "integer", "minimum": 1}
                        },
                        "required": ["category", "severity", "description"]
                    }
                },
                "positive_aspects": {
                    "type": "array",
                    "items": {"type": "string"}
                },
                "customer_expectations": {
                    "type": "array",
                    "items": {"type": "string"}
                },
                "urgency_level": {
                    "type": "string",
                    "enum": ["low", "medium", "high", "immediate"]
                }
            },
            "required": ["overall_sentiment", "key_issues", "urgency_level"]
        }

        response = self.client.beta.messages.create(
            model="claude-sonnet-4-5",
            max_tokens=2048,
            betas=["structured-outputs-2025-11-13"],
            output_format={
                "type": "json_schema",
                "schema": analysis_schema
            },
            messages=[
                {
                    "role": "user",
                    "content": f"""
以下の顧客フィードバックを詳細に分析してください:

{feedback_text}

以下の観点で分析してください:
- 全体的な感情(sentiment)
- 具体的な問題点とその重要度
- 言及された良い点
- 顧客の期待値
- 対応の緊急度
"""
                }
            ]
        )

        return json.loads(response.content[0].text)

    def generate_improvement_plan(self, analysis_result: dict) -> dict:
        """ステップ2: 改善計画の生成(厳密ツール使用)"""

        improvement_tool = {
            "name": "create_improvement_plan",
            "description": "分析結果から改善計画を生成します",
            "input_schema": {
                "type": "object",
                "properties": {
                    "immediate_actions": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "action": {"type": "string", "minLength": 10},
                                "responsible_team": {
                                    "type": "string",
                                    "enum": ["product", "customer_service", "engineering", "sales", "management"]
                                },
                                "estimated_completion": {
                                    "type": "string",
                                    "enum": ["1日", "1週間", "2週間", "1ヶ月", "3ヶ月"]
                                },
                                "impact_level": {
                                    "type": "string",
                                    "enum": ["low", "medium", "high"]
                                }
                            },
                            "required": ["action", "responsible_team", "estimated_completion", "impact_level"]
                        },
                        "minItems": 1,
                        "maxItems": 10
                    },
                    "long_term_strategies": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "strategy": {"type": "string", "minLength": 20},
                                "business_impact": {"type": "string"},
                                "required_resources": {"type": "string"},
                                "timeline": {
                                    "type": "string",
                                    "enum": ["Q1", "Q2", "Q3", "Q4", "来年度"]
                                }
                            },
                            "required": ["strategy", "business_impact", "timeline"]
                        }
                    },
                    "kpi_targets": {
                        "type": "object",
                        "properties": {
                            "customer_satisfaction": {
                                "type": "number",
                                "minimum": 1,
                                "maximum": 10
                            },
                            "issue_resolution_time": {"type": "string"},
                            "repeat_complaint_reduction": {
                                "type": "number",
                                "minimum": 0,
                                "maximum": 100
                            }
                        }
                    },
                    "budget_estimate": {
                        "type": "object",
                        "properties": {
                            "immediate_costs": {"type": "number", "minimum": 0},
                            "ongoing_costs": {"type": "number", "minimum": 0},
                            "expected_roi": {"type": "string"}
                        }
                    }
                },
                "required": ["immediate_actions", "long_term_strategies"]
            }
        }

        response = self.client.beta.messages.create(
            model="claude-sonnet-4-5",
            max_tokens=3000,
            betas=["structured-outputs-2025-11-13"],
            tools=[improvement_tool],
            tool_choice={"type": "tool", "name": "create_improvement_plan"},
            messages=[
                {
                    "role": "user",
                    "content": f"""
以下の顧客フィードバック分析結果を基に、具体的で実行可能な改善計画を作成してください:

分析結果:
{json.dumps(analysis_result, ensure_ascii=False, indent=2)}

改善計画では以下を含めてください:
- 即座に実行すべきアクション(緊急度の高い問題への対処)
- 長期的な戦略(根本的な改善)
- 測定可能なKPI目標
- 予算見積もり
"""
                }
            ]
        )

        return response.content[0].input

    def create_executive_summary(self, analysis: dict, improvement_plan: dict) -> dict:
        """ステップ3: エグゼクティブサマリーの生成"""

        summary_schema = {
            "type": "object",
            "properties": {
                "executive_summary": {
                    "type": "string",
                    "minLength": 100,
                    "maxLength": 500,
                    "description": "経営陣向けのサマリー"
                },
                "key_metrics": {
                    "type": "object",
                    "properties": {
                        "critical_issues_count": {"type": "integer"},
                        "affected_customer_segments": {"type": "array", "items": {"type": "string"}},
                        "estimated_revenue_impact": {"type": "string"},
                        "recommended_investment": {"type": "string"}
                    }
                },
                "next_steps": {
                    "type": "array",
                    "items": {"type": "string"},
                    "minItems": 3,
                    "maxItems": 5
                },
                "risk_assessment": {
                    "type": "string",
                    "enum": ["low", "medium", "high"],
                    "description": "対応しない場合のビジネスリスク"
                }
            },
            "required": ["executive_summary", "key_metrics", "next_steps", "risk_assessment"]
        }

        response = self.client.beta.messages.create(
            model="claude-sonnet-4-5",
            max_tokens=1500,
            betas=["structured-outputs-2025-11-13"],
            output_format={
                "type": "json_schema",
                "schema": summary_schema
            },
            messages=[
                {
                    "role": "user",
                    "content": f"""
以下の分析結果と改善計画から、経営陣向けのエグゼクティブサマリーを作成してください:

分析結果:
{json.dumps(analysis, ensure_ascii=False, indent=2)}

改善計画:
{json.dumps(improvement_plan, ensure_ascii=False, indent=2)}

サマリーには以下を含めてください:
- 簡潔な現状把握と提言
- 重要な数値指標
- 具体的なネクストステップ
- 対応しない場合のリスク評価
"""
                }
            ]
        )

        return json.loads(response.content[0].text)

    def run_complete_analysis(self, feedback_text: str) -> AnalysisResult:
        """完全な分析パイプラインの実行"""

        print("顧客フィードバック分析パイプラインを開始...")

        # ステップ1: フィードバック分析
        print("1. フィードバック詳細分析...")
        analysis = self.analyze_feedback(feedback_text)

        # ステップ2: 改善計画生成
        print("2. 改善計画の策定...")
        improvement_plan = self.generate_improvement_plan(analysis)

        # ステップ3: エグゼクティブサマリー生成
        print("3. エグゼクティブサマリーの作成...")
        executive_summary = self.create_executive_summary(analysis, improvement_plan)

        # 最優先アクションの抽出
        priority_actions = [
            action for action in improvement_plan.get("immediate_actions", [])
            if action.get("impact_level") == "high"
        ]

        print("分析完了!")
        return AnalysisResult(
            feedback_analysis=analysis,
            sentiment_summary=executive_summary,
            improvement_plan=improvement_plan,
            priority_actions=priority_actions
        )

# 使用例
def main():
    pipeline = FeedbackAnalysisPipeline()

    # 実際の顧客フィードバック例
    customer_feedback = """
    先月からこちらのサービスを使い始めましたが、いくつか問題を感じています。

    まず、アプリの動作が非常に遅く、特にデータの読み込みに時間がかかります。
    朝の忙しい時間帯には3-4分も待たされることがあり、業務に支障が出ています。

    また、カスタマーサポートに連絡した際の対応も改善の余地があります。
    問い合わせから返答まで2日間も待たされ、最初の回答では私の質問が理解されていませんでした。
    再度説明が必要で、結局解決まで1週間かかりました。

    価格に関しては他社と比較して高めですが、機能は充実していると思います。
    特にレポート機能は便利で、データの可視化がとても分かりやすいです。

    今後も使い続けたいと思っているので、上記の問題が改善されることを期待しています。
    """

    try:
        # 完全な分析実行
        result = pipeline.run_complete_analysis(customer_feedback)

        # 結果の表示
        print("\n=== 分析結果サマリー ===")
        print(f"全体的感情: {result.feedback_analysis['overall_sentiment']}")
        print(f"緊急度: {result.feedback_analysis['urgency_level']}")

        print(f"\n主要な問題点:")
        for issue in result.feedback_analysis['key_issues']:
            print(f"  - {issue['category']}: {issue['description']} (重要度: {issue['severity']})")

        print(f"\n=== 改善計画 ===")
        print(f"即座に実行すべきアクション数: {len(result.improvement_plan['immediate_actions'])}")
        print(f"長期戦略数: {len(result.improvement_plan.get('long_term_strategies', []))}")

        print(f"\n最優先アクション:")
        for action in result.priority_actions:
            print(f"  - {action['action']}")
            print(f"    担当: {action['responsible_team']}, 期限: {action['estimated_completion']}")

        print(f"\n=== エグゼクティブサマリー ===")
        print(f"概要: {result.sentiment_summary['executive_summary']}")
        print(f"リスク評価: {result.sentiment_summary['risk_assessment']}")

        print(f"\nネクストステップ:")
        for step in result.sentiment_summary['next_steps']:
            print(f"  - {step}")

    except Exception as e:
        print(f"分析中にエラーが発生しました: {e}")

if __name__ == "__main__":
    main()

この包括的な例では、3つの異なるステージで構造化出力を活用しています。 JSON出力でデータ分析結果を構造化し、厳密ツール使用で改善計画を正確に生成し、最後に再びJSON出力でサマリーを作成しています。 各ステップの結果が次のステップの入力として使われ、複雑なビジネスプロセスを自動化しています。

重要な考慮事項

グラマーコンパイルとキャッシング

構造化出力は制約サンプリングとコンパイルされた文法アーティファクトを使用します。 以下のパフォーマンス特性に注意が必要です。

  • 初回リクエスト遅延: 特定のスキーマを初めて使用する際、文法のコンパイルに追加の遅延が発生します
  • 自動キャッシング: コンパイルされた文法は最後の使用から24時間キャッシュされ、後続のリクエストは高速化されます
  • キャッシュ無効化: 以下の変更によりキャッシュが無効化されます:
    • JSONスキーマ構造の変更
    • リクエスト内のツールセットの変更(構造化出力とツール使用の併用時)
    • nameやdescriptionフィールドのみの変更ではキャッシュは無効化されません

プロンプト変更とトークンコスト

構造化出力を使用する際、Claude は期待される出力形式を説明する追加のシステムプロンプトを自動的に受け取ります。

  • 入力トークン数がわずかに増加します
  • 注入されたプロンプトは他のシステムプロンプトと同様にトークン課金されます
  • output_formatパラメータを変更すると、その会話スレッドのプロンプトキャッシュが無効化されます

無効な出力のケース

構造化出力はほとんどの場合でスキーマ準拠を保証しますが、出力がスキーマに一致しない場合があります。

拒否(stop_reason: "refusal")

Claude は構造化出力使用時も安全性と有用性の特性を維持します。 安全上の理由でリクエストを拒否する場合、拒否メッセージがスキーマ制約よりも優先されるため、出力がスキーマに一致しない場合があります。

トークン制限到達(stop_reason: "max_tokens")

max_tokens制限に到達してレスポンスが切り詰められた場合、出力は不完全になりスキーマに一致しない可能性があります。 より高いmax_tokens値で再試行することで完全な構造化出力を取得できます。

スキーマバリデーションエラー

スキーマがサポートされていない機能を使用している場合や複雑すぎる場合、400エラーが返されます。

  • "Too many recursive definitions in schema": スキーマに過度の再帰定義や循環参照があります。スキーマ構造を簡略化し、ネスト深度を減らしてください
  • "Schema is too complex": スキーマが複雑さの制限を超えています。より小さなスキーマに分割するか、strict: trueのツール数を減らしてください

機能互換性

互換性のある機能

  • バッチ処理: 50%割引で構造化出力を大規模に処理可能
  • トークンカウント: コンパイルなしでトークンをカウント可能
  • ストリーミング: 通常のレスポンスと同様に構造化出力をストリーミング可能
  • 複合使用: JSON出力(output_format)と厳密ツール使用(strict: true)を同じリクエストで併用可能

非互換な機能

  • Citations(引用): 引用はテキスト出力と引用ブロックをインターリーブする必要があるため、厳密なJSONスキーマ制約と互換性がありません。output_formatで引用を有効にすると400エラーが返されます
  • Message Prefilling: JSON出力との併用は非対応です

グラマースコープ

グラマーはClaudeの直接的な出力にのみ適用され、ツール使用呼び出し、ツール結果、思考タグ(Extended Thinking使用時)には適用されません。 グラマー状態はセクション間でリセットされ、Claude は自由に思考しながらも最終レスポンスで構造化出力を生成できます。

参考情報