X Enterprises
fastify-x-ai

generateStructured

Generate structured output validated against a Zod schema using the AI SDK's Output helper.

generateStructured

Generates text and parses it into a typed object that conforms to a Zod schema. Internally wraps generate() with the AI SDK's Output.object() helper.

Signature

fastify.xai.generateStructured(params: StructuredParams): Promise<GenerateResult>

interface StructuredParams {
  prompt: string
  schema: ZodObject<any>
  schemaName?: string
  schemaDescription?: string
  provider?: "openai" | "anthropic" | "google"
  model?: string
  maxTokens?: number
  temperature?: number
  system?: string
}

Params

NameTypeRequiredDescription
promptstringYesThe generation prompt
schemaZodObjectYesZod schema describing the expected output shape
schemaNamestringNoSchema name hint sent to the model (improves accuracy)
schemaDescriptionstringNoSchema description hint
providerstringNoOverride default provider
modelstringNoOverride default model
maxTokensnumberNoOverride defaultMaxTokens
temperaturenumberNoOverride defaultTemperature
systemstringNoSystem message

Returns

Same GenerateResult as generate(). The structured object is in result.object (added by the AI SDK Output helper). result.text contains the raw model output before parsing.

Throws

ErrorWhen
xAI generateStructured: 'prompt' is requiredprompt missing or empty
xAI generateStructured: 'schema' is requiredschema missing
xAI: Provider '…' not configuredProvider has no API key

Examples

Recipe generator

import { z } from "zod";

const result = await fastify.xai.generateStructured({
  prompt: "Generate a recipe for chocolate lava cake.",
  schema: z.object({
    name: z.string(),
    servings: z.number(),
    prepMinutes: z.number(),
    ingredients: z.array(
      z.object({ item: z.string(), amount: z.string() }),
    ),
    instructions: z.array(z.string()),
  }),
  schemaName: "Recipe",
  schemaDescription: "A structured cooking recipe",
});

console.log(result.object);
// { name: "Chocolate Lava Cake", servings: 4, ... }

Extracting structured data from user input

const contactSchema = z.object({
  firstName: z.string(),
  lastName: z.string(),
  email: z.string().optional(),
  company: z.string().optional(),
});

fastify.post("/extract-contact", async (request, reply) => {
  const { rawText } = request.body;

  const result = await fastify.xai.generateStructured({
    prompt: `Extract contact information from this text:\n\n${rawText}`,
    schema: contactSchema,
    schemaName: "Contact",
    temperature: 0.1, // low temperature for extraction tasks
  });

  return result.object;
});

See Also

  • generate — What generateStructured() delegates to internally
  • createEmbedding — Vector embeddings for semantic search

AI Context

package: "@xenterprises/fastify-x-ai"
method: fastify.xai.generateStructured(params)
use-when: Generate structured JSON output validated against a Zod schema — uses AI SDK object generation mode
params: prompt (required), schema (required Zod schema), model, provider, maxTokens, temperature, system
returns: { object (typed by schema), usage, finishReason }
Copyright © 2026