Structured Outputs in TypeScript
Introduction: Grounding Factor 1 in Practice
In the previous course, you learned about Factor 1 (Natural Language to Tool Calls) of the 12-Factor Agents methodology: translating natural language into machine-readable actions. This unit begins with prompted JSON: we ask the model for a particular shape, but the API does not enforce it. The next unit introduces native function calls with a strict tool schema. OpenAI calls that schema-enforced feature Structured Outputs; a prompt alone does not provide the same guarantee.
Now, it is time to implement that principle. In this lesson, you will learn a probabilistic approach for obtaining structured outputs: prompting OpenAI models to return JSON. This method relies on careful instruction through the system prompt, but it is important to understand that this is a best-effort technique — the model will usually comply, but there is no guarantee. You will need robust error handling to manage cases where the model does not follow instructions perfectly.
The System Prompt Pattern
The first step in obtaining structured outputs is crafting a system prompt that clearly instructs the model on which format to use. Think of the system prompt as setting the rules of the game before the conversation starts. Here is a simple but effective pattern:
Notice what this prompt does. It does not simply ask the model to "return JSON" in a vague way. It shows the exact JSON schema you expect, complete with field names and a brief description of the content for each field. The word "only" is deliberate — it reinforces that the model should not add extra commentary or explanations outside the JSON structure.
This approach leverages the model's training on structured data formats; therefore, when you provide a clear schema, the model generally complies. However, remember that this is a best-effort instruction — the model may still occasionally deviate from the schema or return invalid JSON. This systemPrompt string will be passed directly to the instructions field of the API request, as you will see in the next section.
Making the API Request
