The greatest challenge in building software with AI is unpredictability. Asking an AI for a "JSON list" might result in a code block, a markdown table, or text with trailing commas. Structured Outputs force the AI to adhere to a strict schema, ensuring your code can always parse the result.
The problem with "Raw" AI responses
When you ask an AI to "return a list of 5 cities," you might get:
- A numbered list.
- A bulleted list.
- A paragraph of text.
Parsing this reliably in a production application is nearly impossible.
The Solution: JSON Schema and Structured Outputs
ModelRiver uses industry-standard JSON Schema to define the expected output. When you send a request through a Workflow with a structured output enabled, ModelRiver:
- Injects Schema Instructions: Automatically formats the prompt to tell the AI exactly how the JSON should look.
- Validates Output: Checks the AI's response against your schema before it reaches your application.
- Automated Retries: If the AI produces malformed JSON, ModelRiver can automatically retry or attempt to fix the formatting.
Designing a robust AI schema
A good schema is the foundation of a reliable AI feature.
1. Be explicit with types
Instead of just string, use enum for fields with limited options (e.g., status: "approved" | "pending" | "rejected").
2. Use descriptions
Each field in your JSON schema can have a description. ModelRiver passes these to the AI as context, significantly improving accuracy.
3. Require essential fields
Mark critical fields as required to ensure the AI doesn't skip them if it's uncertain.
Benefits for production applications
Type Safety (TypeScript/Typed Languages)
By receiving guaranteed JSON, you can use automated tools to generate TypeScript interfaces, giving you complete type safety from the AI response down to your UI components.
Reduced Hallucinations
By limiting the output space to a specific schema, the model is less likely to wander into irrelevant text or provide non-existent data.
Seamless Backend Integration
Structured data can be directly inserted into databases, sent to webhooks, or used to trigger logic without complex regex or secondary "clean-up" prompts.
How to implement Structured Outputs
With ModelRiver, you don't need to write complex system prompts.
- Define a Structure in the Console by providing a sample JSON object.
- Attach the Structure to a Workflow.
- Call the Workflow from your code.
The SDK will return a parsed JavaScript object instead of a raw string.