← Back to blog

Prompt API: reliable JSON from Gemini Nano, no hand-parsing

Published 2026-12-03Updated 2026-12-03

Friday, 7 p.m. A café's WhatsApp won't stop buzzing:

hola, me mandas 2 empanadas de pollo y una Coca-Cola sin azúcar a la calle 10 #43-21, pago en efectivo

("hi, can you send me 2 chicken empanadas and a sugar-free Coca-Cola to calle 10 #43-21, paying cash.")

Someone has to read every message, figure out what was ordered, where it goes and how it's paid, and type it into the order system by hand. Ten messages, fine. Two hundred, and orders get lost, addresses get swapped, and the sugar-free Coca-Cola shows up with sugar.

The obvious fix is to put a language model in the middle: it reads the message and returns the order as JSON, ready to save. And it works… almost always. One day the response comes wrapped in a Markdown code block, another day there's a friendly sentence before the opening brace, another day the address field shows up as deliveryAddress. Your code expected an object and blows up. You end up with a replace() to strip backticks, a JSON.parse inside a try/catch, and crossed fingers. (In the offline-first AI post I did exactly that.)

Chrome's Prompt API solves exactly this with one option: responseConstraint. You pass a JSON Schema and the browser forces the model to follow it while it generates. It's not "please try to return this": the response is valid JSON in that shape, or the promise rejects. And it runs with Gemini Nano on the user's device: no server, no API key, no per-order cost.

In this post we'll turn that WhatsApp message into a validated order. And I'll show you what happened when I ran the same thing with and without a schema: without one, not a single response could be parsed.

This is the second post in the series on Chrome's built-in AI APIs; the first one was about the Language Detector API and the lang attribute. The demo is in demos/prompt-api-structured-output-json-schema (the README explains how to run it). No build step: just ES modules.

If you've never used the Prompt API, start with the introduction. Here I assume you know what a session is and how to send it a prompt.

The problem: asking for JSON "nicely"

That message has to end up as this:

json
{
  "items": [
    { "quantity": 2, "name": "empanadas de pollo", "notes": "" },
    { "quantity": 1, "name": "Coca-Cola sin azúcar", "notes": "" }
  ],
  "fulfillment": "delivery",
  "address": "calle 10 #43-21",
  "paymentMethod": "cash",
  "notes": ""
}

