Using Pydantic with Claude Sonnet 4.5 on OpenRouter
This tutorial explains how to use a Pydantic schema to extract structured data using Claude Sonnet 4.5.
Please read this tutorial first to understand the basic setup
Code:
import json
import os
import time
import requests
from dotenv import load_dotenv
from inputs import get_input_text
from schema import VAERSReport
from system import system_instruction_1 as system_instruction
load_dotenv()
model_name = 'anthropic/claude-sonnet-4.5'
api_key = os.getenv("OPENROUTER_API_KEY")
json_schema_text = json.dumps(VAERSReport.model_json_schema(), indent=2)
input_text, sentence_map = get_input_text()
prompt = f"""
Report: {input_text}
JSON Schema:
{json_schema_text}
"""
url = "https://openrouter.ai/api/v1/chat/completions"
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"HTTP-Referer": "https://botflo.com/", # Optional. Site URL for rankings on openrouter.ai.
"X-Title": "LLM Accuracy Comparisons for Structured Outputs", # Optional
}
payload = {
"model": model_name,
"messages": [
{"role": "system", "content": f'{system_instruction}'},
{"role": "user", "content": f'{prompt}'}
],
"reasoning": {
"effort": "high"
}
}
before = time.time()
response_full = requests.post(url, headers=headers, data=json.dumps(payload))
elapsed = time.time() - before
response = response_full.json()
metadata = {
"metrics": {
"elapsed": elapsed,
"usage": response['usage']
},
"text": {
"system_instruction": system_instruction,
"sentence_map": sentence_map,
"json_schema_text": json_schema_text
}
}
response["metadata"] = metadata
response_file_name = f"responses/response_{model_name.replace('/', '-')}.json"
with open(response_file_name, 'w+') as f:
json.dump(response, f, indent=2)
output_text = response.get('choices')[0].get('message').get('content')
print(output_text)
input_file_name = f"inputs/input_{model_name.replace('/', '-')}.txt"
with open(input_file_name, 'w+') as f:
f.write(input_text)
output_file_name = f"outputs/output_{model_name.replace('/', '-')}.txt"
with open(output_file_name, 'w+') as f:
f.write(output_text)
LLM Response:
```json
{
"timeline": {
"date_of_vaccination": {
"year": 1999,
"month": 6,
"citations": [3, 42],
"explanation": "Last in series of Hepatitis B vaccinations on 6/30/99"
},
"regression_onset_date": {
"year": 2000,
"month": null,
"citations": [45, 146, 147],
"explanation": "Spring of 2000; mother reported symptoms began between 21-23 months"
},
"diagnosis_date": {
"year": 2001,
"month": 1,
"citations": [98, 150],
"explanation": "Evaluated at autism resource center on 1/4/01"
},
"age_at_vaccination_months": {
"value": 16,
"citations": [3],
"explanation": "Age listed as 1.33 years in VAERS header"
},
"age_at_diagnosis_months": {
"value": 25,
"citations": [98],
"explanation": "Approximately 25 months based on evaluation date 1/4/01 and birth around 12/1998"
}
},
"developmental_milestones": [
{
"milestone_name": {
"value": "sitting_without_support",
"citations": [41]
},
"milestone_type": "adaptive_behavior",
"milestone_age_in_months": {
"value": 8,
"citations": [41],
"explanation": "Sat without support at 8 months (6 months adjusted for prematurity)"
},
"milestone_has_regressed": {
"value": false,
"citations": [41]
},
"regression_start_date_in_months": {
"value": null,
"citations": null
},
"progressed_after_regression": {
"value": false,
"citations": null
}
},
{
"milestone_name": {
"value": "walking",
"citations": [41]
},
"milestone_type": "adaptive_behavior",
"milestone_age_in_months": {
"value": 12,
"citations": [41],
"explanation": "Walked by 12 months (10 months adjusted for prematurity)"
},
"milestone_has_regressed": {
"value": false,
"citations": [41]
},
"regression_start_date_in_months": {
"value": null,
"citations": null
},
"progressed_after_regression": {
"value": false,
"citations": null
}
},
{
"milestone_name": {
"value": "single_words",
"citations": [41]
},
"milestone_type": "language",
"milestone_age_in_months": {
"value": 17,
"citations": [41],
"explanation": "Started saying a few single words at around 17 months (15 months adjusted)"
},
"milestone_has_regressed": {
"value": true,
"citations": [99, 110, 147],
"explanation": "Parents concerned language appeared delayed and good language behaviors decreased in frequency"
},
"regression_start_date_in_months": {
"value": 21,
"citations": [146, 147],
"explanation": "Between 21-23 months began to develop symptoms"
},
"progressed_after_regression": {
"value": false,
"citations": [160, 162],
"explanation": "Autism persisted as of July 2002"
}
},
{
"milestone_name": {
"value": "eye_contact",
"citations": [108, 113, 116]
},
"milestone_type": "social_communication",
"milestone_age_in_months": {
"value": null,
"citations": null,
"explanation": "Was using eye contact during evaluation, age of achievement not specified"
},
"milestone_has_regressed": {
"value": true,
"citations": [110],
"explanation": "Parents concerned that good social behaviors no longer happen with same frequency"
},
"regression_start_date_in_months": {
"value": 21,
"citations": [146]
},
"progressed_after_regression": {
"value": false,
"citations": [160, 162]
}
},
{
"milestone_name": {
"value": "responding_to_name",
"citations": [108]
},
"milestone_type": "social_communication",
"milestone_age_in_months": {
"value": null,
"citations": null,
"explanation": "Responded to his name during evaluation, age of achievement not specified"
},
"milestone_has_regressed": {
"value": true,
"citations": [110],
"explanation": "Good social behaviors decreased in frequency"
},
"regression_start_date_in_months": {
"value": 21,
"citations": [146]
},
"progressed_after_regression": {
"value": false,
"citations": [160, 162]
}
},
{
"milestone_name": {
"value": "joint_attention",
"citations": [108, 110]
},
"milestone_type": "social_communication",
"milestone_age_in_months": {
"value": null,
"citations": null,
"explanation": "Initiated sharing interests during evaluation"
},
"milestone_has_regressed": {
"value": true,
"citations": [110],
"explanation": "Initiating joint attention no longer happens with same frequency"
},
"regression_start_date_in_months": {
"value": 21,
"citations": [146]
},
"progressed_after_regression": {
"value": false,
"citations": [160, 162]
}
},
{
"milestone_name": {
"value": "pointing",
"citations": [117, 124]
},
"milestone_type": "social_communication",
"milestone_age_in_months": {
"value": null,
"citations": null,
"explanation": "Pointed at objects but often had to be prompted"
},
"milestone_has_regressed": {
"value": true,
"citations": [110, 117],
"explanation": "Using gestures no longer happens with same frequency, had to be prompted to point"
},
"regression_start_date_in_months": {
"value": 21,
"citations": [146]
},
"progressed_after_regression": {
"value": false,
"citations": [160, 162]
}
},
{
"milestone_name": {
"value": "pretend_play",
"citations": [121, 122, 123]
},
"milestone_type": "social_communication",
"milestone_age_in_months": {
"value": null,
"citations": null,
"explanation": "Demonstrated beginning pretend play skills, used to play this way with brother"
},
"milestone_has_regressed": {
"value": true,
"citations": [123],
"explanation": "This type of play has decreased significantly in the past several weeks"
},
"regression_start_date_in_months": {
"value": 21,
"citations": [146]
},
"progressed_after_regression": {
"value": false,
"citations": [160, 162]
}
}
],
"regression_record": {
"pre_regression_language_level": {
"value": "babbling_single_words",
"citations": [41, 146],
"explanation": "Started saying a few single words at 17 months, developed normally for first 21-23 months"
},
"pre_regression_social_communication_level": {
"value": "reciprocal_interaction",
"citations": [103, 104, 105, 106, 107, 108, 109, 146],
"explanation": "Good social behaviors including responding to name, sharing interests, smiling, greeting father, showing enjoyment in interactions"
},
"pre_regression_adaptive_behavior_level": {
"value": "moderate_independence",
"citations": [81, 121, 122, 146],
"explanation": "Appropriate play with objects, feeding skills, developed normally"
},
"post_regression_language_level": {
"value": "babbling_single_words",
"citations": [84, 85, 114, 115],
"explanation": "Limited verbalizations, some single words and word approximations, expressive communication at 15 month level"
},
"post_regression_social_communication_level": {
"value": "basic_engagement",
"citations": [110, 111, 118, 119, 120],
"explanation": "Decreased social behaviors, interest in playing with other children decreased, unusual receptive language difficulties"
},
"post_regression_adaptive_behavior_level": {
"value": "basic_self_help",
"citations": [127, 128, 140],
"explanation": "Adaptive behavior in borderline impaired range, self-care skills slightly below average"
},
"has_language_loss": {
"value": true,
"citations": [99, 110, 147, 148],
"explanation": "Parents concerned language appeared delayed, difficulty with speech, good language behaviors decreased"
},
"has_social_loss": {
"value": true,
"citations": [110, 111, 147, 148],
"explanation": "Good social behaviors no longer happen with same frequency, interest in playing with other children decreased, excessive shyness"
},
"has_adaptive_loss": {
"value": true,
"citations": [127, 128],
"explanation": "Adaptive behavior assessed in borderline impaired range"
},
"has_repetitive_behaviors": {
"value": true,
"citations": [126, 148],
"explanation": "Began lining up toys and objects, using language repetitively"
}
},
"early_vaccination_symptoms": {
"had_autism_features": {
"value": false,
"ongoing": true,
"days_to_symptom_onset": null,
"citations": [45, 146, 147, 160, 162],
"explanation": "Autism features developed months after vaccination at 21-23 months of age, not within 30 days; persisted as of July 2002"
},
"had_fever": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No fever reported within 30 days of vaccination"
},
"had_speech_loss": {
"value": false,
"ongoing": true,
"days_to_symptom_onset": null,
"citations": [147, 148],
"explanation": "Speech difficulties developed at 21-23 months, not within 30 days of vaccination"
},
"had_irritability": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No irritability reported within 30 days of vaccination"
},
"had_eye_contact_loss": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No eye contact loss reported within 30 days of vaccination"
},
"had_diarrhea": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No diarrhea reported within 30 days of vaccination"
},
"had_seizures": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No seizures reported within 30 days of vaccination"
},
"had_lethargy": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No lethargy reported within 30 days of vaccination"
},
"had_screaming": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": [82, 83],
"explanation": "Screaming when frustrated noted later, not within 30 days of vaccination"
},
"had_behavioral_changes": {
"value": false,
"ongoing": true,
"days_to_symptom_onset": null,
"citations": [126, 147, 148],
"explanation": "Behavioral changes (lining up toys, repetitive language, aggressive behaviors) developed at 21-23 months, not within 30 days of vaccination"
},
"had_rash": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No rash reported within 30 days of vaccination"
},
"had_head_banging": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No head banging reported within 30 days of vaccination"
},
"had_social_withdrawal": {
"value": false,
"ongoing": true,
"days_to_symptom_onset": null,
"citations": [110, 111, 147, 148],
"explanation": "Social withdrawal and excessive shyness developed at 21-23 months, not within 30 days of vaccination"
},
"had_injection_site_reaction": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No injection site reaction reported"
},
"had_balance_loss": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No balance loss reported within 30 days of vaccination"
},
"had_appetite_loss": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No appetite loss reported within 30 days of vaccination"
},
"had_staring_spells": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No staring spells reported"
},
"had_hand_flapping": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No hand flapping reported"
},
"had_toe_walking": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No toe walking reported"
},
"had_gastrointestinal_problems": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": [32],
"explanation": "Gastroesophageal reflux noted in neonatal period, not related to vaccination"
},
"had_hyperactivity": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No hyperactivity reported within 30 days of vaccination"
},
"had_ear_infections": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": [39, 135],
"explanation": "Otitis media occurred at 9 months and repeatedly, not within 30 days of vaccination"
},
"had_vomiting": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No vomiting reported within 30 days of vaccination"
},
"had_sleep_problems": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No sleep problems reported within 30 days of vaccination"
},
"had_encephalopathy": {
"value": false,
"ongoing": false,
"days_to_symptom_onset": null,
"citations": null,
"explanation": "No encephalopathy reported"
}
},
"diagnosis_record": {
"asd_severity": {
"value": 2,
"citations": [151],
"explanation": "Rated in moderate autism category per Autism Treatment Evaluation Checklist"
},
"diagnosis_name": [
{
"value": "autism",
"citations": [150, 160, 162, 163]
},
{
"value": "Mixed Expressive Receptive Language Disorder",
"citations": [96, 130]
}
],
"diagnosing_professional": [
{
"value": "psychologist",
"citations": [87, 98, 130]
},
{
"value": "autism trainer",
"citations": [144, 150]
}
]
},
"intervention_record": {
"interventions": [
{
"value": "speech_therapy",
"citations": [76, 86, 97, 131, 154]
},
{
"value": "occupational_therapy",
"citations": [143, 154]
},
{
"value": "aba",
"citations": [154],
"explanation": "Intensive early intervention using applied behavioral analysis"
},
{
"value": "social_skills",
"citations": [77, 131],
"explanation": "Day care recommended for social skills, structured interactions with typical peers"
},
{
"value": "other",
"citations": [78, 79, 131],
"explanation": "Behavior modifications, special instruction for appropriate play skills, parent training"
}
],
"is_intervention_ongoing": {
"value": true,
"citations": [160, 162],
"explanation": "Autism persisted as of July 2002, implying ongoing need for intervention"
},
"has_recovery": {
"value": false,
"citations": [11, 160, 162],
"explanation": "Not recovered, autism persisted as of July 2002"
}
},
"birth_record": {
"was_normal_pre_vaccination": {
"value": true,
"citations": [33, 54, 146],
"explanation": "Neurobehavioral assessments appropriate for age throughout hospitalization, doing well developmentally, developed normally for first 21-23 months"
},
"apgar_score": [
{
"value": "8 at one minute, 9 at five minutes",
"citations": [29]
}
]
},
"behavior_record": {
"repetitive_behaviors": [
{
"value": "lining up toys and objects",
"citations": [126, 148]
},
{
"value": "using language repetitively",
"citations": [148]
},
{
"value": "screaming when frustrated",
"citations": [82, 83]
}
]
},
"heavy_metal_tests": [
{
"metal_type": "mercury",
"value": 10.0,
"unit": "ug/L",
"is_elevated": false,
"citations": [20]
},
{
"metal_type": "lead",
"value": 16.0,
"unit": "ug/L",
"is_elevated": false,
"citations": [20]
},
{
"metal_type": "arsenic",
"value": 60.0,
"unit": "ug/L",
"is_elevated": false,
"citations": [20]
}
],
"comorbidities": [
{
"value": "asthma",
"citations": [155],
"explanation": "Reactive airway disease"
},
{
"value": "other",
"citations": [39, 135, 155],
"explanation": "Recurrent otitis media (ear infections)"
}
],
"environmental_exposures": [
{
"value": "other_mercury",
"citations": [45, 161],
"explanation": "Alleged exposure to thimerosol and mercury contained in vaccines"
}
],
"legal_matter": {
"value": true,
"citations": [22],
"explanation": "Report received as part of litigation proceedings"
},
"diagnosis_reporting_delay_reason": {
"value": "Report received as part of litigation proceedings",
"citations": [22]
}
}
```
Metrics
{
"elapsed": 230.39993715286255,
"usage": {
"prompt_tokens": 16028,
"completion_tokens": 15258,
"total_tokens": 31286
}
}