Routing between specialists
A router makes one decision before any agent runs: which specialist gets the question. It is cheaper and more predictable than a supervisor, and cannot combine answers.
A supervisor is a model deciding each turn. A router is a single classification step, often one model call or plain rules, that sends the question on and steps aside. With plain rules it is ordinary Python.
import re
from specialists import last_reply, orders_agent, policies_agent
def route(question):
if re.search(r"\b[A-Z]\d+\b", question):
return "orders", orders_agent
return "policies", policies_agent
def answer(question):
name, agent = route(question)
return name, last_reply(agent, question)route picks a specialist by looking for an order id, and answer passes the question on and returns which agent answered.
Pick one to watch it run, step by step.
from router import answer
for question in ["Where is A17?", "Is shipping free?", "Where is A17, and how long does a refund take?"]:
name, reply = answer(question)
print(f"{name:<8} {reply.splitlines()[-1]}")The first two went to the right place without a model deciding anything. The third shows the limit: it mentions an order, so it went to the orders agent alone. That agent read the word "refund" as a refund request, a tool it does not have, so neither half was answered. In lesson 30 the supervisor avoided this by asking each specialist its own question. A router makes one choice; questions that need two agents need a supervisor, or a router that sends to several agents and merges the answers, which the documentation builds with LangGraph.
- Route questions that contain "refund" and an order id to the policies agent, and test both kinds.
- Add a third specialist for account questions and a rule for it.
- Print how many model calls
answermakes for one question.
Little by little, you're building something great.