AI Engineering
Structured outputs and tool calling: making LLM output safe to use in code
Free text is a poor interface between a model and your code. Use typed schemas, validation with error feedback and server-side argument checks.
By Envexa Engineering6 min read
The moment an LLM's output feeds other code, such as a database write, an API call or a decision, free text becomes a liability. Parsing prose with regular expressions breaks on the first unexpected phrasing. The fix is to make the interface between the model and your code explicit: a schema the output must satisfy, and validation that happens in your code, not in the model's good intentions.
Define the schema first
Describe what you need as a typed model. Keep it small and specific, use enums for closed sets, and mark what is genuinely optional. Fields the model cannot know should not be in the schema.
from enum import Enum
from pydantic import BaseModel, Field
class Category(str, Enum):
billing = "billing"
shipping = "shipping"
technical = "technical"
other = "other"
class TicketTriage(BaseModel):
category: Category
urgency: int = Field(ge=1, le=5)
summary: str = Field(max_length=280)
needs_human: boolUse the provider's structured mode, then validate anyway
Most LLM APIs can constrain output to a JSON schema or force a function call. Use that: it greatly reduces malformed output. But constrained decoding guarantees shape, not truth or business validity. Always validate in your own code, because the value urgency: 5 can be valid JSON and still wrong.
Retry with the error, not blindly
When validation fails, send the specific error back to the model once or twice ("urgency must be between 1 and 5; you returned 9") instead of repeating the same request. Cap the attempts, log every failure, and have a defined fallback, such as routing the item to a human queue.
Tool calling: the model proposes, your code decides
- Validate arguments server-side against the tool's schema, exactly as you would validate an HTTP request from an untrusted client.
- Take identity from your context, not the model. The customer ID comes from the authenticated session, never from a model-supplied argument.
- Separate read tools from write tools and require confirmation or approval for anything irreversible.
- Make write tools idempotent with idempotency keys, because retries and repeated tool calls happen.
- Return structured errors the model can act on (
order_not_found), not stack traces.
Design schemas the model can follow
- Write field descriptions like documentation for a new colleague. Models read them.
- Prefer flat structures to deeply nested ones, and short enums to free strings.
- Give examples of edge cases in the description ("use
otherwhen none apply"). - Allow an explicit way to say "unknown" or "not present", or the model will invent a value.
Test the contract
Include schema-validity rate and tool-argument validity in your evaluation set, and track them in production. A drop in validity is often the first sign that a prompt or model change has hurt behaviour. Keep the schema versioned like an API, since downstream code depends on it.
Treat the model as an unreliable but useful collaborator, and put typed, validated boundaries around it. The result is output you can put in a database and tool calls you can safely execute.
Related articles
Building reliable AI agents: tools, limits and a way out
How to design AI agents that behave in production: small typed toolsets, step and cost budgets, validated arguments, escalation and trajectory evaluation.
How to evaluate an LLM application before and after you ship it
Vibe checks do not scale. Build a golden test set, mix rule-based checks with model grading and human review, run it in CI, and keep measuring in production.