AutoGen Tutorial (TypeScript): parsing structured output for intermediate developers
This tutorial shows you how to get AutoGen in TypeScript to return structured JSON you can reliably parse into typed objects. You need this when an LLM is generating business data, and you want to avoid brittle string parsing in workflows like claims intake, KYC review, or document extraction.
What You'll Need
- •Node.js 18+ installed
- •A TypeScript project with
ts-nodeor a build step - •OpenAI API key set as
OPENAI_API_KEY - •Packages:
- •
@autogenai/autogen - •
zod - •
dotenv - •
typescript - •
ts-nodeif you want to run directly
- •
Install them:
npm install @autogenai/autogen zod dotenv
npm install -D typescript ts-node @types/node
Step-by-Step
- •Start by defining the schema you want the model to produce. Keep it narrow and explicit; structured output works best when the model has very little room to improvise.
import "dotenv/config";
import { z } from "zod";
const ClaimSummarySchema = z.object({
claimId: z.string(),
customerName: z.string(),
severity: z.enum(["low", "medium", "high"]),
amountUsd: z.number(),
flags: z.array(z.string()),
});
type ClaimSummary = z.infer<typeof ClaimSummarySchema>;
- •Create a small helper that sends a prompt and asks for JSON only. In production, this is where you keep the format contract tight and reject anything that fails validation.
import { AssistantAgent } from "@autogenai/autogen";
const agent = new AssistantAgent({
name: "parser",
modelClient: {
apiKey: process.env.OPENAI_API_KEY!,
model: "gpt-4o-mini",
},
});
async function generateClaimSummary(input: string): Promise<string> {
const result = await agent.run([
{
role: "user",
content: [
"Extract a claim summary from the text below.",
"Return only valid JSON with keys:",
'claimId, customerName, severity, amountUsd, flags',
"",
input,
].join("\n"),
},
]);
return String(result.messages.at(-1)?.content ?? "");
}
- •Parse the raw response with
JSON.parse, then validate it with Zod. This gives you two layers of protection: syntax correctness and shape correctness.
function parseClaimSummary(raw: string): ClaimSummary {
const parsed = JSON.parse(raw);
return ClaimSummarySchema.parse(parsed);
}
async function main() {
const raw = await generateClaimSummary(
"Claim CLM-1042 from Priya Shah. Water damage in kitchen after pipe burst. Estimated payout is $4200. Flag for adjuster review."
);
const summary = parseClaimSummary(raw);
console.log(summary);
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
- •Add a fallback path for bad generations. In real systems, models sometimes wrap JSON in markdown fences or add extra commentary, so strip that before parsing.
function extractJsonBlock(raw: string): string {
const trimmed = raw.trim();
if (trimmed.startsWith("```")) {
return trimmed.replace(/^```(?:json)?\s*/i, "").replace(/```$/, "").trim();
}
return trimmed;
}
function parseClaimSummarySafe(raw: string): ClaimSummary {
const jsonText = extractJsonBlock(raw);
const parsed = JSON.parse(jsonText);
return ClaimSummarySchema.parse(parsed);
}
- •If you want stronger guarantees, enforce the format in the prompt and keep the schema close to the code that consumes it. That makes refactors safer because your parser and your downstream logic evolve together.
async function mainStrict() {
const raw = await generateClaimSummary(
[
"You are a data extraction service.",
"Output must be valid JSON only.",
"Do not include markdown, prose, or code fences.",
"",
"Claim CLM-2048 from Daniel Kim. Theft report for laptop stolen from car. Estimated payout is $1800. No special flags.",
].join("\n")
);
const summary = parseClaimSummarySafe(raw);
console.log("Parsed claim:", summary.claimId, summary.severity);
}
mainStrict().catch(console.error);
Testing It
Run the script with your API key set in the environment:
OPENAI_API_KEY=your_key_here npx ts-node index.ts
You should see a parsed object printed to the console with typed fields like claimId, customerName, and amountUsd. If parsing fails, check whether the model returned extra text or invalid JSON; that usually means your prompt is too loose or your schema is too broad.
For a real test, try three inputs:
- •one clean claim description
- •one noisy paragraph with irrelevant details
- •one input missing a field like amount
Your validation should catch missing or malformed fields instead of letting bad data flow downstream.
Next Steps
- •Add retry logic that re-prompts the model when Zod validation fails.
- •Move from plain JSON parsing to tool/function calling for stricter structured output.
- •Extend the schema with nested objects for line items, policy details, or triage decisions.
Keep learning
- •The complete AI Agents Roadmap — my full 8-step breakdown
- •Free: The AI Agent Starter Kit — PDF checklist + starter code
- •Work with me — I build AI for banks and insurance companies
By Cyprian Aarons, AI Consultant at Topiax.
Want the complete 8-step roadmap?
Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.
Get the Starter Kit