|

Using Pydantic with Qwen3 Max Instruct on OpenRouter

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

Please read this tutorial first to understand the basic setup

Code:

import os
import json
import requests
import datetime
from inputs import get_input_text
from system import system_instruction_1 as system_instruction
from schema import VAERSReport
from dotenv import load_dotenv
import time
load_dotenv()
model_name = 'qwen/qwen3-max'
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": [42],
      "explanation": "Last dose of Hepatitis B (Engerix-B) administered on 1999-06-30 per paragraph [42]."
    },
    "regression_onset_date": {
      "year": 2001,
      "month": 10,
      "citations": [146, 147],
      "explanation": "Parents reported regression began between 21-23 months of age; child was born in late December 1998 (31.5 weeks gestation), so 21-23 months corresponds to approx. Oct-Nov 2000; however, paragraph [150] references autism diagnosis 'recently' as of Feb 2001, and paragraph [126] notes new behaviors 'very recently' as of Oct 2000 evaluation. For conservative estimate aligned with [146], we use 22 months => Oct 2000 (age-adjusted would be ~20 months, but parent-reported chronological age used here). However, [150] says 'recently diagnosed' on 2/13/01, and [146] says regression started 21-23 months, so midpoint 22 months = Oct 2000. But [160] and [162] indicate autism persisted as of July 2002, but do not clarify onset. We choose October 2000 as best estimate."
    },
    "diagnosis_date": {
      "year": 2001,
      "month": 2,
      "citations": [150],
      "explanation": "Autism diagnosis reported on 2/13/01 per [150]."
    },
    "age_at_vaccination_months": {
      "value": 6.0,
      "citations": [42],
      "explanation": "Child born ~Dec 1998 (31.5 weeks gestation, delivered ~Dec 23, 1998); vaccinated on 1999-06-30 → ~6 months old."
    },
    "age_at_diagnosis_months": {
      "value": 26,
      "citations": [150],
      "explanation": "Diagnosed Feb 2001; born Dec 1998 → ~26 months old."
    }
  },
  "developmental_milestones": [
    {
      "milestone_name": {
        "value": "single_words",
        "citations": [41],
        "explanation": "Started saying a few single words at ~17 months chronological (15 adjusted)."
      },
      "milestone_type": "language",
      "milestone_age_in_months": {
        "value": 17,
        "citations": [41],
        "explanation": "Chronological age reported."
      },
      "milestone_has_regressed": {
        "value": true,
        "citations": [110, 111, 115, 123],
        "explanation": "Parents reported decrease in joint attention, social play, and spontaneous speech."
      },
      "regression_start_date_in_months": {
        "value": 22,
        "citations": [146, 147],
        "explanation": "Regression reported between 21-23 months; midpoint used."
      },
      "progressed_after_regression": {
        "value": false,
        "citations": [160, 162],
        "explanation": "Autism persisted as of July 2002; no recovery noted."
      }
    },
    {
      "milestone_name": {
        "value": "walking",
        "citations": [41],
        "explanation": "Walked by 12 months chronological (10 adjusted)."
      },
      "milestone_type": "adaptive_behavior",
      "milestone_age_in_months": {
        "value": 12,
        "citations": [41],
        "explanation": "Chronological age."
      },
      "milestone_has_regressed": {
        "value": false,
        "citations": [],
        "explanation": "No motor regression reported."
      },
      "regression_start_date_in_months": {
        "value": null,
        "citations": null,
        "explanation": null
      },
      "progressed_after_regression": {
        "value": null,
        "citations": null,
        "explanation": null
      }
    },
    {
      "milestone_name": {
        "value": "joint_attention",
        "citations": [110, 116, 117],
        "explanation": "Previously used gestures and initiated joint attention, but frequency decreased."
      },
      "milestone_type": "social_communication",
      "milestone_age_in_months": {
        "value": 18,
        "citations": [110],
        "explanation": "Implied prior to regression at ~22 months."
      },
      "milestone_has_regressed": {
        "value": true,
        "citations": [110, 111],
        "explanation": "Parents noted decline in joint attention behaviors."
      },
      "regression_start_date_in_months": {
        "value": 22,
        "citations": [146, 147],
        "explanation": "Aligned with reported regression window."
      },
      "progressed_after_regression": {
        "value": false,
        "citations": [160, 162],
        "explanation": "No recovery documented."
      }
    },
    {
      "milestone_name": {
        "value": "pretend_play",
        "citations": [121, 122, 123],
        "explanation": "Demonstrated beginning pretend play during evaluation, but parents reported significant decrease recently."
      },
      "milestone_type": "social_communication",
      "milestone_age_in_months": {
        "value": 20,
        "citations": [123],
        "explanation": "Reported as prior behavior before recent decline (~20 months)."
      },
      "milestone_has_regressed": {
        "value": true,
        "citations": [123],
        "explanation": "Play decreased significantly in weeks before Oct 2000 evaluation."
      },
      "regression_start_date_in_months": {
        "value": 22,
        "citations": [146, 147],
        "explanation": "Consistent with overall regression timeline."
      },
      "progressed_after_regression": {
        "value": false,
        "citations": [160, 162],
        "explanation": "No recovery noted."
      }
    }
  ],
  "regression_record": {
    "pre_regression_language_level": {
      "value": "babbling_single_words",
      "citations": [41, 115],
      "explanation": "Used single words like 'car', 'choo choo', 'hi dada' before regression."
    },
    "pre_regression_social_communication_level": {
      "value": "reciprocal_interaction",
      "citations": [103, 104, 105, 109, 110],
      "explanation": "Showed social engagement, responded to name, greeted father, played with brothers."
    },
    "pre_regression_adaptive_behavior_level": {
      "value": "moderate_independence",
      "citations": [41, 125],
      "explanation": "Walked, played with puzzles/books, self-fed to some extent."
    },
    "post_regression_language_level": {
      "value": "babbling_single_words",
      "citations": [114, 115],
      "explanation": "Still used some single words but not flexible phrase speech; primarily grunting/screaming."
    },
    "post_regression_social_communication_level": {
      "value": "basic_engagement",
      "citations": [108, 113, 116],
      "explanation": "Responded to name, showed objects with eye contact, but limited joint attention and social reciprocity."
    },
    "post_regression_adaptive_behavior_level": {
      "value": "basic_self_help",
      "citations": [128, 140],
      "explanation": "Daily living and motor skills rated ~15 months; required support."
    },
    "has_language_loss": {
      "value": true,
      "citations": [110, 115, 118, 119, 120],
      "explanation": "Parents noted reduced spontaneous speech; receptive/expression delays noted."
    },
    "has_social_loss": {
      "value": true,
      "citations": [110, 111, 123],
      "explanation": "Decreased joint attention, social play, and interaction with peers."
    },
    "has_adaptive_loss": {
      "value": true,
      "citations": [127, 128, 141, 142],
      "explanation": "Adaptive behavior in 'Borderline Impaired range'; sensory processing issues affected self-care."
    },
    "has_repetitive_behaviors": {
      "value": true,
      "citations": [126, 148, 151],
      "explanation": "Began lining up toys; rated 'moderate' autism on ATEC due to repetitive behaviors."
    }
  },
  "early_vaccination_symptoms": null,
  "diagnosis_record": {
    "asd_severity": {
      "value": 2,
      "citations": [151],
      "explanation": "Rated 'moderate' autism on Autism Treatment Evaluation Checklist."
    },
    "diagnosis_name": [
      {
        "value": "Autism",
        "citations": [150],
        "explanation": "Mother reported recent autism diagnosis."
      },
      {
        "value": "Mixed Expressive Receptive Language Disorder",
        "citations": [96, 130],
        "explanation": "Diagnosed by psychologists."
      }
    ],
    "diagnosing_professional": [
      {
        "value": "Autism resource center psychologist",
        "citations": [150],
        "explanation": "Diagnosis reported from autism resource center."
      }
    ]
  },
  "intervention_record": {
    "interventions": [
      {
        "value": "speech_therapy",
        "citations": [76, 86, 149, 154],
        "explanation": "Recommended and initiated."
      },
      {
        "value": "occupational_therapy",
        "citations": [143, 154],
        "explanation": "Recommended and initiated."
      },
      {
        "value": "aba",
        "citations": [154],
        "explanation": "Intensive early intervention using applied behavioral analysis recommended."
      }
    ],
    "is_intervention_ongoing": {
      "value": true,
      "citations": [154, 160],
      "explanation": "Interventions recommended as ongoing; autism persisted as of 2002."
    },
    "has_recovery": {
      "value": false,
      "citations": [11, 160, 162],
      "explanation": "Report states 'Recovered? No'; autism persisted as of July 2002."
    }
  },
  "birth_record": {
    "was_normal_pre_vaccination": {
      "value": true,
      "citations": [33, 40, 54, 58, 63, 65, 146],
      "explanation": "Neurobehavioral assessments appropriate for age; mother reported normal development until 21-23 months; neonatologist noted good development except mild language delay possibly due to prematurity."
    },
    "apgar_score": [
      {
        "value": "8 and 9 at 1 and 5 minutes",
        "citations": [29],
        "explanation": "Reported Aspar (APGAR) scores."
      }
    ]
  },
  "behavior_record": {
    "repetitive_behaviors": [
      {
        "value": "lining up toys and objects (e.g., blocks, chairs)",
        "citations": [126, 148],
        "explanation": "New behavior reported shortly after Oct 2000 evaluation."
      }
    ]
  },
  "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": "allergies",
      "citations": [17],
      "explanation": "Allergies listed under medical history."
    },
    {
      "value": "other",
      "citations": [32, 39, 40],
      "explanation": "Includes gastroesophageal reflux, otitis media, prematurity-related conditions."
    }
  ],
  "environmental_exposures": [
    {
      "value": "other_mercury",
      "citations": [45, 46],
      "explanation": "Mother alleged injury due to thimerosal and mercury in vaccines."
    }
  ],
  "legal_matter": {
    "value": true,
    "citations": [22],
    "explanation": "Report received as part of litigation proceedings."
  },
  "diagnosis_reporting_delay_reason": null
}
```

Metrics

{
  "elapsed": 95.87803983688354,
  "usage": {
    "prompt_tokens": 13919,
    "completion_tokens": 3249,
    "total_tokens": 17168
  }
}

Leave a Reply