Skip to main content
Use structuredOutput to force the agent to respect a zod schema. The schema is passed to the AI SDK experimental_output field and the result is typed accordingly.
import { Output } from "@ai_kit/core/agents";
import { z } from "zod";

const personSpec = Output.object({
  schema: z.object({
    name: z.string(),
    age: z.number().nullable().describe("Person age."),
    contact: z.object({
      type: z.literal("email"),
      value: z.string(),
    }),
    occupation: z.object({
      type: z.literal("employed"),
      company: z.string(),
      position: z.string(),
    }),
  }),
});

const structured = await assistant.generate({
  prompt: "Create a sample profile for a potential customer.",
  structuredOutput: personSpec,
});

console.log(structured.experimental_output);
// -> { name: "...", age: 32, contact: { ... }, occupation: { ... } }
  • Output.object offers an ergonomic builder for the expected payload.
  • Schema descriptions are forwarded to the model to boost accuracy.
  • If parsing fails, the SDK throws—catch it to retry or log the error.

Targeted extraction

import { Agent, Output } from "@ai_kit/core";
import { z } from "zod";
import { google } from "@ai-sdk/google";

const siretOutput = Output.object({
  schema: z.object({
    siret: z
      .string()
      .length(14, "The SIRET must contain exactly 14 digits."),
  }),
});

const assistant = new Agent({
  name: "life-assistant",
  instructions: "Lifestyle assistant",
  model: google("gemini-2.5-flash"),
  tools: {
    google_search: google.tools.googleSearch({}),
  },
});

const result = await assistant.generate({
  prompt: "Find the SIRET of Aidalinfo.",
  structuredOutput: siretOutput,
});

console.log(result.experimental_output);
// -> { siret: "12345678901234" }

Tips

  • Prefer agent.generate for structured generation—streaming + schemas remains experimental.
  • Log parsing errors to fine-tune prompts or trigger retries.
  • Separate “strict” outputs (IDs, metadata) from free-form content (summaries, answers).