|

Using Pydantic with Qwen3 Coder Plus on OpenRouter

This tutorial explains how to use a Pydantic schema to extract structured data using Qwen3 Coder Plus.

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-plus'
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": "Child received Engerix B on 1/24/99, 2/15/99, and 6/30/99. The last vaccination was on 6/30/99."
    },
    "regression_onset_date": {
      "year": 2000,
      "month": 3,
      "citations": [45],
      "explanation": "In the spring of 2000, the subject 'suffered neurologic damage as a result of exposure to thimerosol and mercury contained in the various vaccines which were administered.' This marks the reported onset of regression/autism symptoms."
    },
    "diagnosis_date": {
      "year": 2001,
      "month": 1,
      "citations": [98],
      "explanation": "The subject was evaluated by a 2nd psychologist on 1/4/01 at the 'autism resource center' of a tertiary care center."
    },
    "age_at_vaccination_months": {
      "value": 10.5,
      "citations": [37, 42],
      "explanation": "The child was born at 31.5 weeks gestation and was discharged 6 weeks after birth. Vaccinations started at about 2 months corrected age (24/7 = ~3.4 months), with the last set at 6/30/99 (which would be about 10.5 months corrected age considering birth at 31.5 weeks + 6 weeks NICU stay)."
    },
    "age_at_diagnosis_months": {
      "value": 18,
      "citations": [99],
      "explanation": "His parents became concerned about his development at around 18 months because his language appeared delayed. The formal evaluation for autism was conducted at age 20 months (adjusted age 18 months) but concerns and potential diagnosis started at 18 months."
    }
  },
  "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": "The subject sat without support at 8 months (6 months adjusted for prematurity)."
      },
      "milestone_has_regressed": {
        "value": false,
        "citations": [],
        "explanation": "There is no explicit mention that sitting ability regressed."
      },
      "regression_start_date_in_months": {
        "value": null,
        "citations": [],
        "explanation": null
      },
      "progressed_after_regression": {
        "value": false,
        "citations": [],
        "explanation": "Not applicable since sitting milestone did not regress."
      }
    },
    {
      "milestone_name": {
        "value": "walking",
        "citations": [41],
        "explanation": "Subject walked by 12 months (10 months adjusted for prematurity)."
      },
      "milestone_type": "adaptive_behavior",
      "milestone_age_in_months": {
        "value": 12,
        "citations": [41],
        "explanation": "The subject walked by 12 months (10 months adjusted for prematurity)."
      },
      "milestone_has_regressed": {
        "value": false,
        "citations": [],
        "explanation": "There is no explicit mention that walking ability regressed."
      },
      "regression_start_date_in_months": {
        "value": null,
        "citations": [],
        "explanation": null
      },
      "progressed_after_regression": {
        "value": false,
        "citations": [],
        "explanation": "Not applicable since walking milestone did not regress."
      }
    },
    {
      "milestone_name": {
        "value": "single_words",
        "citations": [41],
        "explanation": "Started saying a few single words at around age 17 months (15 months adjusted)."
      },
      "milestone_type": "language",
      "milestone_age_in_months": {
        "value": 17,
        "citations": [41],
        "explanation": "Started saying a few single words at around age 17 months (15 months adjusted for prematurity)."
      },
      "milestone_has_regressed": {
        "value": true,
        "citations": [147],
        "explanation": "The mother reported that between 21-23 months, the subject began to develop symptoms of developmental delay and autism including difficulty with speech. Previously acquired speech skills were lost."
      },
      "regression_start_date_in_months": {
        "value": 22,
        "citations": [146, 147],
        "explanation": "Mother reported the child developed normally for the first 21-23 months. Regression of speech began around this time."
      },
      "progressed_after_regression": {
        "value": false,
        "citations": [],
        "explanation": "There is no indication that speech progressed after the regression."
      }
    },
    {
      "milestone_name": {
        "value": "eye_contact",
        "citations": [107],
        "explanation": "Parental report that the subject showed a 'good range of facial expression' indicates intact eye contact."
      },
      "milestone_type": "social_communication",
      "milestone_age_in_months": {
        "value": null,
        "citations": [],
        "explanation": "The specific age of acquiring eye contact is not mentioned in the report."
      },
      "milestone_has_regressed": {
        "value": true,
        "citations": [110, 127],
        "explanation": "Parents reported that some of the good social behaviors (such as eye contact) no longer happened with the same frequency at home. At 20 months, his social developmental age was assessed at 10 months."
      },
      "regression_start_date_in_months": {
        "value": 22,
        "citations": [146,147],
        "explanation": "Parents noticed decrease in socialization skills about the time the child was 21-23 months old."
      },
      "progressed_after_regression": {
        "value": false,
        "citations": [],
        "explanation": "There is no indication that social communication/eye contact progressed after the regression."
      }
    },
    {
      "milestone_name": {
        "value": "responding_to_name",
        "citations": [108],
        "explanation": "The subject responded to his name during the evaluation."
      },
      "milestone_type": "social_communication",
      "milestone_age_in_months": {
        "value": null,
        "citations": [],
        "explanation": "The specific age of responding to name is not mentioned in the report."
      },
      "milestone_has_regressed": {
        "value": true,
        "citations": [110],
        "explanation": "Parents reported that some of the good social behaviors (which would include responding to name) no longer happened with the same frequency at home."
      },
      "regression_start_date_in_months": {
        "value": 22,
        "citations": [146,147],
        "explanation": "Regression noticed around 21-23 months of age."
      },
      "progressed_after_regression": {
        "value": false,
        "citations": [],
        "explanation": "There is no indication that responding to name progressed after the regression."
      }
    },
    {
      "milestone_name": {
        "value": "pointing",
        "citations": [117],
        "explanation": "The subject pointed at objects on occasion during the evaluation, but often had to be prompted to do so."
      },
      "milestone_type": "social_communication",
      "milestone_age_in_months": {
        "value": null,
        "citations": [],
        "explanation": "The specific age of pointing is not mentioned in the report."
      },
      "milestone_has_regressed": {
        "value": true,
        "citations": [123],
        "explanation": "Parents reported that at home he enjoys looking at books and will point to some of the pictures when prompted, but this type of play had decreased significantly recently."
      },
      "regression_start_date_in_months": {
        "value": 22,
        "citations": [146,147],
        "explanation": "Regression noticed around 21-23 months of age."
      },
      "progressed_after_regression": {
        "value": false,
        "citations": [],
        "explanation": "There is no indication that pointing progressed after the regression."
      }
    },
    {
      "milestone_name": {
        "value": "pretend_play",
        "citations": [121],
        "explanation": "The subject demonstrated some beginning pretend play skills during the evaluation in January 2001 (age 20 months)."
      },
      "milestone_type": "social_communication",
      "milestone_age_in_months": {
        "value": 20,
        "citations": [121],
        "explanation": "Demonstrated pretend play at 20 months during the evaluation."
      },
      "milestone_has_regressed": {
        "value": true,
        "citations": [123],
        "explanation": "Parents reported that this type of play (including pretend play with brothers) had decreased significantly in the past several weeks."
      },
      "regression_start_date_in_months": {
        "value": 22,
        "citations": [146,147],
        "explanation": "Regression noticed around 21-23 months of age."
      },
      "progressed_after_regression": {
        "value": false,
        "citations": [],
        "explanation": "There is no indication that pretend play progressed after the regression."
      }
    },
    {
      "milestone_name": {
        "value": "joint_attention",
        "citations": [116],
        "explanation": "The subject showed objects to other people or gave them (with eye contact) when he needed help, indicating joint attention abilities."
      },
      "milestone_type": "social_communication",
      "milestone_age_in_months": {
        "value": null,
        "citations": [],
        "explanation": "The specific age of achieving joint attention is not mentioned in the report."
      },
      "milestone_has_regressed": {
        "value": true,
        "citations": [110],
        "explanation": "Parents reported that some of the good social behaviors he had demonstrated in the past (initiating joint attention) no longer happen with the same frequency at home."
      },
      "regression_start_date_in_months": {
        "value": 22,
        "citations": [146,147],
        "explanation": "Regression noticed around 21-23 months of age."
      },
      "progressed_after_regression": {
        "value": false,
        "citations": [],
        "explanation": "There is no indication that joint attention progressed after the regression."
      }
    }
  ],
  "regression_record": {
    "pre_regression_language_level": {
      "value": "two_word_phrases",
      "citations": [41, 114],
      "explanation": "Before regression, the subject could say single words (like 'car', 'choo choo', 'wasis', 'hi dada', 'bye bye') and repeat phrases like 'sit down'. This is consistent with a two-word phrase level just before regression."
    },
    "pre_regression_social_communication_level": {
      "value": "reciprocal_interaction",
      "citations": [108, 116],
      "explanation": "Before regression, the child responded to his name, engaged in joint attention (showing objects to others), pointed occasionally, and interacted socially with family members. This level reflects reciprocal interactions."
    },
    "pre_regression_adaptive_behavior_level": {
      "value": "moderate_independence",
      "citations": [41, 57],
      "explanation": "The child was walking independently and had age-appropriate gross motor skills. Fine motor skills were assessed at 20-month level. This indicates moderate independence in adaptive behaviors."
    },
    "post_regression_language_level": {
      "value": "babbling_single_words",
      "citations": [83, 114],
      "explanation": "After regression, speech was characterized by grunting and screaming with occasional single words. Some single words were still used but not flexibly or spontaneously."
    },
    "post_regression_social_communication_level": {
      "value": "basic_engagement",
      "citations": [110, 112, 127],
      "explanation": "Socialization skills regressed to a 10-month level (age 20 months). Parents noted decreased interest in playing with other children and limited social awareness, indicating basic engagement rather than reciprocal interaction."
    },
    "post_regression_adaptive_behavior_level": {
      "value": "basic_self_help",
      "citations": [139, 140],
      "explanation": "After regression, fine motor skills were assessed at 20-month level (age 20 months), and self-care skills were slightly below average range according to occupational therapy assessment, indicating basic self-help abilities."
    },
    "has_language_loss": {
      "value": true,
      "citations": [147],
      "explanation": "Mother explicitly reported that between 21-23 months, the subject began to develop symptoms of developmental delay and autism including 'difficulty w/speech'. Previously acquired speech was lost."
    },
    "has_social_loss": {
      "value": true,
      "citations": [110, 123, 127],
      "explanation": "Multiple sources indicate social losses: parents reported decrease in social behaviors (110), decrease in pretend play (123), and social developmental age regressed to 10 months (127)."
    },
    "has_adaptive_loss": {
      "value": true,
      "citations": [147],
      "explanation": "Parental report of the child developing 'symptoms of developmental delay and autism' between 21-23 months indicates loss of previously acquired adaptive skills."
    },
    "has_repetitive_behaviors": {
      "value": true,
      "citations": [148, 126],
      "explanation": "The child exhibited lining up toys and objects (e.g., blocks, chairs in the waiting rooms) instead of playing appropriately, which is a repetitive behavior observed around 21-23 months of age."
    }
  },
  "early_vaccination_symptoms": null,
  "diagnosis_record": {
    "asd_severity": {
      "value": 2,
      "citations": [151],
      "explanation": "Using the Autism Treatment Evaluation Checklist, the subject was rated in the 'moderate' autism category, which corresponds to severity level 2."
    },
    "diagnosis_name": [
      {
        "value": "Autism",
        "citations": [1, 45, 100, 150],
        "explanation": "Reported as 'autism' in VAERS report (1), parental allegation mentions autism due to vaccines (45), evaluation conducted to determine Pervasive Developmental Disorder (100), and formally diagnosed with autism by autism resource center (150)."
      },
      {
        "value": "Mixed Expressive-Receptive Language Disorder",
        "citations": [96, 129],
        "explanation": "Initially diagnosed as Mixed Expressive-Receptive Language Disorder by psychologist (96), but later autism diagnosis supersedes this (129)."
      },
      {
        "value": "Pervasive Developmental Disorder - Not Otherwise Specified",
        "citations": [100, 130],
        "explanation": "Evaluated for Pervasive Developmental Disorder (100), and noted that a Pervasive Developmental Disorder could not be ruled out (130). This typically corresponds to PDD-NOS."
      }
    ],
    "diagnosing_professional": [
      {
        "value": "Psychologist at autism resource center",
        "citations": [98, 150],
        "explanation": "Evaluated by a psychologist at the autism resource center on 1/4/01, and the center made the autism diagnosis (150)."
      }
    ]
  },
  "intervention_record": {
    "interventions": [
      {
        "value": "speech_therapy",
        "citations": [76, 86, 97, 149, 154],
        "explanation": "Speech therapy strongly recommended (76, 86) and later initiated (149) as part of treatment plan."
      },
      {
        "value": "occupational_therapy",
        "citations": [143, 154],
        "explanation": "Occupational therapy recommended (143) and presumably initiated as part of intensive early intervention (154)."
      },
      {
        "value": "aba",
        "citations": [154],
        "explanation": "Recommended intensive early intervention using applied behavioral analysis (154)."
      }
    ],
    "is_intervention_ongoing": {
      "value": true,
      "citations": [159, 161, 162],
      "explanation": "The most recent information received on 10/15/02 did not provide outcomes (159) and outcome of mercury toxicity was not provided (161). Autism persisted as of 15July02 (162), indicating ongoing intervention."
    },
    "has_recovery": {
      "value": false,
      "citations": [160, 162],
      "explanation": "Info received indicated that autism persisted on 10/15/02 (160) and persisted as of 15July02 (162), indicating no recovery."
    }
  },
  "birth_record": {
    "was_normal_pre_vaccination": {
      "value": true,
      "citations": [40, 146],
      "explanation": "Developmental history revealed that 'Motor milestones appear to have been within normal limits' (40) and child developed normally for first 21-23 months (146) before vaccination-induced autism was alleged."
    },
    "apgar_score": [
      {
        "value": "8 at 1 minute",
        "citations": [29],
        "explanation": "The subject's Apgar scores were 8 and 9 at one and five minutes, respectively (29)."
      },
      {
        "value": "9 at 5 minutes",
        "citations": [29],
        "explanation": "The subject's Apgar scores were 8 and 9 at one and five minutes, respectively (29)."
      }
    ]
  },
  "behavior_record": {
    "repetitive_behaviors": [
      {
        "value": "Lining up toys and objects (e.g., blocks, chairs in waiting rooms) instead of playing appropriately",
        "citations": [126, 148],
        "explanation": "Repetitive behavior observed when child demonstrated lining up toys shortly after evaluation (126) and reported by mother as beginning between 21-23 months (148)."
      },
      {
        "value": "Using language repetitively",
        "citations": [148],
        "explanation": "Mother reported repetitive use of language as one of the symptoms that began between 21-23 months (148)."
      }
    ]
  },
  "heavy_metal_tests": [
    {
      "metal_type": "lead",
      "value": 16,
      "unit": "ug/L",
      "is_elevated": false,
      "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]
    },
    {
      "metal_type": "aluminum",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [21]
    },
    {
      "metal_type": "beryllium",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [21]
    },
    {
      "metal_type": "chromium",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [21]
    },
    {
      "metal_type": "copper",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [21]
    },
    {
      "metal_type": "gallium",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [21]
    },
    {
      "metal_type": "manganese",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [21]
    },
    {
      "metal_type": "nickel",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [21]
    },
    {
      "metal_type": "platinum",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [21]
    },
    {
      "metal_type": "rubidium",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [21]
    },
    {
      "metal_type": "selenium",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [21]
    },
    {
      "metal_type": "thallium",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [21]
    },
    {
      "metal_type": "tin",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [21]
    },
    {
      "metal_type": "titanium",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [21]
    },
    {
      "metal_type": "tungsten",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [21]
    },
    {
      "metal_type": "uranium",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [21]
    },
    {
      "metal_type": "zinc",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [21]
    }
  ],
  "comorbidities": [
    {
      "value": "adhd",
      "citations": [],
      "explanation": "Not explicitly mentioned in report."
    },
    {
      "value": "colitis",
      "citations": [],
      "explanation": "Not explicitly mentioned in report, though gastroesophageal reflux is noted."
    },
    {
      "value": "allergies",
      "citations": [],
      "explanation": "Not explicitly mentioned in report."
    },
    {
      "value": "asthma",
      "citations": [155],
      "explanation": "Subject experienced reactive airway disease (155), which is closely related to asthma."
    },
    {
      "value": "eczema",
      "citations": [],
      "explanation": "Not explicitly mentioned in report."
    },
    {
      "value": "seizure_disorder",
      "citations": [],
      "explanation": "Not explicitly mentioned in report."
    },
    {
      "value": "ocd",
      "citations": [],
      "explanation": "Not explicitly mentioned in report."
    },
    {
      "value": "anxiety",
      "citations": [],
      "explanation": "Not explicitly mentioned in report."
    },
    {
      "value": "other",
      "citations": [32, 155],
      "explanation": "Child experienced mixed apnea and bradycardia of prematurity (32), thrombocytopenia, anemia of prematurity, jaundice, feeding intolerance, gastroesophageal reflux (32), reactive airway disease (155), and left otitis media (155)."
    }
  ],
  "environmental_exposures": [],
  "legal_matter": {
    "value": true,
    "citations": [22],
    "explanation": "Explicitly stated that 'This report was received as part of litigation proceedings' (22)."
  },
  "diagnosis_reporting_delay_reason": {
    "value": "Report submitted as part of litigation proceedings",
    "citations": [22],
    "explanation": "The report was submitted in the context of litigation (22), which likely contributed to the delay between diagnosis (January 2001) and reporting (March 2004)."
  }
}

Metrics

{
  "elapsed": 83.33422899246216,
  "usage": {
    "prompt_tokens": 13919,
    "completion_tokens": 5924,
    "total_tokens": 19843,
    "prompt_tokens_details": {
      "cached_tokens": 0
    }
  }
}

Leave a Reply