The first thing everyone tries is adding "Reply with JSON only" at the end of the prompt. I tried it in the demo with the four sample messages, in Chrome 158: all four responses came wrapped in ```json, so JSON.parse failed on all four. And even after stripping the fences, the model made up its own field names (delivery_address instead of address), and in the English order it turned "paying by card" into "transfer".

It's not that the model is bad. An instruction in the prompt is a suggestion, and a parser needs a contract.

How the demo works

A textarea with a customer message, four sample messages, and two panels. The flow is:

  1. Check the availability badge. It shows what LanguageModel.availability() returns in your browser, or unsupported if the API doesn't exist.
  2. Load a sample message with the chips (two in Spanish and two in English; among them, a really messy one and one with no address) or write your own.
  3. Press "Parse order" (or "Download model & parse", if Gemini Nano isn't on your device yet).
  4. Look at "Raw model output". It's the exact string prompt() returned, one per attempt.
  5. Look at "Validated order". The order as a receipt, the JSON, and, if something's off, the list of problems.
  6. Tick "Also run without responseConstraint" to run the same prompt with no schema and compare.

Here it is live. It needs desktop Chrome 148 or later on hardware that meets Gemini Nano's requirements; if LanguageModel isn't available, the demo tells you so:

The actual demo from the repo, running in your browser. Needs desktop Chrome 148+ with Gemini Nano available.Open in a new tab ↗

Piece 1: the schema is the contract

The contract is a JSON Schema. In the demo it lives in order-parser.js as an object literal, because it goes to the model as-is:

js
export const ORDER_SCHEMA = {
  type: 'object',
  additionalProperties: false,
  required: ['items', 'fulfillment', 'address', 'paymentMethod', 'notes'],
  properties: {
    items: {
      type: 'array',
      minItems: 1,
      maxItems: 20,
      items: {
        type: 'object',
        additionalProperties: false,
        required: ['quantity', 'name', 'notes'],
        properties: {
          quantity: { type: 'integer', minimum: 1, maximum: 99 },
          name: { type: 'string', minLength: 1, maxLength: 80 },
          notes: { type: 'string', maxLength: 120 },
        },
      },
    },
    fulfillment: { enum: ['delivery', 'pickup', 'unknown'] },
    address: { type: ['string', 'null'], maxLength: 160 },
    paymentMethod: { enum: ['cash', 'card', 'transfer', 'unknown'] },
    notes: { type: 'string', maxLength: 200 },
  },
};

Three design decisions that matter more than the syntax:

  • Everything is required. An optional field is a field the model can skip. I'd rather it always be there, with an explicit value for "none": "" for notes, null for the address.
  • Enums have an emergency exit. paymentMethod includes "unknown". Without it, when the message doesn't say how the customer pays, the schema forces the model to pick one of the other three. Under hard constraints, an enum with no "I don't know" is an invitation to make things up.
  • additionalProperties: false on every object. Without it, the model can add fields nobody asked for.

Piece 2: responseConstraint on prompt()

With the schema in place, using it is one more option:

js
const raw = await session.prompt(prompt, { responseConstraint: ORDER_SCHEMA });
const order = JSON.parse(raw);

The Chrome documentation puts it this way: the schema goes in the options object of prompt() or promptStreaming(), as the value of responseConstraint. The explainer adds the details that matter when you write code on top of it:

  • The result is a string you can parse with JSON.parse().
  • If the browser can't produce a response that matches the schema, the promise rejects with a "SyntaxError" DOMException.
  • If the schema is valid but uses features the browser doesn't support, it rejects with "NotSupportedError".
  • If you pass something that's neither a schema nor a RegExp, TypeError.

Notice it doesn't say "the model tries". The constraint is applied while decoding: at each step, the browser only lets through tokens that keep the output inside the schema. That's why a backtick can't show up before the brace, nor a field that isn't in properties, nor "2" where an integer goes.

One detail that isn't in the documentation but shows up in practice: properties come out in the same order as in the schema. In my tests, the constrained response always had quantity before name, as I declared them; without a schema, the model put name first. The constraint library Google points to (more on that in a moment) documents that it fixes the order to the schema's. If one field helps the model "think" about the next, put it first.

Also with promptStreaming()

Same option. What changes is when you can parse: half a JSON document isn't JSON. In Chrome 158, each promptStreaming() chunk is a new piece (in my test, 116 chunks starting with {, \n, spaces, "), so you concatenate them and parse at the end:

js
let raw = '';
for await (const chunk of session.promptStreaming(prompt, { responseConstraint: ORDER_SCHEMA })) {
  raw += chunk;
  rawOutput.textContent = raw; // show progress, but don't parse yet
}
const order = JSON.parse(raw);

For a 300-character response it's not worth it; the demo uses prompt(). If you're going to show progress on screen, the streaming without destroying your INP post covers how to do it without blocking the main thread.

And with a RegExp

responseConstraint also accepts a regular expression, according to the explainer. For single-value answers it's more direct than a schema:

js
const qty = await session.prompt('How many empanadas? "me mandas 2 empanadas". Digits only.', {
  responseConstraint: /^\d{1,2}$/,
});
// "2"

I tried it in Chrome 158 and got "2". Watch out with TypeScript, coming up below: the types don't accept it.

Piece 3: which JSON Schema it understands (and which it doesn't)

This is where the documentation falls short. Neither the Prompt API guide nor the structured output guide publishes a list of supported keywords. What does exist is the JSON Schema Tester, which the guide itself recommends to "make sure your JSON Schema works well with the Prompt API". That tool checks compatibility with llguidance, and its rules are:

  • Remote $refs (https://…) aren't supported.
  • pattern can't use lookarounds ((?=…), (?!…), etc.).
  • format only accepts date-time, time, date, duration, email, hostname, ipv4, ipv6, uuid, and uri.
  • minProperties/maxProperties only if every defined property is required.
  • patternProperties must be disjoint.

The llguidance docs cover the rest: anyOf, oneOf (partial), allOf (partial), const, enum, type (single or array), items, prefixItems, minItems/maxItems, minLength/maxLength, minimum/maximum and their exclusive versions, and multipleOf.

That Chrome uses llguidance is my inference from the tester, not something the documentation states. So I checked. In Chrome 158:

SchemaResult
pattern with lookahead ^(?=.*[A-Z])…NotSupportedError
format: 'phone'NotSupportedError
$ref: 'https://example.com/item.json'NotSupportedError
format: 'date'"2026-03-15"
{ enum: ['yes', 'no'] }"yes"
responseConstraint: 42TypeError

It matches the tester and the explainer. The NotSupportedError message is generic ("the input or options could not be processed"), so it doesn't tell you which keyword failed: run the schema through the tester before blaming the model.

Piece 4: the schema takes up context too

This one is easy to miss. According to the Prompt API guide, the implementation may include the schema in the message the model receives, and that uses up part of the context window. To avoid it there's omitResponseConstraintInput, and the docs recommend describing the format in the prompt when you use it:

js
await session.prompt(prompt, {
  responseConstraint: ORDER_SCHEMA,
  omitResponseConstraintInput: true,
});

How much does it cost? The docs say you can measure it by passing responseConstraint to session.measureContextUsage(). In Chrome 158 that didn't work: measureContextUsage() returned 51 tokens with the schema, without it, and with omitResponseConstraintInput. So I measured it the old-fashioned way: contextUsage before and after a real prompt(), on clones of the same session:

OptionscontextUsage (before → after)
responseConstraint156 → 501
responseConstraint + omitResponseConstraintInput156 → 288
no constraint156 → 334

Here the schema cost about 200 tokens out of a 9,216-token window (contextWindow on my machine). For one order, that's nothing. For a large schema in a long conversation, it adds up.

But the number I cared about most was a different one. With omitResponseConstraintInput: true, the message that says "pago en efectivo" (paying cash) came back with "paymentMethod": "transfer" all four times I ran it; with the schema visible it came back "cash" all four. It makes sense: the constraint keeps the model inside the enum, but if it can't see the schema, it doesn't know what each option means. If you omit it, describe every field in the prompt. For a schema this size, I keep it visible.

(Two more names, in case you're coming from older code: inputUsage, inputQuota, and measureInputUsage() are now contextUsage, contextWindow, and measureContextUsage(). The explainer says the old names are gone on the web and only remain, deprecated, in extensions.)

Piece 5: TypeScript types

For types there's @types/dom-chromium-ai, the package the documentation itself recommends. The current version is 0.0.18 (October 2026), and it types LanguageModel and the rest of the built-in APIs (Summarizer, Writer, Rewriter, Translator, LanguageDetector, Proofreader):

bash
npm install --save-dev @types/dom-chromium-ai

Two things you'll notice when you use it:

  • prompt() returns Promise<string>. It isn't generic: the type of what you parse is your problem.
  • responseConstraint is typed as Record<string, unknown>. A schema fits fine, but a RegExp doesn't compile, even though the explainer and Chrome accept it. If you need one, you'll have to cast.

The real TypeScript risk isn't the API, it's the schema and the type drifting apart: you add a field to the schema, forget the type, and the compiler says nothing. Without adding dependencies, you can derive what you can from the schema and let the compiler watch the rest:

ts
export const ORDER_SCHEMA = {
  // …the same schema as above…
} as const;
 
type Props = typeof ORDER_SCHEMA.properties;
 
export type Order = {
  items: { quantity: number; name: string; notes: string }[];
  fulfillment: Props['fulfillment']['enum'][number]; // 'delivery' | 'pickup' | 'unknown'
  address: string | null;
  paymentMethod: Props['paymentMethod']['enum'][number];
  notes: string;
};
 
// Compile-time guard: `required` and the keys of Order must match exactly.
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
const requiredMatchesType: Same<(typeof ORDER_SCHEMA.required)[number], keyof Order> = true;

The enums come from the schema, so they can't drift. And if you add a field to required without adding it to Order (or the other way around), requiredMatchesType stops compiling. I tested it with TypeScript 5.9 and the 0.0.18 types: removing notes from Order gives Type 'true' is not assignable to type 'false'.

To go from string to Order, I use a helper that forces you to pass a validator, so there's no as Order hiding anywhere:

ts
export async function promptJson<T>(
  session: LanguageModel,
  input: string,
  schema: Record<string, unknown>,
  validate: (value: unknown) => value is T,
): Promise<T> {
  const raw = await session.prompt(input, { responseConstraint: schema });
  const value: unknown = JSON.parse(raw);
  if (!validate(value)) throw new TypeError('Response does not match the expected type.');
  return value;
}

What about Zod? If you already use it, Zod 4 ships z.toJSONSchema() built in (you don't need zod-to-json-schema, which was for Zod 3). I wrote the same order with Zod 4.6, and the generated schema only uses keywords from the list above; for nullable() it emits anyOf: [{…}, { type: 'null' }] and adds a $schema key. I passed it to Gemini Nano as-is and got the same order back. The upside is that z.infer gives you the type and .safeParse() the validator. The downside is adding a dependency for a 30-line schema; for this demo, I didn't.

Piece 6: validate anyway, constrained isn't correct

This is the part the documentation's line "developers can now assume the model's response is valid JSON" leaves out. It's true: it's valid JSON and it matches the schema. That doesn't make it correct. The schema guarantees the shape, not the meaning.

I saw it in the demo itself, more than once:

  • With "send me 2 of the usual pepperoni pizzas to my place pls, cash", the model answered "fulfillment": "delivery" and "address": null. Flawless JSON, and an order your driver can't deliver.
  • With the taco order, which has no address, it once returned "address": "null": the string "null". The schema says type: ['string', 'null'], and "null" is a perfectly valid string.
  • With the messy message, which says "mándalo a la cra 45…" (send it to cra 45…), it marked "fulfillment": "pickup" in several runs, with the full address right next to it.

None of the three is practical to catch with a JSON Schema. That's why validateOrder() has two parts, and each problem says what to do about it:

js
/**
 * @typedef {{ message: string, action: 'retry' | 'ask' }} Problem
 * 'retry': the model got it wrong and can fix it from the message.
 * 'ask': the message lacks the information; a human has to ask the customer.
 */
export function validateOrder(order, message) {
  const problems = [];
  const retry = (text) => problems.push({ message: text, action: 'retry' });
  const ask = (text) => problems.push({ message: text, action: 'ask' });
 
  // 1. Structure: mirrors ORDER_SCHEMA. Cheap insurance (and what catches
  //    the no-schema path in the comparison).
  // …
 
  // 2. Meaning: valid JSON, but does it make sense?
  const source = new Set(tokens(message));
  if (address?.trim()) {
    const addressTokens = tokens(address);
    const found = addressTokens.filter((t) => source.has(t)).length;
    if (found / addressTokens.length < 0.6) {
      retry(`The address "${address}" doesn't appear in the message. Use null if there is none.`);
    } else if (fulfillment === 'pickup') {
      retry('"fulfillment" is "pickup", but there is a delivery address. If the customer asked to send it there, it is "delivery".');
    }
  } else if (fulfillment === 'delivery') {
    ask('This is a delivery, but the message has no address. Ask the customer for it.');
  }
  // …plus: every item name must appear in the message, and no duplicated lines.
 
  return problems;
}

