Structured Output, JSON Schema, and Typed Model Responses
How to request JSON Schema–constrained model output on agent APIs, validate it, and avoid common schema and parsing mistakes.
When you need language models to feed databases, agents, or UI components, free-form prose forces brittle parsing. This page centres on structured outputs: constraining model text to JSON that matches a JSON Schema you define. Most detail comes from the Perplexity Agent API (response_format with json_schema), with comparable mechanisms on Chrome’s Prompt API (responseConstraint) and Cloudflare Workers AI JSON Mode (response_format). It also covers post-generation validation (for example with Zod) and limits that documentation stresses across providers.
Structured output: what it guarantees (and what it does not)
Section titled “Structured output: what it guarantees (and what it does not)”Structured output means the runtime shapes the model’s reply so you receive machine-readable JSON aligned with your schema, instead of prose you scrape or regex-parse. Perplexity describes the goal plainly:
Force the model to return JSON your code can parse instead of prose you have to scrape.
— Perplexity, Structure the output
That constraint addresses syntax and shape, not factual truth. Cloudflare’s extraction documentation warns that schema compliance is separate from correctness:
Types and constraints define the form a result can take. They do not guarantee that it answers your question correctly.
— Cloudflare, Extraction models
Treat typed JSON as the first layer; add tests, citations, or server-side checks when answers must be accurate.
JSON Schema vs “just output JSON”: why providers push schemas
Section titled “JSON Schema vs “just output JSON”: why providers push schemas”Models often wrap JSON in friendly filler even when you ask for “JSON only.” Chrome’s guidance for the Prompt API is explicit:
Don’t: Rely on natural language instructions (like “output only JSON”) alone. Models might include conversational filler that breaks your parser.
— Google Chrome, Built-in AI APIs: Do and don’t
The recommended pattern is to pass a JSON Schema (or equivalent constraint) with the request. Chrome’s Language Model guide adds that responseConstraint helps prevent chatter such as “Sure, here is your JSON:” so you can JSON.parse the result directly.
Common conclusion: Prefer schema-backed structured output for anything programmatic; use natural-language format hints only as a supplement, not the sole enforcement.
response_format and responseConstraint: how major APIs enable structured output
Section titled “response_format and responseConstraint: how major APIs enable structured output”Different products expose the same idea under different field names. The table compares request shape and where to read more.
| Mechanism | Product / API | Request field | Schema wrapper | Primary doc |
|---|---|---|---|---|
| JSON Schema structured output | Perplexity Agent API | response_format |
type: "json_schema", json_schema.name + schema |
Output Control |
| Legacy Sonar | Perplexity Sonar | response_format |
Same json_schema shape |
Core Features |
| OpenAI-compatible surface | Perplexity Agent API | response_format |
Same; works on /v1/agent and compatibility aliases |
OpenAI Compatibility |
| Client-side Prompt API | Chrome built-in AI | responseConstraint on prompt() / promptStreaming() |
Plain JSON Schema object (do not JSON.stringify before passing) |
The Prompt API |
| Workers AI inference | Cloudflare Workers AI | response_format |
type: json_object or json_schema; OpenAI-compatible |
JSON Mode |
Perplexity states that structured outputs produce data you can integrate without manual parsing:
Structured outputs enable you to enforce specific response formats from Perplexity’s models, ensuring consistent, machine-readable data that can be directly integrated into your applications without manual parsing.
— Perplexity, Output Control
Workers AI frames JSON Mode similarly for agents and tool calling:
When we want text-generation AI models to interact with databases, services, and external systems programmatically, typically when using tool calling or building AI agents, we must have structured response formats rather than natural language.
— Cloudflare, JSON Mode
Perplexity Agent API: response_format with json_schema
Section titled “Perplexity Agent API: response_format with json_schema”To enable structured output on the Agent API, add a response_format block as documented in Output Control and worked examples in Structured Output Extraction:
response_format.typemust be"json_schema".json_schema.nameis required, 1–64 alphanumeric characters.json_schema.schemamust be a valid JSON Schema object.
Parsed content typically appears in output_text as a JSON string (see Academic and Scholarly Search and Shape output). You can generate the schema from Pydantic’s model_json_schema() and validate with model_validate_json, as in Output Control.
Required vs optional fields: Properties listed in required must appear in the output. Properties declared but not listed in required may be omitted and can resolve to JSON null. If required is empty or omitted, declared properties are optional—behavior is consistent for streaming and non-streaming on /v1/agent and its compatibility alias (Output Control).
When output may diverge from the schema: Responses match the schema unless generation is cut short—for example when output exceeds max_tokens (Output Control, Structured Output Extraction).
Chrome Prompt API: responseConstraint JSON Schema
Section titled “Chrome Prompt API: responseConstraint JSON Schema”On supported Chrome versions, pass a JSON Schema object as responseConstraint in the options to LanguageModel.prompt() or promptStreaming() (Structured output support for the Prompt API, The Prompt API). Structured output for schemas is specific to the Prompt API among Chrome’s built-in AI APIs (Language Model).
responseConstraint consumes context window. You can measure impact with session.measureContextUsage(), or set omitResponseConstraintInput: true and reinforce the shape in the prompt (The Prompt API).
Cloudflare Workers AI: JSON Mode and prompt-embedded schemas
Section titled “Cloudflare Workers AI: JSON Mode and prompt-embedded schemas”Workers AI JSON Mode uses response_format with type json_object or json_schema, compatible with OpenAI’s convention (JSON Mode). A worked pattern embeds the schema in the system message for models run via the REST API (Explore Code Generation Using DeepSeek Coder Models).
On Workers, you can also use the Vercel AI SDK with Zod via Output.object({ schema: z.object({...}) }) (Vercel AI SDK).
Schema design: provider rules and durable JSON shape
Section titled “Schema design: provider rules and durable JSON shape”Schemas are contracts. Perplexity’s Agent API enforces strict structural rules (Structured Output Extraction):
additionalProperties: falseon every"type": "object"(top-level and nested).- No recursive schemas (
$refto self). - No unconstrained objects (avoid bare
objectwithoutpropertiesoradditionalProperties: true). - No external
$ref; definitions must be inline. - Every schema needs a
nameat the API level.
Patterns that work well include flat typed objects, arrays of typed objects, and string enum fields (Structured Output Extraction).
For long-lived configuration JSON (not only LLM output), Cloudflare’s custom metadata guidance aligns with stable pipelines: keep the schema fixed, prefer flat structures, use snake_case keys, real booleans and numeric integers, and define fallback behavior when keys are missing or unknown.
Prompt hints that improve compliance
Section titled “Prompt hints that improve compliance”Perplexity recommends reinforcing the schema in the user message or instructions—for example asking to “return the data as a JSON object with the following structure” (Output Control, Core Features). That improves adherence but does not replace response_format.
Chrome: avoid tight length limits in the schema
Section titled “Chrome: avoid tight length limits in the schema”For the Prompt API, do not rely on maxLength in the schema to cap UI text. Chrome advises truncating client-side instead, because strict length limits can produce compressed nonsense (Language Model).
Extraction pipelines: documents, search, and tools
Section titled “Extraction pipelines: documents, search, and tools”Structured output fits repeatable extraction: paper metadata (Academic and Scholarly Search), financial fields from attachments (Document Q&A), comparisons and research tables (Structured Output Extraction). The JSON schema keeps field names stable across varying source formats (Document Q&A).
Very large documents may be truncated to token limits; split files and process sections separately (Document Q&A).
Combining web_search, function tools, and structured output
Section titled “Combining web_search, function tools, and structured output”You can pass tools (for example web_search or custom functions) together with response_format. In multi-turn function-call loops, pass the same response_format on every responses.create call; schema enforcement applies to the final text output, not to function arguments (Structured Output Extraction, Give it tools).
LiteLLM can forward Perplexity structured formats via extra_body (Perplexity with LiteLLM).
Validation after generation: JSON Schema vs Zod
Section titled “Validation after generation: JSON Schema vs Zod”Structured output reduces parsing failures; validation still catches edge cases and encodes business rules. Zod is used in Chrome’s rule-based evaluations for readable, declarative checks (types, regexes, refinements) with path-specific error messages. The same pattern appears in Cloudflare’s Vercel AI SDK examples with Output.object.
Common conclusion: Use provider structured output for format; use Zod (or similar) where you need custom rules beyond JSON Schema—for example word counts, cross-field logic, or hex color formats.
Latency, limits, and common mistakes
Section titled “Latency, limits, and common mistakes”First-request schema preparation (Perplexity)
Section titled “First-request schema preparation (Perplexity)”The first request with a new JSON Schema may delay the first token, often 10–30 seconds, while the schema is prepared; later requests avoid that delay (Output Control, Core Features). Timeouts are possible on the first call—plan retries or warm-up requests in production.
Mistakes to avoid
Section titled “Mistakes to avoid”| Mistake | Why it fails | What to do instead |
|---|---|---|
| “Output JSON only” in the prompt | Filler breaks JSON.parse |
Set response_format / responseConstraint / JSON Mode (Built-in AI APIs: Do and don’t) |
| URLs in structured fields | Hallucinated or broken links | Read URLs from search_results / citations (Output Control) |
additionalProperties: true or open objects |
Perplexity rejects or weakens conformance | Set additionalProperties: false everywhere (Structured Output Extraction) |
| Assuming schema ⇒ correct facts | Types do not verify truth | Cross-check sources; validate semantically (Extraction models) |
maxLength in Prompt API schemas |
Odd token compression | Truncate in app code (Language Model) |
Omitting response_format in tool loops |
Final answer may not match schema | Repeat response_format each turn (Structured Output Extraction) |
For deeper parameters (streaming, background runs, effort), see Output Control, Prompt Guide, Quickstart, and Models.
How to check this on your site
Section titled “How to check this on your site”-
Define a minimal JSON Schema with
additionalProperties: falseand run one Agent API call withresponse_format.typeset tojson_schema, following Structured Output Extraction; confirmoutput_textparses and required keys are present. -
If you use Chrome’s Prompt API, call
prompt()with a smallresponseConstraint(for example a boolean or single-object schema) per The Prompt API and verify the response parses without leading prose. -
If you use Workers AI, send a
json_schemaresponse_formatper JSON Mode and confirm theresponseobject matches property types. -
Run the parsed JSON through your Zod or JSON Schema validator (patterns from rule-based evaluations) and fix any systematic type or rule failures.
-
You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about, and we will correct or clarify it.