Using Pydantic with Z.AI: GLM 4.6 on OpenRouter

This tutorial explains how to use a Pydantic schema to extract structured data using Z.AI: GLM 4.6.

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 = 'z-ai/glm-4.6'
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 vaccination date was 6/30/99"
    },
    "regression_onset_date": {
      "year": 1999,
      "month": 11,
      "citations": [146, 147],
      "explanation": "Regression began between 21-23 months of age"
    },
    "diagnosis_date": {
      "year": 2001,
      "month": 1,
      "citations": [98, 150],
      "explanation": "Diagnosed with autism in January 2001"
    },
    "age_at_vaccination_months": {
      "value": 16,
      "citations": [3],
      "explanation": "Age was 1.33 years (16 months) at vaccination"
    },
    "age_at_diagnosis_months": {
      "value": 35,
      "citations": [98, 150],
      "explanation": "Diagnosed at approximately 35 months old"
    }
  },
  "developmental_milestones": [
    {
      "milestone_name": {
        "value": "sitting_without_support",
        "citations": [41],
        "explanation": "Sat without support at 8 months"
      },
      "milestone_type": "adaptive_behavior",
      "milestone_age_in_months": {
        "value": 8,
        "citations": [41]
      },
      "milestone_has_regressed": {
        "value": false,
        "citations": [],
        "explanation": "No regression reported for sitting"
      },
      "regression_start_date_in_months": {
        "value": null,
        "citations": []
      },
      "progressed_after_regression": {
        "value": null,
        "citations": []
      }
    },
    {
      "milestone_name": {
        "value": "walking",
        "citations": [41],
        "explanation": "Walked by 12 months"
      },
      "milestone_type": "adaptive_behavior",
      "milestone_age_in_months": {
        "value": 12,
        "citations": [41]
      },
      "milestone_has_regressed": {
        "value": false,
        "citations": [],
        "explanation": "No regression reported for walking"
      },
      "regression_start_date_in_months": {
        "value": null,
        "citations": []
      },
      "progressed_after_regression": {
        "value": null,
        "citations": []
      }
    },
    {
      "milestone_name": {
        "value": "single_words",
        "citations": [41],
        "explanation": "Started saying single words at 17 months"
      },
      "milestone_type": "language",
      "milestone_age_in_months": {
        "value": 17,
        "citations": [41]
      },
      "milestone_has_regressed": {
        "value": true,
        "citations": [110, 111],
        "explanation": "Language use decreased after initial development"
      },
      "regression_start_date_in_months": {
        "value": 21,
        "citations": [146, 147]
      },
      "progressed_after_regression": {
        "value": false,
        "citations": [160, 162],
        "explanation": "Autism persisted as of July 2002"
      }
    },
    {
      "milestone_name": {
        "value": "joint_attention",
        "citations": [108, 110],
        "explanation": "Initially had joint attention but it decreased"
      },
      "milestone_type": "social_communication",
      "milestone_age_in_months": {
        "value": 18,
        "citations": [108, 110]
      },
      "milestone_has_regressed": {
        "value": true,
        "citations": [110, 111],
        "explanation": "Joint attention behaviors decreased in frequency"
      },
      "regression_start_date_in_months": {
        "value": 21,
        "citations": [146, 147]
      },
      "progressed_after_regression": {
        "value": false,
        "citations": [160, 162],
        "explanation": "Autism persisted as of July 2002"
      }
    },
    {
      "milestone_name": {
        "value": "pointing",
        "citations": [117],
        "explanation": "Pointed at objects but often needed prompting"
      },
      "milestone_type": "social_communication",
      "milestone_age_in_months": {
        "value": 20,
        "citations": [117]
      },
      "milestone_has_regressed": {
        "value": true,
        "citations": [110],
        "explanation": "Use of gestures decreased over time"
      },
      "regression_start_date_in_months": {
        "value": 21,
        "citations": [146, 147]
      },
      "progressed_after_regression": {
        "value": false,
        "citations": [160, 162],
        "explanation": "Autism persisted as of July 2002"
      }
    }
  ],
  "regression_record": {
    "pre_regression_language_level": {
      "value": "babbling_single_words",
      "citations": [41, 114],
      "explanation": "Used single words before regression"
    },
    "pre_regression_social_communication_level": {
      "value": "reciprocal_interaction",
      "citations": [108, 109],
      "explanation": "Had reciprocal interaction before regression"
    },
    "pre_regression_adaptive_behavior_level": {
      "value": "basic_self_help",
      "citations": [41],
      "explanation": "Basic self-help skills present before regression"
    },
    "post_regression_language_level": {
      "value": "babbling_single_words",
      "citations": [114],
      "explanation": "Limited to single words after regression"
    },
    "post_regression_social_communication_level": {
      "value": "basic_engagement",
      "citations": [110, 111],
      "explanation": "Basic engagement but decreased social skills"
    },
    "post_regression_adaptive_behavior_level": {
      "value": "basic_self_help",
      "citations": [140],
      "explanation": "Basic self-help skills maintained"
    },
    "has_language_loss": {
      "value": true,
      "citations": [110, 111],
      "explanation": "Language use and joint attention decreased"
    },
    "has_social_loss": {
      "value": true,
      "citations": [110, 111],
      "explanation": "Interest in playing with other children decreased"
    },
    "has_adaptive_loss": {
      "value": false,
      "citations": [140],
      "explanation": "Self-care skills slightly below average but not lost"
    },
    "has_repetitive_behaviors": {
      "value": true,
      "citations": [126],
      "explanation": "Started lining up toys and objects"
    }
  },
  "early_vaccination_symptoms": null,
  "diagnosis_record": {
    "asd_severity": {
      "value": 2,
      "citations": [151],
      "explanation": "Rated in 'moderate' autism category"
    },
    "diagnosis_name": [
      {
        "value": "Autism",
        "citations": [150],
        "explanation": "Diagnosed with autism by autism resource center"
      },
      {
        "value": "Mixed Expressive Receptive Language Disorder",
        "citations": [96],
        "explanation": "Initial diagnosis before autism diagnosis"
      }
    ],
    "diagnosing_professional": [
      {
        "value": "Psychologist at autism resource center",
        "citations": [98],
        "explanation": "Psychologist at tertiary care center autism resource center"
      }
    ]
  },
  "intervention_record": {
    "interventions": [
      {
        "value": "speech_therapy",
        "citations": [76, 86],
        "explanation": "Speech therapy recommended and initiated"
      },
      {
        "value": "occupational_therapy",
        "citations": [143],
        "explanation": "Occupational therapy recommended"
      },
      {
        "value": "aba",
        "citations": [154],
        "explanation": "Applied behavioral analysis recommended"
      },
      {
        "value": "social_skills",
        "citations": [77],
        "explanation": "Social skills through daycare recommended"
      }
    ],
    "is_intervention_ongoing": {
      "value": true,
      "citations": [149],
      "explanation": "Recently began receiving speech therapy and special instruction"
    },
    "has_recovery": {
      "value": false,
      "citations": [160, 162],
      "explanation": "Autism persisted as of July 2002"
    }
  },
  "birth_record": {
    "was_normal_pre_vaccination": {
      "value": false,
      "citations": [24, 40],
      "explanation": "Born premature at 31.5 weeks with motor milestones not within normal limits"
    },
    "apgar_score": [
      {
        "value": "8",
        "citations": [29],
        "explanation": "APGAR score at one minute"
      },
      {
        "value": "9",
        "citations": [29],
        "explanation": "APGAR score at five minutes"
      }
    ]
  },
  "behavior_record": {
    "repetitive_behaviors": [
      {
        "value": "Lining up toys and objects",
        "citations": [126],
        "explanation": "Recently began demonstrating lining up toys behavior"
      }
    ]
  },
  "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": false,
      "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": [20]
    },
    {
      "metal_type": "berium",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [20]
    },
    {
      "metal_type": "chromium",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [20]
    },
    {
      "metal_type": "copper",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [20]
    },
    {
      "metal_type": "gallium",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [20]
    },
    {
      "metal_type": "manganese",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [20]
    },
    {
      "metal_type": "nickel",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [20]
    },
    {
      "metal_type": "platinum",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [20]
    },
    {
      "metal_type": "rubidium",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [20]
    },
    {
      "metal_type": "selenium",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [20]
    },
    {
      "metal_type": "thallium",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [20]
    },
    {
      "metal_type": "tin",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [20]
    },
    {
      "metal_type": "titanium",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [20]
    },
    {
      "metal_type": "tungsten",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [20]
    },
    {
      "metal_type": "uranium",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [20]
    },
    {
      "metal_type": "zinc",
      "value": null,
      "unit": null,
      "is_elevated": true,
      "citations": [20]
    }
  ],
  "comorbidities": [
    {
      "value": "other",
      "citations": [155],
      "explanation": "Pneumonia, reactive airway disease, otitis media"
    }
  ],
  "environmental_exposures": [
    {
      "value": "other_mercury",
      "citations": [45],
      "explanation": "Exposure to thimerosol 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": 47.972068786621094,
  "usage": {
    "prompt_tokens": 13497,
    "completion_tokens": 3629,
    "total_tokens": 17126,
    "prompt_tokens_details": {
      "cached_tokens": 0
    }
  }
}

Leave a Reply