demo · v137 · origin trial

Structured Output

The Prompt API can be constrained to return JSON matching a schema. The browser uses the model's logits + a grammar to guarantee parseable output — no JSON.parse retry loops, no “extract JSON from a code fence” regex. Below: classify a snippet of text into a fixed shape, validate the result against the schema.

Heads up · origin trial / flagConstrained output ships behind chrome://flags/#prompt-api-for-gemini-nano. If your build doesn't expose responseConstraint, this page falls back to a free-form prompt that asks for JSON and shows you exactly the unreliability the feature exists to eliminate.
probing…

schema given to model

model output

awaiting run…

the code

const session = await LanguageModel.create({
  initialPrompts: [
    { role: "system", content: "Extract structured data from the input." },
  ],
});

const schema = {
  type: "object",
  required: ["rating", "sentiment"],
  properties: {
    rating: { type: "number", minimum: 0, maximum: 10 },
    sentiment: { enum: ["positive", "neutral", "negative"] },
    pros: { type: "array", items: { type: "string" } },
    cons: { type: "array", items: { type: "string" } },
  },
};

const result = await session.prompt(input, {
  responseConstraint: schema,   // browser enforces grammar
});
// result is a JSON string that parses cleanly.

see also