Lesson 2 of 9 · 26m
Structured Output and Tool Use Without Wishful Thinking
Use schemas, validation, constrained decoding, and narrow tools to make model output executable instead of merely plausible.
The moment model output drives software, prose becomes a liability. You do not want a paragraph that sounds like a routing decision; you want an object your service can validate and execute. The design goal is not perfect obedience. It is a pipeline where malformed output fails closed, valid output is checked, and tools expose only the authority the workflow actually needs.
Ask for the smallest machine-readable object
A schema should represent decisions and fields the application truly uses:
{
"type": "object",
"additionalProperties": false,
"properties": {
"label": {"enum": ["billing", "bug", "abuse", "feature_request", "other"]},
"priority": {"enum": ["low", "normal", "urgent"]},
"handoff": {"type": "boolean"},
"summary": {"type": "string", "maxLength": 240}
},
"required": ["label", "priority", "handoff", "summary"]
}Use provider-native structured output or constrained decoding when available. It reduces syntax errors, but it does not prove the facts inside the object. Schema validity is not semantic truth.
Validate twice: shape, then policy
The parser can enforce types. Your application must enforce business rules:
parsed = TicketClassification.model_validate_json(raw)
if parsed.priority == "urgent" and not parsed.handoff:
raise PolicyViolation("urgent tickets must hand off")
if parsed.label == "abuse" and customer.plan == "enterprise":
queue = "trust-and-safety"This second validation layer is where real reliability comes from. A model may output syntactically perfect nonsense. Your code decides whether the nonsense is executable.
Tools are capabilities, not decorations
Function calling works best when tools are narrow, typed, idempotent, and boring:
tools = [{
"type": "function",
"name": "lookup_order",
"description": "Fetch one order by ID for the authenticated customer.",
"parameters": {"type": "object", "properties": {"order_id": {"type": "string"}},
"required": ["order_id"], "additionalProperties": False},
}]Do not expose run_sql, http_request, or execute_code to a general assistant because it is convenient. Expose lookup_order, create_refund_case, or get_shipping_status with server-side authorization. If a tool can mutate state, require explicit confirmation or use a workflow step outside the model loop.
Expect malformed calls and loops
Tool-using agents fail in familiar ways: wrong argument types, hallucinated IDs, repeated calls, circular reasoning, and calls after the answer was already available. Bound the loop:
for step in range(max_steps := 6):
response = call_model(messages, tools=tools)
if not response.tool_calls:
break
messages.extend(execute_allowed_tools(response.tool_calls))
else:
return escalation_response("tool step budget exhausted")Log the tool-call graph. When something goes wrong, the sequence is often more important than the final text.
Never let tool results become trusted instructions
A web page, ticket body, PDF, or database row can contain text that looks like a command. Treat tool output as untrusted content. Present it as data, delimit it, and keep the model's authority model explicit. The safest architectures also separate read tools from write tools so retrieval cannot directly trigger action.
Field notes
- JSON mode means parseable JSON, not correct JSON.
- Use
additionalProperties: falsewhen the output feeds automation. - Tool names and descriptions influence behavior; sloppy naming creates sloppy calls.
- Idempotency keys matter when retries can repeat side effects.
- A confirmation step is a product feature, not an admission that the model failed.
Was this lesson helpful?