stratus

Structured Output

Parse model output into typed objects with Zod schemas

Structured output lets you constrain the model to respond with JSON matching a Zod schema. The parsed result is available as a fully typed finalOutput on the result.

Basic Usage

structured.ts
import { z } from "zod";
import { Agent, run } from "stratus-sdk/core";

const schema = z.object({
  name: z.string(),
  age: z.number(),
  interests: z.array(z.string()),
});

const agent = new Agent({
  name: "extractor",
  model,
  outputType: schema, 
  instructions: "Extract person info from the text.",
});

const result = await run(agent, "John is 30 and likes hiking and chess.");

// result.finalOutput is typed as { name: string; age: number; interests: string[] }
console.log(result.finalOutput.name);      // "John"
console.log(result.finalOutput.age);       // 30
console.log(result.finalOutput.interests); // ["hiking", "chess"]

With Sessions

session-structured.ts
const session = createSession({
  model,
  outputType: z.object({ answer: z.number() }),
});

session.send("What is 6 * 7?");
for await (const event of session.stream()) { /* drain */ }

const result = await session.result;
console.log(result.finalOutput.answer); // 42

With prompt()

prompt-structured.ts
const result = await prompt("What is the capital of France?", {
  model,
  outputType: z.object({
    city: z.string(),
    country: z.string(),
  }),
});

console.log(result.finalOutput); // { city: "Paris", country: "France" }

How It Works

Schema conversion

The Zod schema is converted to JSON Schema via zodToJsonSchema().

Sent to Azure

The JSON Schema is sent as response_format with type: "json_schema" and strict: true.

Model output constrained

Azure enforces that the model output matches the schema.

Parsed and typed

On completion, Stratus parses the raw JSON output with the Zod schema. The typed result is available on result.finalOutput.

Error Handling

If the model output can't be parsed, an OutputParseError is thrown:

error-handling.ts
import { OutputParseError } from "stratus-sdk/core";

try {
  const result = await run(agent, input);
} catch (error) {
  if (error instanceof OutputParseError) {
    console.error("Failed to parse output:", error.message);
  }
}

Supported Zod Types

The zodToJsonSchema converter adds additionalProperties: false to all objects for Azure strict mode compatibility.

  • z.object() - with required fields
  • z.string(), z.number(), z.boolean()
  • z.array()
  • z.enum()
  • z.optional(), z.nullable()
  • z.default()
  • z.union()
  • .describe() - maps to JSON Schema description
Edit on GitHub

Last updated on

On this page