The grounding rules (the address and the products must appear in the message) are the defense against an LLM's worst extraction failure: making data up with total confidence. They're what caught the "null". tokens() normalizes case, accents, punctuation, and a naive plural, so "Azúcar" and "azucar", or "pizza" and "pizzas", count as the same. It's a heuristic, not an address parser; it's enough for a demo, and your domain will have better rules.

Retry with feedback, but only what the model can fix

My first version retried on any problem: it replied to the model, in the same session, with the list of errors. With the no-address order, something happened that I didn't expect. The model didn't invent an address (that was my fear), but in 2 out of 5 runs it "fixed" the error by changing fulfillment from "delivery" to "unknown". The validator was happy. The order was worse: the customer had written "send me… to my place".

The lesson: feedback is an invitation to change anything that makes the error go away. If a piece of data is missing from the message, no prompt will make it appear, and retrying only opens the door for the model to hide the problem. So now parseOrder() only retries retry problems, and ask problems go straight to a human:

js
export async function parseOrder(baseSession, message, { signal, maxRetries = 1 } = {}) {
  const session = await baseSession.clone({ signal });
  const attempts = [];
  try {
    let input = buildPrompt(message);
    for (let attempt = 0; ; attempt++) {
      const raw = await session.prompt(input, { responseConstraint: ORDER_SCHEMA, signal });
      const order = JSON.parse(raw);
      const problems = validateOrder(order, message);
      attempts.push({ raw, problems });
 
      const fixable = problems.filter((p) => p.action === 'retry');
      if (fixable.length === 0 || attempt >= maxRetries) return { attempts, order, problems };
 
      input = `Your previous answer has these problems:\n${fixable.map((p) => `- ${p.message}`).join('\n')}\n` +
        'Fix only these, using only information from the original message, and answer again.';
    }
  } finally {
    session.destroy();
  }
}

