AutoGen Tutorial (TypeScript): building conditional routing for beginners

By Cyprian AaronsUpdated 2026-04-21
autogenbuilding-conditional-routing-for-beginnerstypescript

This tutorial shows you how to build a simple conditional router in AutoGen TypeScript: one agent classifies an incoming request, then your code routes it to the right specialist agent. You need this when you want deterministic control over multi-agent flows instead of letting every request fan out to every agent.

What You'll Need

  • Node.js 18+ installed
  • A TypeScript project with ts-node or a build step
  • AutoGen TypeScript packages:
    • @autogen/core
    • @autogen/openai
  • An OpenAI API key set as OPENAI_API_KEY
  • Basic familiarity with:
    • async/await
    • TypeScript classes
    • running scripts from the command line

Step-by-Step

  1. Start by installing the packages and setting up a minimal TypeScript project. If you already have a project, just add the dependencies and skip the init commands.
npm init -y
npm install @autogen/core @autogen/openai
npm install -D typescript ts-node @types/node
npx tsc --init
  1. Create a small router agent that classifies each message into one of three buckets: billing, claims, or general. The important part is that this agent returns structured JSON so your application can route without guessing.
import { OpenAIChatCompletionClient } from "@autogen/openai";
import { AssistantAgent } from "@autogen/core";

const modelClient = new OpenAIChatCompletionClient({
  model: "gpt-4o-mini",
  apiKey: process.env.OPENAI_API_KEY,
});

const routerAgent = new AssistantAgent({
  name: "router",
  modelClient,
  systemMessage: `
You classify user requests into exactly one label:
billing, claims, general

Return only valid JSON:
{"route":"billing"} or {"route":"claims"} or {"route":"general"}
`,
});
  1. Create three specialist agents that handle each route. In real systems these would connect to tools, internal APIs, or policy documents; here they just produce focused responses.
import { AssistantAgent } from "@autogen/core";

const billingAgent = new AssistantAgent({
  name: "billing_agent",
  modelClient,
  systemMessage: "You answer billing questions for an insurance product.",
});

const claimsAgent = new AssistantAgent({
  name: "claims_agent",
  modelClient,
  systemMessage: "You answer claims questions for an insurance product.",
});

const generalAgent = new AssistantAgent({
  name: "general_agent",
  modelClient,
  systemMessage: "You answer general customer support questions.",
});
  1. Add a routing function that asks the router agent for a decision, parses the JSON, and dispatches to the right specialist. This is the core pattern: keep routing logic in code, not in prompt soup.
type Route = "billing" | "claims" | "general";

async function getRoute(message: string): Promise<Route> {
  const result = await routerAgent.run(message);
  const text = result.messages[result.messages.length - 1]?.content ?? "{}";
  const parsed = JSON.parse(text) as { route?: Route };

  if (parsed.route === "billing" || parsed.route === "claims" || parsed.route === "general") {
    return parsed.route;
  }

  return "general";
}

async function handleMessage(message: string): Promise<string> {
  const route = await getRoute(message);

  if (route === "billing") {
    const result = await billingAgent.run(message);
    return result.messages[result.messages.length - 1]?.content ?? "";
  }

  if (route === "claims") {
    const result = await claimsAgent.run(message);
    return result.messages[result.messages.length - 1]?.content ?? "";
  }

  const result = await generalAgent.run(message);
  return result.messages[result.messages.length - 1]?.content ?? "";
}
  1. Wire everything together in a runnable script and test it with a few example prompts. This gives you a complete baseline you can extend with confidence checks, thresholds, or human handoff.
async function main() {
  const samples = [
    "I need to update my payment method for my policy.",
    "My claim was denied and I want to know why.",
    "What documents do I need to file a complaint?",
  ];

  for (const sample of samples) {
    const response = await handleMessage(sample);
    console.log("\nUSER:", sample);
    console.log("ASSISTANT:", response);
  }
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});

Testing It

Run the script with npx ts-node index.ts after exporting your API key. You should see each input routed to a different specialist based on intent, not on hardcoded keywords alone.

Check the router output first if something looks wrong. In production, log both the selected route and the raw router response so you can spot malformed JSON or misclassification quickly.

If you want stricter behavior, add schema validation before dispatching. That prevents bad model output from crashing your flow and gives you a clean fallback path like general or human escalation.

Next Steps

  • Add Zod validation for the router JSON before calling JSON.parse
  • Replace specialist prompts with tool-backed agents that call internal APIs
  • Extend routing from one label to multiple conditions, such as priority, language, and customer tier

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