A customer asks why this month’s invoice is higher than last month’s. The classifier sends the ticket to the billing team, which is correct, but it also marks the ticket urgent. The backend parses the JSON and both values pass the schema. So who decides whether the ticket is really urgent?
This article answers that question step by step. It is written for readers who know basic Python but have not built an LLM feature before.
The idea in plain words
Think of a paper form at a post office. The clerk checks that every box is filled in and that the “delivery type” box says either “standard” or “express”. A neatly filled form is easy to process. But if you tick “express”, the clerk still checks that you actually paid for express. A correctly filled box is not proof that its content is true.
An LLM response works the same way. An LLM (large language model) is the kind of AI model behind chat assistants. You send it text and it sends text back. When a program needs to use that answer, it usually asks for JSON, a simple text format of named fields such as {"queue":"billing"}.
A JSON Schema is a description of what that JSON must look like: which fields are required and which values each field may hold. An enum is a fixed list of allowed values, such as normal or urgent.
OpenAI’s Structured Outputs feature makes the model’s completed answer follow a schema you supply. Structured Outputs documentation The documentation adds two exceptions: an answer the model refused to give, and an answer that was cut off. So you get a well-filled form most of the time. What you do not get is a guarantee that “urgent” is true.
Why it matters
Routing means deciding which team’s queue a ticket goes into. If routing is wrong, a customer waits longer or an on-call engineer gets paged for nothing. Neither problem shows up as an error in your logs, because the JSON was perfectly valid.
The fix is to split the work. The model is good at reading free text and suggesting a team. Facts the model cannot see, such as whether an incident is affecting the account right now, should come from your own systems.
The example setup
The schema has two required fields:
queue: one ofbilling,account, ormanual_review. The last one means “a person on duty decides”.priority:normalorurgent.
The operations team marks a ticket urgent only when a verified incident is affecting the account. Incident status lives in an internal incident tracker. The model never sees it.
So the rule is:
- Keep the queue the model suggests.
- Take the priority from the incident tracker, not from the model.
- If anything is uncertain, send the ticket to
manual_review.
Step-by-step method
All the code below runs in your backend, the server program that receives tickets. It was tested locally with Python 3.13.5 and Pydantic 2.12.5. Pydantic is a Python library that checks data against a class you define. Install it with pip install pydantic. The API call in step 2 also needs pip install openai and an API key.
Step 1: Describe the schema as a Python class
Save this as the top of a file called routing.py:
from typing import Literal
from pydantic import BaseModel
class Classification(BaseModel):
queue: Literal["billing", "account", "manual_review"]
priority: Literal["normal", "urgent"]
MANUAL = ("manual_review", "normal")
Literal[...] is how Pydantic expresses an enum. The class doubles as the JSON Schema sent to the API. MANUAL is the safe fallback decision that later steps reuse.
Step 2: Call the model
The documentation shows a responses.parse method that takes the Pydantic class as text_format:
from openai import OpenAI
client = OpenAI()
response = client.responses.parse(
model=MODEL,
input=[
{"role": "system", "content": "Classify the support ticket."},
{"role": "user", "content": ticket.text},
],
text_format=Classification,
)
queue, priority = route(ticket.id, ticket.account_id, response, incidents, store)
MODEL is the model name you use. ticket, incidents and store come from your own application. This call was not run against the live API for this article. The route function is defined in step 5.
Step 3: Check the response before reading it
The documentation describes two cases where the parsed result should not be trusted:
- Incomplete response.
response.statusis"incomplete".response.incomplete_details.reasontells you why, for example"max_output_tokens". A token is a small chunk of text, and this reason means the output hit its length limit and was cut short, possibly in the middle of the JSON. - Refusal. A refusal is when the model declines to answer, for example for safety reasons. It shows up as a content item with
type == "refusal"and arefusaltext. The guide notes that a refusal does not necessarily follow your schema.
Add this function to routing.py:
def extract(response) -> Classification | None:
# Incomplete output (e.g. reason "max_output_tokens") may be cut off mid-JSON.
if response.status == "incomplete":
return None
for output in response.output:
if output.type != "message":
continue
for item in output.content:
if item.type == "refusal": # a refusal does not follow the schema
return None
return response.output_parsed
It returns None for “do not trust this”, and otherwise the parsed Classification object from output_parsed.
Step 4: Decide the priority from trusted data
Add this to routing.py:
def decide(c: Classification | None, account_id: str, incidents) -> tuple[str, str]:
if c is None or c.queue == "manual_review":
return MANUAL
try:
active = incidents.has_active_incident(account_id)
except Exception:
return MANUAL # incident source unavailable: let a person decide
# The model's own priority is ignored; the incident record decides.
return (c.queue, "urgent" if active else "normal")
incidents is any object with a has_active_incident method that talks to your incident tracker. If that lookup fails, for example on a timeout, the ticket goes to a person instead of guessing.
Step 5: Make retries idempotent
An operation is idempotent when running it twice has the same effect as running it once.
Why it matters here: a worker can crash after routing a ticket but before marking the job as done. The job queue then runs it again. By then the model may answer differently, or the incident may be resolved. Without protection, one ticket could end up in two queues, or change priority.
Add the last function to routing.py:
def route(ticket_id: str, account_id: str, response, incidents, store: dict):
if ticket_id in store: # retry of a ticket already routed
return store[ticket_id]
decision = decide(extract(response), account_id, incidents)
store.setdefault(ticket_id, decision)
return store[ticket_id]
The first decision for a ticket ID wins. Later runs return it unchanged.
Step 6: Test every outcome locally
You do not need the API to test the logic. Save this as test_routing.py next to routing.py. It builds stand-in response objects shaped like the ones the documentation describes:
from types import SimpleNamespace as NS
from routing import Classification, route
def message(*items):
return NS(type="message", content=list(items))
def ok(queue, priority):
c = Classification(queue=queue, priority=priority)
return NS(status="completed", output=[message(NS(type="output_text"))], output_parsed=c)
refusal = NS(status="completed", output=[message(NS(type="refusal", refusal="I can't help with that."))], output_parsed=None)
cut_off = NS(status="incomplete", incomplete_details=NS(reason="max_output_tokens"), output=[], output_parsed=None)
class Incidents:
def __init__(self, active=(), down=False):
self.active, self.down = set(active), down
def has_active_incident(self, account_id):
if self.down:
raise TimeoutError("incident service timeout")
return account_id in self.active
store = {}
print(route("T1", "acct-1", ok("billing", "urgent"), Incidents(), store))
print(route("T2", "acct-2", ok("account", "normal"), Incidents(active={"acct-2"}), store))
print(route("T3", "acct-3", refusal, Incidents(), store))
print(route("T4", "acct-4", cut_off, Incidents(), store))
print(route("T5", "acct-5", ok("billing", "normal"), Incidents(down=True), store))
# Retry T2 after the incident is resolved: the stored decision is kept.
print(route("T2", "acct-2", ok("account", "normal"), Incidents(), store))
Run it in a terminal with python3 test_routing.py. The output was:
('billing', 'normal')
('account', 'urgent')
('manual_review', 'normal')
('manual_review', 'normal')
('manual_review', 'normal')
('account', 'urgent')
Line by line:
- The invoice question. The model said urgent, the tracker had no incident, so it went to billing as normal.
- An account ticket with a real incident becomes urgent, even though the model said normal.
- The refusal goes to a person.
- The cut-off response goes to a person.
- The incident tracker timed out, so a person decides.
- The retry of ticket T2 keeps its first decision, even though the incident has cleared.
The same cases as a checklist:
| Situation | Expected behavior |
|---|---|
Model selects billing and no active incident is recorded |
Route to billing with normal priority |
Model selects account and an incident is confirmed |
Route to account with urgent priority |
| Model refuses, response is incomplete, or incident data is unavailable | Route to manual_review for a person to handle |
| The same ticket is processed again | Keep the first stored decision |
Step 7: Measure routing accuracy, not only valid JSON
When you change the model or the prompt, you need to know whether routing got better or worse. Use a labeled set: real past tickets where a person has written down the correct queue. Record the model’s raw output for each one.
Save this as labeled.jsonl. JSONL means one JSON object per line. This six-line fixture was written for this article:
{"id": "L1", "expected_queue": "billing", "model_output": "{\"queue\":\"billing\",\"priority\":\"normal\"}"}
{"id": "L2", "expected_queue": "billing", "model_output": "{\"queue\":\"account\",\"priority\":\"normal\"}"}
{"id": "L3", "expected_queue": "account", "model_output": "{\"queue\":\"account\",\"priority\":\"urgent\"}"}
{"id": "L4", "expected_queue": "account", "model_output": "{\"queue\":\"billing\",\"priority\":\"normal\"}"}
{"id": "L5", "expected_queue": "manual_review", "model_output": "{\"queue\":\"manual_review\",\"priority\":\"normal\"}"}
{"id": "L6", "expected_queue": "billing", "model_output": "{\"queue\":\"billing\",\"priority\":\"normal\""}
L2 and L4 go to the wrong team. L6 is missing its closing brace, like a cut-off answer. Then save this as evaluate.py:
import json, sys
from pydantic import ValidationError
from routing import Classification # the model from step 1
def evaluate(path):
rows = [json.loads(line) for line in open(path)]
valid = correct = 0
for row in rows:
try:
queue = Classification.model_validate_json(row["model_output"]).queue
valid += 1
except ValidationError:
queue = "manual_review" # same fallback as production
correct += queue == row["expected_queue"]
n = len(rows)
print(f"tickets: {n}")
print(f"valid JSON: {valid}/{n} = {valid / n:.0%}")
print(f"routing accuracy: {correct}/{n} = {correct / n:.0%}")
evaluate(sys.argv[1])
Run python3 evaluate.py labeled.jsonl. It printed:
tickets: 6
valid JSON: 5/6 = 83%
routing accuracy: 3/6 = 50%
The gap is the point. Five of six answers were valid JSON, yet only half the tickets reached the right team. A new release can keep the first number high while the second one falls. Track both.
Common mistakes
- Trusting
output_parsedwithout checking status. A cut-off or refused answer is not a classification. Check first, as in step 3. - Letting the model decide facts it cannot see. Priority, account state and payment status belong to your own data.
- Using a dict for idempotency in production. The dict in step 5 only shows the idea. It is not safe when several workers run at once. Let the database enforce it with a unique key, for example in PostgreSQL
INSERT INTO ticket_routes (ticket_id, queue, priority) VALUES (...) ON CONFLICT (ticket_id) DO NOTHING, then read back the row that was stored. - Measuring only the valid-JSON rate. It tells you the form was filled in, not that it was filled in correctly.
- Treating
manual_reviewas failure. It is the safe path. Watch how many tickets land there, but do not remove it to make numbers look better.
Going further
If you need more confidence before switching a live system, compare old and new versions on the same traffic, as in how Anthropic checked a live API rewrite before moving traffic. For finding which step of a multi-step agent went wrong, tracing AI agents with OpenTelemetry covers the span structure.
Conclusion
A schema makes a response readable and restricts its shape, but it cannot establish whether a business claim is true. Check for incomplete and refused responses before parsing, take decisions such as priority from trusted application data, send anything uncertain to manual_review, store the decision under the ticket ID so retries do not change it, and track routing accuracy separately from the valid-JSON rate.