|

Using Pydantic with DeepSeek V3.1 Terminus on OpenRouter

This tutorial explains how to use a Pydantic schema to extract structured data using DeepSeek V3.1 Terminus.

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 = 'deepseek/deepseek-v3.1-terminus'
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],
      "explanation": "Vaccination date is explicitly listed as 1999-06-30"
    },
    "regression_onset_date": null,
    "diagnosis_date": {
      "year": 2001,
      "month": 1,
      "citations": [98],
      "explanation": "Evaluation on 1/4/01 led to diagnosis of autism"
    },
    "age_at_vaccination_months": {
      "value": 16,
      "citations": [3],
      "explanation": "Age at vaccination is given as 1.33 years, which is approximately 16 months"
    },
    "age_at_diagnosis_months": {
      "value": 25,
      "citations": [61, 98],
      "explanation": "Age estimated from evaluations: 20 months chrono on 8/22/00, diagnosis around 1/4/01 gives approximately 25 months"
    }
  },
  "developmental_milestones": [
    {
      "milestone_name": {
        "value": "sitting_without_support",
        "citations": [41],
        "explanation": "Sat without support at 8 months chronological age"
      },
      "milestone_type": "adaptive_behavior",
      "milestone_age_in_months": {
        "value": 8,
        "citations": [41],
        "explanation": "Achieved at 8 months chronological age"
      },
      "milestone_has_regressed": {
        "value": false,
        "citations": [41],
        "explanation": "No reported regression of sitting ability"
      },
      "regression_start_date_in_months": null,
      "progressed_after_regression": {
        "value": false,
        "citations": [41],
        "explanation": "Not applicable as no regression occurred"
      }
    },
    {
      "milestone_name": {
        "value": "walking",
        "citations": [41],
        "explanation": "Walked by 12 months chronological age"
      },
      "milestone_type": "adaptive_behavior",
      "milestone_age_in_months": {
        "value": 12,
        "citations": [41],
        "explanation": "Achieved by 12 months chronological age"
      },
      "milestone_has_regressed": {
        "value": false,
        "citations": [41],
        "explanation": "No reported regression of walking ability"
      },
      "regression_start_date_in_months": null,
      "progressed_after_regression": {
        "value": false,
        "citations": [41],
        "explanation": "Not applicable as no regression occurred"
      }
    },
    {
      "milestone_name": {
        "value": "single_words",
        "citations": [41],
        "explanation": "Started saying a few single words at around 17 months chronological age"
      },
      "milestone_type": "language",
      "milestone_age_in_months": {
        "value": 17,
        "citations": [41],
        "explanation": "Achieved at approximately 17 months chronological age"
      },
      "milestone_has_regressed": {
        "value": true,
        "citations": [146],
        "explanation": "Language regression reported between 21-23 months"
      },
      "regression_start_date_in_months": {
        "value": 22,
        "citations": [146],
        "explanation": "Regression onset around 21-23 months, approximated to 22 months"
      },
      "progressed_after_regression": {
        "value": false,
        "citations": [160],
        "explanation": "Autism and language issues persisted with no recovery reported"
      }
    }
  ],
  "regression_record": {
    "pre_regression_language_level": {
      "value": "babbling_single_words",
      "citations": [41],
      "explanation": "Had single words at 17 months before regression"
    },
    "pre_regression_social_communication_level": {
      "value": "basic_engagement",
      "citations": [108],
      "explanation": "Responded to name and shared interest before regression"
    },
    "pre_regression_adaptive_behavior_level": {
      "value": "moderate_independence",
      "citations": [41, 53],
      "explanation": "Achieved motor milestones and had age-appropriate adaptive skills early on"
    },
    "post_regression_language_level": {
      "value": "babbling_single_words",
      "citations": [84, 115],
      "explanation": "Post-regression, language limited to single words with delays"
    },
    "post_regression_social_communication_level": {
      "value": "basic_engagement",
      "citations": [108, 113],
      "explanation": "Social skills impaired, with reduced eye contact and interaction"
    },
    "post_regression_adaptive_behavior_level": {
      "value": "basic_self_help",
      "citations": [95, 128],
      "explanation": "Adaptive behavior scored below age level post-regression"
    },
    "has_language_loss": {
      "value": true,
      "citations": [146],
      "explanation": "Language regression reported with loss of skills"
    },
    "has_social_loss": {
      "value": true,
      "citations": [110, 111],
      "explanation": "Social behaviors decreased frequency post-regression"
    },
    "has_adaptive_loss": {
      "value": true,
      "citations": [128],
      "explanation": "Adaptive behavior declined post-regression"
    },
    "has_repetitive_behaviors": {
      "value": true,
      "citations": [126],
      "explanation": "Observed lining up toys repetitively"
    }
  },
  "early_vaccination_symptoms": {
    "had_autism_features": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "Autism onset reported much later than 30 days post-vaccination"
    },
    "had_fever": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "No fever reported within 30 days of vaccination"
    },
    "had_speech_loss": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "Speech loss occurred later, not within 30 days"
    },
    "had_irritability": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "No irritability reported within 30 days"
    },
    "had_eye_contact_loss": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "Eye contact loss reported later, not within 30 days"
    },
    "had_diarrhea": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "No diarrhea reported within 30 days"
    },
    "had_seizures": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "No seizures reported within 30 days"
    },
    "had_lethargy": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "No lethargy reported within 30 days"
    },
    "had_screaming": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "Screaming reported later in context of frustration, not within 30 days"
    },
    "had_behavioral_changes": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "Behavioral changes occurred later, not within 30 days"
    },
    "had_rash": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "No rash reported within 30 days"
    },
    "had_head_banging": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "No head banging reported within 30 days"
    },
    "had_social_withdrawal": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "Social withdrawal reported later, not within 30 days"
    },
    "had_injection_site_reaction": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "No injection site reaction reported within 30 days"
    },
    "had_balance_loss": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "No balance loss reported within 30 days"
    },
    "had_appetite_loss": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "No appetite loss reported within 30 days"
    },
    "had_staring_spells": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "No staring spells reported within 30 days"
    },
    "had_hand_flapping": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "No hand flapping reported within 30 days"
    },
    "had_toe_walking": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "No toe walking reported within 30 days"
    },
    "had_gastrointestinal_problems": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "GI problems like reflux were preexisting, not new within 30 days"
    },
    "had_hyperactivity": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "No hyperactivity reported within 30 days"
    },
    "had_ear_infections": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "Ear infections occurred later, not within 30 days"
    },
    "had_vomiting": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "No vomiting reported within 30 days"
    },
    "had_sleep_problems": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "No sleep problems reported within 30 days"
    },
    "had_encephalopathy": {
      "value": false,
      "ongoing": false,
      "days_to_symptom_onset": null,
      "citations": [3],
      "explanation": "No encephalopathy reported within 30 days"
    }
  },
  "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": "Diagnosed by psychologist"
      }
    ],
    "diagnosing_professional": [
      {
        "value": "autism resource center",
        "citations": [150],
        "explanation": "Made autism diagnosis"
      },
      {
        "value": "psychologist",
        "citations": [96, 98],
        "explanation": "Conducted evaluations and diagnoses"
      }
    ]
  },
  "intervention_record": {
    "interventions": [
      {
        "value": "speech_therapy",
        "citations": [77, 86],
        "explanation": "Speech therapy recommended multiple times"
      },
      {
        "value": "occupational_therapy",
        "citations": [143],
        "explanation": "Occupational therapy recommended"
      },
      {
        "value": "aba",
        "citations": [154],
        "explanation": "Applied behavioral analysis recommended"
      },
      {
        "value": "social_skills",
        "citations": [77, 154],
        "explanation": "Social skills training recommended"
      },
      {
        "value": "other",
        "citations": [78, 79],
        "explanation": "Behavior modifications and special instruction recommended"
      }
    ],
    "is_intervention_ongoing": {
      "value": true,
      "citations": [154],
      "explanation": "Interventions were recommended and likely ongoing"
    },
    "has_recovery": {
      "value": false,
      "citations": [11, 160],
      "explanation": "No recovery reported; autism persisted"
    }
  },
  "birth_record": {
    "was_normal_pre_vaccination": {
      "value": false,
      "citations": [24, 32],
      "explanation": "Had preexisting conditions from birth, including prematurity complications"
    },
    "apgar_score": [
      {
        "value": "8 at 1 minute, 9 at 5 minutes",
        "citations": [29],
        "explanation": "Apgar scores provided at birth"
      }
    ]
  },
  "behavior_record": {
    "repetitive_behaviors": [
      {
        "value": "lining up toys and objects",
        "citations": [126],
        "explanation": "Observed lining up blocks, chairs, etc."
      },
      {
        "value": "repetitive language use",
        "citations": [148],
        "explanation": "Used language repetitively"
      }
    ]
  },
  "heavy_metal_tests": [
    {
      "metal_type": "lead",
      "value": 16,
      "unit": "ug/L",
      "is_elevated": false,
      "citations": [20],
      "explanation": "Urine lead level within reference range (0-79 ug/L)"
    },
    {
      "metal_type": "arsenic",
      "value": 60,
      "unit": "ug/L",
      "is_elevated": false,
      "citations": [20],
      "explanation": "Urine arsenic level within reference range (0-99 ug/L)"
    },
    {
      "metal_type": "mercury",
      "value": 10,
      "unit": "ug/L",
      "is_elevated": false,
      "citations": [20],
      "explanation": "Urine mercury level less than 10 ug/L, within reference range (0-19.9 ug/L)"
    }
  ],
  "comorbidities": [
    {
      "value": "other",
      "citations": [32],
      "explanation": "Preexisting conditions include gastroesophageal reflux, apnea, etc."
    }
  ],
  "environmental_exposures": [
    {
      "value": "unknown",
      "citations": [20],
      "explanation": "No specific environmental exposures reported"
    }
  ],
  "legal_matter": {
    "value": true,
    "citations": [22],
    "explanation": "Report received as part of litigation proceedings"
  },
  "diagnosis_reporting_delay_reason": {
    "value": "litigation proceedings",
    "citations": [22],
    "explanation": "Delay likely due to legal context of the report"
  }
}
```

Metrics

{
  "elapsed": 164.05108404159546,
  "usage": {
    "prompt_tokens": 13586,
    "completion_tokens": 13255,
    "total_tokens": 26841,
    "prompt_tokens_details": null,
    "completion_tokens_details": null
  }
}

Leave a Reply