"""Structured outputs with the Python SDK: client.messages.parse() + a Pydantic model (SDK transforms the schema, validates the response, returns parsed_output). Also shows the raw output_config.format form and an unsupported schema keyword (`minimum`) returning 400. STATUS: LIVE_VERIFIED 2026-09-18 (claude-haiku-4-5-20251001): parsed Person(name='Ada', age=36, city='Lyon'); raw call OK; `minimum` → 400 "For 'integer' type, property 'minimum' is not supported". ≈$0.0006. Run: .venv/bin/python examples/anthropic/structured-output/json_schema_pydantic.py """ from __future__ import annotations import json import os import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[3])) from scripts import live # noqa: E402 import anthropic # noqa: E402 from pydantic import BaseModel # noqa: E402 MODEL = os.environ.get("ANTHROPIC_MODEL", "claude-haiku-4-5-20251001") client = anthropic.Anthropic(max_retries=1) PROMPT = "Ada is 36 and lives in Lyon. Extract the person." class Person(BaseModel): name: str age: int city: str parsed = client.messages.parse(model=MODEL, max_tokens=100, output_format=Person, messages=[{"role": "user", "content": PROMPT}]) print("parse():", parsed.parsed_output) live.log_request("anthropic", "POST", "/v1/messages", 200, 0.0003, f"example structured-output/json_schema_pydantic.py parse {MODEL}") schema = {"type": "object", "properties": {"name": {"type": "string"}, "age": {"type": "integer"}, "city": {"type": "string"}}, "required": ["name", "age", "city"], "additionalProperties": False} raw = client.messages.create(model=MODEL, max_tokens=100, output_config={"format": {"type": "json_schema", "schema": schema}}, messages=[{"role": "user", "content": PROMPT}]) print("raw:", json.loads(raw.content[0].text)) live.log_request("anthropic", "POST", "/v1/messages", 200, 0.0003, f"example structured-output/json_schema_pydantic.py raw {MODEL}") bad = {"type": "object", "properties": {"age": {"type": "integer", "minimum": 0}}, "required": ["age"], "additionalProperties": False} try: client.messages.create(model=MODEL, max_tokens=50, output_config={"format": {"type": "json_schema", "schema": bad}}, messages=[{"role": "user", "content": PROMPT}]) except anthropic.BadRequestError as e: print("unsupported keyword ->", e.status_code, e.body["error"]["message"]) live.log_request("anthropic", "POST", "/v1/messages", e.status_code, 0, "example structured-output/json_schema_pydantic.py minimum -> 400")