Notice baseSession.clone(). The base session already has the system prompt processed; each order runs on a clone that's destroyed at the end, so one order never pollutes the next one's context. And the retry happens on the same clone, so the model sees its previous answer along with the problems.

With this, both retry cases I saw got fixed on the second attempt: the "null" became null, and the messy message's "pickup" became "delivery". The no-address order ends at "needs a human" in a single attempt, which is right: the next step is asking the customer for the address, not pushing the model.

To sum up error handling:

  • SyntaxError: the model couldn't satisfy the schema. Retry once, or ask the user to rephrase.
  • NotSupportedError: your schema uses something Chrome doesn't support. That's your bug; run it through the tester.
  • A retry problem: the model got wrong something that's in the message. One retry with feedback, at most.
  • An ask problem: information is missing. To a human, no retry.

With and without responseConstraint: what I saw

I ran the demo's four sample messages with and without a schema, in desktop Chrome 158 (macOS). It's a small sample on a single machine: treat it as an observation, not a benchmark.

MessageWith responseConstraintWithout responseConstraint
ES · cleanValid on the 1st attempt, every timeMarkdown fences, JSON.parse fails
EN · pickupValid; once "address": "null", fixed on retryFences, and paymentMethod: "transfer" (the message says card)
ES · messyValid; sometimes "pickup", fixed on retryMarkdown fences, JSON.parse fails
EN · no addressSchema OK, address missing → "needs a human"Markdown fences, JSON.parse fails

