Structured Outputs

Open In Colab Download .ipynb

Set the OpenRouter API Key from Colab Secrets

from google.colab import userdata
OPENROUTER_API_KEY = userdata.get('OPENROUTER_API_KEY')

(Or grab the OpenRouter API key if running locally)

import os
from dotenv import load_dotenv
load_dotenv()

OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY")

Create the OpenAI client with OpenRouter URL

import openai

# Initialize the OpenAI client with event hooks
client = openai.OpenAI(
    base_url='https://openrouter.ai/api/v1',
    api_key=OPENROUTER_API_KEY,
)

Create the “Location” type

from pydantic import BaseModel

# Define the model for a geographic location
class Location(BaseModel):
  name: str
  country: str
  latitude: float
  longitude: float

Send request with response_format set

MODEL = 'openai/gpt-5.2-chat' #@param ["openai/gpt-5.2-chat", "anthropic/claude-sonnet-4.5", "google/gemini-2.5-pro"]

response = client.chat.completions.parse(
    model=MODEL,
    messages=[
        {"role": "user", "content": "What are the GPS coordinates for Paris?"},
    ],
    response_format=Location
)

completion = response.choices[0].message
print(completion)
ParsedChatCompletionMessage[Location](content='{"name":"Paris","country":"France","latitude":48.8566,"longitude":2.3522}', refusal=None, role='assistant', annotations=None, audio=None, function_call=None, tool_calls=None, parsed=Location(name='Paris', country='France', latitude=48.8566, longitude=2.3522), reasoning=None)
# Display the JSON repesentation
print(completion.content)

# Display the parsed type
print(completion.parsed)

# Pretty-print
if completion.parsed:
  location: Location = completion.parsed
  print(f"{location.name}, {location.country} has GPS coordinates of {location.latitude}, {location.longitude}")
{"name":"Paris","country":"France","latitude":48.8566,"longitude":2.3522}
name='Paris' country='France' latitude=48.8566 longitude=2.3522
Paris, France has GPS coordinates of 48.8566, 2.3522