Use this file to discover all available pages before exploring further.
Instead of parsing free-form text, you can ask a model to return data that matches a specific structure. Genkit validates the output against your schema and automatically retries if the model returns invalid JSON.
Use format: 'enum' to constrain a response to one of a specific set of values:
const SentimentSchema = z.enum(['positive', 'negative', 'neutral']);const response = await ai.generate({ prompt: 'The food was cold and the service was slow.', output: { schema: SentimentSchema, format: 'enum', },});console.log(response.output); // "negative"
Some models support native constrained generation — the model is instructed at the inference level to only produce tokens that are valid for the given schema. This is more reliable than prompt-based instructions.Set output.constrained: true to enable it when available:
const response = await ai.generate({ prompt: 'Extract the order details from this receipt: ...', output: { schema: OrderSchema, constrained: true, },});
Not all models support constrained generation. Genkit falls back to prompt-based instructions when the model does not support it. You can check model.supports.constrained to see what a model supports.
Genkit calls response.assertValidSchema() internally. If the model returns output that fails schema validation, Genkit throws a GenkitError. You can call response.isValid() to check without throwing:
For more reliable structured output, use Gemini models with constrained: true. These models support native JSON mode and are less likely to produce invalid output.
Structured output works inside flows just like it does in standalone generate() calls. Define the flow’s output schema with Zod and use it in the generate call: