Using Pydantic with Qwen3 Coder Flash on OpenRouter
This tutorial explains how to use a Pydantic schema to extract structured data using Qwen3 Coder Flash.
Please read this tutorial first to understand the basic setup
Code:
import os
import json
import requests
import time
from inputs import get_input_text
from system import system_instruction_1 as system_instruction
from schema import VAERSReport
from dotenv import load_dotenv
load_dotenv()
model_name = 'qwen/qwen3-coder-flash'
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:
{
"timeline": {
"date_of_vaccination": {
"year": 1999,
"month": 6,
"citations": [42],
"explanation": "Vaccination date recorded as June 30, 1999"
},
"regression_onset_date": {
"year": 2000,
"month": 3,
"citations": [45],
"explanation": "Mother alleged that the infant was administered vaccines earlier in life and became more profoundly affected with autism in the spring of 2000"
},
"diagnosis_date": {
"year": 2001,
"month": 1,
"citations": [98],
"explanation": "Subject was evaluated by a 2nd psychologist on 1/4/01 at an autism resource center"
},
"age_at_vaccination_months": {
"value": 1,
"citations": [42],
"explanation": "Vaccine administration dates indicate he received Engerix B on 1/24/99, 2/15/99, and 6/30/99, suggesting he was about 1 month old at vaccination based on birth date in 1998"
},
"age_at_diagnosis_months": {
"value": 13,
"citations": [98],
"explanation": "Diagnosis occurred at approximately 13 months of age based on 1/4/01 evaluation"
}
},
"developmental_milestones": [
{
"milestone_name": {
"value": "sitting_without_support",
"citations": [41],
"explanation": "Subject sat without support at 8 months (6 months adjusted for prematurity)"
},
"milestone_type": "adaptive_behavior",
"milestone_age_in_months": {
"value": 8,
"citations": [41],
"explanation": "Subject sat without support at 8 months (adjusted age 6 months)"
},
"milestone_has_regressed": {
"value": true,
"citations": [45, 126],
"explanation": "Regression reported with decrease in play behavior and increased toy lining up"
},
"regression_start_date_in_months": {
"value": 18,
"citations": [99, 126],
"explanation": "Parents first became concerned about development around 18 months"
},
"progressed_after_regression": {
"value": false,
"citations": [45, 133],
"explanation": "Report indicates ongoing autism despite interventions, suggesting regression continued"
}
},
{
"milestone_name": {
"value": "walking",
"citations": [41],
"explanation": "Subject walked by 12 months (10 months adjusted)"
},
"milestone_type": "adaptive_behavior",
"milestone_age_in_months": {
"value": 12,
"citations": [41],
"explanation": "Subject walked by 12 months (adjusted age 10 months)"
},
"milestone_has_regressed": {
"value": true,
"citations": [126],
"explanation": "Regression was reported with decreased toy play behavior"
},
"regression_start_date_in_months": {
"value": 18,
"citations": [99, 126],
"explanation": "Parents first became concerned about development around 18 months"
},
"progressed_after_regression": {
"value": false,
"citations": [133],
"explanation": "No indication of improvement post-regression in the available text"
}
},
{
"milestone_name": {
"value": "single_words",
"citations": [41],
"explanation": "Subject started saying a few single words around 17 months (15 months adjusted)"
},
"milestone_type": "language",
"milestone_age_in_months": {
"value": 17,
"citations": [41],
"explanation": "Subject started saying single words at around 17 months (adjusted for prematurity)"
},
"milestone_has_regressed": {
"value": true,
"citations": [45, 126],
"explanation": "Regression was reported with delayed speech and increased repetitive behaviors"
},
"regression_start_date_in_months": {
"value": 18,
"citations": [99, 126],
"explanation": "Parents expressed concern about development around 18 months"
},
"progressed_after_regression": {
"value": false,
"citations": [134],
"explanation": "Occupational therapist noted mild delays in fine motor and sensory processing"
}
},
{
"milestone_name": {
"value": "responding_to_name",
"citations": [109],
"explanation": "Parents reported that subject responds to his name"
},
"milestone_type": "social_communication",
"milestone_age_in_months": {
"value": null,
"citations": [109],
"explanation": "Response to name mentioned but specific age not captured"
},
"milestone_has_regressed": {
"value": false,
"citations": [109, 126],
"explanation": "Subject responded to his name, but regression was reported with decreased social behaviors"
},
"regression_start_date_in_months": {
"value": 18,
"citations": [126],
"explanation": "Regression reported with decreased interest in playing with others"
},
"progressed_after_regression": {
"value": false,
"citations": [],
"explanation": "No evidence of progression after regression identified"
}
}
],
"regression_record": {
"pre_regression_language_level": {
"value": "babbling_single_words",
"citations": [41, 71, 84],
"explanation": "Based on early evaluations showing verbal communication at 15 months and assessment of expressive communication at 15 months"
},
"pre_regression_social_communication_level": {
"value": "reciprocal_interaction",
"citations": [104, 107, 110],
"explanation": "Subject watched others, played somewhat, and initiated sharing of interests, suggesting pre-existing social communication abilities"
},
"pre_regression_adaptive_behavior_level": {
"value": "moderate_independence",
"citations": [128],
"explanation": "Domain scores showing borderline impaired adaptive behavior level"
},
"post_regression_language_level": {
"value": "no_speech",
"citations": [85, 115, 149],
"explanation": "Evaluated as expressing limited speech with only one-word approximations, indicating a significant language loss"
},
"post_regression_social_communication_level": {
"value": "no_engagement",
"citations": [110, 111, 123],
"explanation": "Subject demonstrated decreased interest in playing with others and less frequent initiation of communicative exchanges"
},
"post_regression_adaptive_behavior_level": {
"value": "no_independence",
"citations": [128],
"explanation": "Subject's adaptive behavior was assessed as borderline impaired relative to peers"
},
"has_language_loss": {
"value": true,
"citations": [85, 115, 149],
"explanation": "Significant delay in language development confirmed by multiple assessments showing limited verbal communication"
},
"has_social_loss": {
"value": true,
"citations": [110, 111, 123],
"explanation": "Decreased social engagement reported with reduced interest in peer interaction and decreased initiations"
},
"has_adaptive_loss": {
"value": true,
"citations": [128],
"explanation": "Adaptive behavior was assessed as borderline impaired, indicating loss of typical adaptive functioning"
},
"has_repetitive_behaviors": {
"value": true,
"citations": [126, 149],
"explanation": "Subject was observed lining up toys and objects and exhibits repetitive behaviors"
}
},
"early_vaccination_symptoms": null,
"diagnosis_record": {
"asd_severity": {
"value": 2,
"citations": [130, 151],
"explanation": "Diagnosis of Mixed Expressive Receptive Language Disorder with autism features; moderate autism category assessed"
},
"diagnosis_name": [
{
"value": "Autism",
"citations": [150],
"explanation": "Subject officially diagnosed with autism at the autism resource center"
},
{
"value": "Mixed Expressive Receptive Language Disorder",
"citations": [130],
"explanation": "Formal psychiatric diagnosis documented as Mixed Expressive Receptive Language Disorder"
},
{
"value": "Pervasive Developmental Disorder",
"citations": [130],
"explanation": "While Pervasive Developmental Disorder was not ruled out, this was noted as another possibility"
}
],
"diagnosing_professional": [
{
"value": "Psychologist",
"citations": [98, 100, 113],
"explanation": "Autism diagnosis conducted by a psychologist with Autism Diagnostic Interview and scales"
},
{
"value": "Neurologist",
"citations": [51, 55, 61],
"explanation": "Neonatologist who conducted developmental screenings at multiple timepoints"
},
{
"value": "Speech Pathologist",
"citations": [80],
"explanation": "Speech pathology evaluation conducted to assess linguistic abilities"
},
{
"value": "Occupational Therapist",
"citations": [134],
"explanation": "Occupational therapy evaluation for fine motor development"
},
{
"value": "Autism Trainer",
"citations": [144],
"explanation": "Autism specialist who completed Treatment Evaluation Checklist"
}
]
},
"intervention_record": {
"interventions": [
{
"value": "speech_therapy",
"citations": [76, 86, 112, 154],
"explanation": "Speech therapy recommended across multiple evaluations and treatments"
},
{
"value": "occupational_therapy",
"citations": [143, 154],
"explanation": "Occupational therapy recommended for sensory-processing issues and fine motor delays"
},
{
"value": "aba",
"citations": [154],
"explanation": "Applied Behavioral Analysis therapy recommended for intensive early intervention"
},
{
"value": "social_skills",
"citations": [131, 154],
"explanation": "Structured interactions with peers recommended for social skill development"
},
{
"value": "other",
"citations": [154],
"explanation": "Parent training recommended as part of comprehensive intervention program"
}
],
"is_intervention_ongoing": {
"value": true,
"citations": [154],
"explanation": "Intensive early intervention recommended and ongoing treatment indicated"
},
"has_recovery": {
"value": false,
"citations": [162],
"explanation": "Autism was reported to persist as of July 2002, indicating no recovery"
}
},
"birth_record": {
"was_normal_pre_vaccination": {
"value": true,
"citations": [147],
"explanation": "Mother reported that subject developed normally until 21-23 months of life"
},
"apgar_score": [
{
"value": "8 and 9",
"citations": [29],
"explanation": "Aspar scores of 8 and 9 at one and five minutes respectively"
}
]
},
"behavior_record": {
"repetitive_behaviors": [
{
"value": "Lining up toys and objects",
"citations": [126],
"explanation": "Subject was observed lining up toys and objects (blocks, chairs) rather than playingappropriately"
},
{
"value": "Hand flapping",
"citations": [127],
"explanation": "Repetitive motor mannerisms/stimming behavior noted in evaluation"
},
{
"value": "Toe walking",
"citations": [127],
"explanation": "Toe walking behavior assessed during evaluation"
}
]
},
"heavy_metal_tests": [
{
"metal_type": "lead",
"value": 16,
"unit": "ug/L",
"is_elevated": true,
"citations": [20]
},
{
"metal_type": "arsenic",
"value": 60,
"unit": "ug/L",
"is_elevated": true,
"citations": [20]
},
{
"metal_type": "mercury",
"value": 10,
"unit": "ug/L",
"is_elevated": false,
"citations": [20]
}
],
"comorbidities": [
{
"value": "allergies",
"citations": [33],
"explanation": "Documented comorbid allergies in the prenatal history"
},
{
"value": "asthma",
"citations": [33],
"explanation": "History of respiratory issues including respiratory distress and reactive airway disease"
},
{
"value": "seizure_disorder",
"citations": [33],
"explanation": "Reports of preterm complications including apnea and bradycardia"
},
{
"value": "other",
"citations": [33],
"explanation": "Thrombocytopenia, anemia, jaundice, and other neonatal conditions"
}
],
"environmental_exposures": [
{
"value": "other_mercury",
"citations": [155],
"explanation": "Reported mercury exposure through vaccines containing thimerosal"
}
],
"legal_matter": {
"value": true,
"citations": [22],
"explanation": "Report was received as part of litigation proceedings"
},
"diagnosis_reporting_delay_reason": {
"value": "not specified",
"citations": [],
"explanation": "No explicit reason provided in the report for any delay between diagnosis and reporting"
}
}
Metrics
{
"elapsed": 22.026559114456177,
"usage": {
"prompt_tokens": 13265,
"completion_tokens": 5270,
"total_tokens": 18535,
"prompt_tokens_details": {
"cached_tokens": 108,
"audio_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 1401
}
}
}