Stark-Kit / Docs

Structured Outputs

Pass a Zod schema to the outputType option and Stark-Kit auto-configures the agent to return structured JSON.

How it works

When you provide a Zod schema to an Agent's outputType, Stark-Kit converts it to a JSON schema and injects it into the system prompt. It also automatically defines a submit_final_output tool behind the scenes. The model is forced to call this tool to complete its run, ensuring the output strictly adheres to your required shape.

structured.ts
import "dotenv/config";
import { Agent, run, OpenAIProvider } from "@mehularora/stark-kit";
import z from "zod";
const provider = new OpenAIProvider();
// Define the exact shape of the response you want
const FeedbackSchema = z.object({
sentiment: z.enum(["positive", "negative", "neutral"]),
topics: z.array(z.string()).describe("Main topics mentioned in the feedback"),
score: z.number().min(0).max(10).describe("Sentiment intensity from 0 to 10"),
});
const analyzer = new Agent({
name: "FeedbackAnalyzer",
provider,
instructions: "Analyze customer feedback. Extract sentiment, topics, and a severity score.",
outputType: FeedbackSchema, // ← bind the output schema here
});
const result = await run({
agent: analyzer,
messages: "The checkout was confusing and the email confirmation never arrived. Very frustrating.",
});
if (result.status === "complete") {
// result.finalOutput is typed as z.infer<typeof FeedbackSchema>
console.log(result.finalOutput);
// → { sentiment: "negative", topics: ["checkout", "email confirmation"], score: 8 }
}

Accessing the typed output

When an agent has outputType set, the final result contains a finalOutput property typed correctly as z.infer<typeof YourSchema>. The regular result.content string will also contain the JSON representation.

Tip: Structured outputs and tools can be combined on the same agent. The model can call tools freely during its reasoning steps and then submit the final structured answer when it's done.