With a schema: every response parsed and had the right shape. Without one: none passed a plain JSON.parse, and on top of that the model used a different field name (delivery_address or deliveryAddress), which breaks your code even after you strip the fences. Each constrained order took between 2 and 6 seconds on my machine with the model already loaded, and up to 11 when there was a retry.

And three "valid" details that show the schema's limit, because not even my validator catches them:

  • "3 beef tacos, one of them with no onions" always came back as one line of 3 tacos with the note "one with no onions". Reasonable, but a kitchen system might want two lines (2 + 1).
  • In the messy message, "otra hamburguesa igual pero sencilla" (another burger just like it, but single) came back as "hamburguesa sencilla" without the "no pickles" that "just like it" implied.
  • Once, with the pizza order, the model added a phantom second line: 2× pepperoni pizza and 1× pepperoni pizza. The duplicate rule catches identical lines, but this one had different notes and got through.

If those matter to you, they're domain rules or examples in the system prompt. The schema doesn't reach that far.

Availability, languages, and hardware

The usual for Gemini Nano APIs, briefly (the details on downloading, user activation, and monitor are in the previous post):

  • Version: the Prompt API is stable on the web since Chrome 148; in extensions, since Chrome 138 (status table).
  • Platforms: Windows 10/11, macOS 13+, Linux, and ChromeOS on Chromebook Plus. Android and iOS aren't supported yet (requirements).
  • Hardware: at least 22 GB free on the volume with your Chrome profile, and a GPU with more than 4 GB of VRAM, or a CPU with 16 GB of RAM and 4 cores. The initial download needs an unmetered connection.
  • Languages: expectedInputs and expectedOutputs accept "en", "ja", "es", "de", and "fr". Declare them: if the browser can't handle one, create() fails up front instead of giving you something odd later.
  • Same options for availability() and create(). The docs flag this as critical, because availability depends on the languages and modalities you ask for. In the demo both use SESSION_OPTIONS.
  • Sampling: on web pages, temperature and topK no longer work (they only remain, deprecated, in extensions). Their replacement is samplingMode, with presets like "most-predictable", which the explainer suggests for content extraction; on the web it's still in an origin trial, so the demo doesn't use it.
  • User activation: if the model is "downloadable" or "downloading", create() needs the user to have interacted with the page. That's why the first call goes in the button's click handler, with no await before it.
  • Where it runs: top-level windows and same-origin iframes; for cross-origin ones, allow="language-model". It isn't available in Web Workers.

