Stop Parsing AI Text: Build Reliable Features with Structured Outputs
A model returns this response: Priority: high Team: billing Reason: The customer was charged twice. Your application needs this: { "priority" : "high" , "team" : "billing" , "reason" : "The customer was charged twice." } They look equivalent to a person. To software, they are completely different interfaces. The first response must be interpreted. The second can be validated. That distinction…
Developing reliable features with the help of AI requires building structured outputs that can be easily consumed by the application code. Simply asking the model to return JSON is not enough, as it only addresses syntax, not the contract the application expects. A JSON schema is needed to define the structure and constraints of the data.
For instance, consider a support ticket triage system that needs an AI model to suggest the responsible team, priority, a summary, and whether a human should review the decision. The result of the AI model must be validated before using it in the application code.
A TypeScript interface for this task might look something like this:
```typescript
type TicketTriage = {
team: "billing" | "account" | "technical" | "other";
priority: "low" | "normal" | "high";
summary: string;
needsHumanReview: boolean;
};
```
However, TypeScript types disappear at runtime, so the model's response still needs runtime validation. The model's output should be treated as external data, such as an HTTP request or message from a queue, and validated accordingly.
To design structured output as an API response, begin with the code that will consume the result. This reveals the actual contract, such as known values for team and priority, required summary, and boolean need for human review. The model should fit this contract, and the rest of the application should not be redesigned to accommodate the model's output.
A small and strict schema helps protect the application while remaining understandable. In this case, a Zod schema for the TicketTriage example is provided, which prevents invented categories, enforces length limits, ensures required fields are present, and validates the structure.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.