AutoGen Tutorial (TypeScript): parsing structured output for beginners

By Cyprian AaronsUpdated 2026-04-21
autogenparsing-structured-output-for-beginnerstypescript

This tutorial shows you how to get structured JSON out of an AutoGen TypeScript agent and parse it safely into a typed object. You need this when you want the model to return predictable fields like name, amount, or decision instead of free-form text that breaks downstream logic.

What You'll Need

  • Node.js 18+
  • A TypeScript project with ts-node or a build step
  • AutoGen packages:
    • @autogen/core
    • @autogen/agentchat
  • An LLM provider configured for AutoGen
  • An API key, for example:
    • OPENAI_API_KEY
  • Basic familiarity with:
    • async/await
    • TypeScript interfaces/types
    • JSON parsing

Step-by-Step

  1. Start by installing the packages and setting up your environment. If you already have a TypeScript project, this is just the runtime and AutoGen dependency setup.
npm install @autogen/core @autogen/agentchat zod
npm install -D typescript ts-node @types/node
  1. Define the shape you want back from the model. For beginner-friendly structured output, keep it small and strict so parsing failures are obvious.
// types.ts
export interface RiskSummary {
  customerName: string;
  riskLevel: "low" | "medium" | "high";
  reasons: string[];
}
  1. Create an assistant agent that is instructed to return only valid JSON matching that shape. The important part here is not asking for prose, because prose is what makes parsing fragile.
// agent.ts
import { AssistantAgent } from "@autogen/agentchat";

export const analyst = new AssistantAgent({
  name: "analyst",
  systemMessage:
    "You are a risk analyst. Return ONLY valid JSON with keys customerName, riskLevel, and reasons. No markdown, no code fences.",
});
  1. Run a prompt through the agent and parse the response with JSON.parse. In production, always validate after parsing; raw JSON syntax correctness is not enough.
// main.ts
import { AssistantAgent } from "@autogen/agentchat";
import { z } from "zod";

const RiskSummarySchema = z.object({
  customerName: z.string(),
  riskLevel: z.enum(["low", "medium", "high"]),
  reasons: z.array(z.string()),
});

const analyst = new AssistantAgent({
  name: "analyst",
  systemMessage:
    "You are a risk analyst. Return ONLY valid JSON with keys customerName, riskLevel, and reasons.",
});

async function run() {
  const result = await analyst.run({
    task: "Summarize this customer profile: John Carter, missed two payments, stable income, high credit utilization.",
  });

  const text = result.messages.at(-1)?.content ?? "";
  const parsed = RiskSummarySchema.parse(JSON.parse(text));

  console.log(parsed.customerName);
  console.log(parsed.riskLevel);
  console.log(parsed.reasons);
}

run();
  1. Add a small helper to handle common failure modes. Models sometimes wrap JSON in code fences or add extra text, so strip that before parsing if you need a little more resilience.
function extractJson(text: string): string {
  const trimmed = text.trim();

  if (trimmed.startsWith("```")) {
    return trimmed.replace(/^```(?:json)?\s*/i, "").replace(/```$/, "").trim();
  }

  const firstBrace = trimmed.indexOf("{");
  const lastBrace = trimmed.lastIndexOf("}");

  if (firstBrace !== -1 && lastBrace !== -1) {
    return trimmed.slice(firstBrace, lastBrace + 1);
  }

  return trimmed;
}
  1. Put the helper into your flow so bad formatting does not immediately kill the request. This gives you a practical baseline before you move to stricter schema enforcement later.
async function runWithExtraction() {
  const result = await analyst.run({
    task: "Summarize this customer profile: Maria Lopez, one late payment last year, low debt ratio, long employment history.",
  });

  const text = result.messages.at(-1)?.content ?? "";
  const jsonText = extractJson(text);
  
  const parsed = RiskSummarySchema.parse(JSON.parse(jsonText));
  console.log(JSON.stringify(parsed, null, 2));
}

runWithExtraction();

Testing It

Run the script with npx ts-node main.ts after setting your API key in the environment. If everything is wired correctly, you should see a typed object printed to the console with customerName, riskLevel, and reasons.

Test a few different prompts and make sure the schema still holds when the content changes. If parsing fails often, tighten the system message and reduce ambiguity in the requested output shape.

A good sanity check is to deliberately ask for something messy like “explain your reasoning” and confirm your parser rejects it unless it still contains valid JSON. That tells you your validation is actually doing work instead of silently accepting junk.

Next Steps

  • Add retry logic when JSON parsing fails on the first attempt.
  • Move from manual extraction to stricter schema-guided output patterns.
  • Wrap this in a reusable service method so every agent response gets validated before it reaches your application logic.

Keep learning

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

Related Guides