AutoGen Tutorial (Python): building conditional routing for beginners

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

This tutorial shows you how to build a simple conditional router in AutoGen with Python, where one agent decides whether a request should go to a support agent, a billing agent, or be handled directly. You need this when you want your agent system to stop being a single linear chat and start making deterministic routing decisions based on message content.

What You'll Need

  • Python 3.10+
  • pyautogen installed
  • An OpenAI API key set in your environment
  • Basic familiarity with AutoGen agents and AssistantAgent
  • A local terminal or notebook to run the code

Install the package:

pip install pyautogen

Set your API key:

export OPENAI_API_KEY="your_key_here"

Step-by-Step

  1. Start by creating three agents: a router, a support agent, and a billing agent. The router will not answer the user directly; it will only decide which path to take based on the latest message.
import os
from autogen import AssistantAgent

config_list = [
    {
        "model": "gpt-4o-mini",
        "api_key": os.environ["OPENAI_API_KEY"],
    }
]

router = AssistantAgent(
    name="router",
    llm_config={"config_list": config_list},
)

support_agent = AssistantAgent(
    name="support_agent",
    llm_config={"config_list": config_list},
)

billing_agent = AssistantAgent(
    name="billing_agent",
    llm_config={"config_list": config_list},
)
  1. Define a routing function that inspects the user text and returns a route label. For beginners, keep this deterministic with keyword matching so you can understand the control flow before moving to LLM-based routing.
def choose_route(message: str) -> str:
    text = message.lower()

    if any(word in text for word in ["invoice", "refund", "charge", "billing", "payment"]):
        return "billing"
    if any(word in text for word in ["password", "login", "error", "bug", "account"]):
        return "support"
    return "general"
  1. Add handlers for each route. The support and billing agents can answer directly, while general requests get a short fallback response from the router path.
def handle_support(message: str) -> str:
    return support_agent.generate_reply(
        messages=[{"role": "user", "content": message}]
    )

def handle_billing(message: str) -> str:
    return billing_agent.generate_reply(
        messages=[{"role": "user", "content": message}]
    )

def handle_general(message: str) -> str:
    return f"General handler: I can help route this later, but for now I received: {message}"
  1. Wrap everything in one orchestration function. This is the actual conditional routing layer: it selects the route first, then calls the correct handler.
def route_message(message: str):
    route = choose_route(message)

    if route == "billing":
        response = handle_billing(message)
    elif route == "support":
        response = handle_support(message)
    else:
        response = handle_general(message)

    return {"route": route, "response": response}
  1. Run a few test messages so you can see the decision boundary in action. This is where beginners usually realize that routing is just regular Python control flow around AutoGen agents.
tests = [
    "I was charged twice for my invoice",
    "I can't log into my account",
    "Can you explain how your product works?"
]

for msg in tests:
    result = route_message(msg)
    print("=" * 40)
    print("Message:", msg)
    print("Route:", result["route"])
    print("Response:", result["response"])

Testing It

Run the script and confirm each input lands on the expected branch. Billing-related words like invoice and charged should map to billing, while login and account issues should map to support. If you get an error about missing credentials, check that OPENAI_API_KEY is exported in the same shell session before running Python.

If you want stronger verification, add more test cases and print only the returned route first. That makes it easier to debug false positives before you inspect full agent responses.

Next Steps

  • Replace keyword routing with an LLM classifier agent that returns structured JSON.
  • Add confidence thresholds so ambiguous requests can go to a fallback or human handoff.
  • Extend the router to support more branches like fraud, onboarding, and escalation.

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