A demo detail that cost me a bug: downloadprogress fires at least two events, 0 and 1, even when there's nothing to download (the explainer says so). My first version showed "Downloading Gemini Nano… 100%" with the model already installed. Now the bar only shows up when availability() didn't say "available".

An honest caveat: what this demo doesn't prove

  • I tested it in desktop Chrome 158 (macOS), on a single machine. LLM output varies across model versions and across runs. The table above is what I saw, not a guarantee.
  • Two things didn't behave the way the documentation says. measureContextUsage() didn't reflect the schema's cost, and passing omitResponseConstraintInput: true without responseConstraint didn't throw the TypeError the explainer describes: it just answered. That may change in future versions; don't build logic that depends on either.
  • The list of supported keywords comes from the tester, not from a Chrome spec. I checked the cases in the table, not all of them.
  • Token-based grounding is a heuristic. A customer who writes "to the usual place", or an address with different abbreviations, will fool it.
  • The first create() can be slow. In one of my runs, with the model already downloaded, it took about 19 seconds; later ones took under half a second. Show a loading state.

What I learned building this

  1. "Reply with JSON only" is a suggestion; responseConstraint is a contract. In my tests, the difference was between no parseable responses and all of them.
  2. The schema is a design, not paperwork. Always-required fields, explicit null and "", and an "unknown" in every enum. Under hard constraints, an enum with no way out forces the model to make things up.
  3. Constrained isn't correct. The schema gives you the shape. Your code validates the meaning.
  4. Don't ask the model to fix what's missing. Retrying with feedback works for model mistakes. For data the customer never wrote, the model will find a way to make the error disappear, not to make the order better. That goes to a human.
  5. The schema is part of the prompt. It takes up context, and hiding it with omitResponseConstraintInput can cost you accuracy. Measure with the real contextUsage.

This is the second post in the series on Chrome's built-in AI APIs. In the next one we switch API and scale: the Summarizer API, "Summarize 500 reviews without paying for tokens".


To keep exploring

Are you pulling structured data out of free text in the browser? Tell me what schema you use and what still breaks. Let's talk on X/Twitter or LinkedIn.

Profile