Skip to main content

Overview

The router pattern is a multi-agent architecture where a routing step classifies input and directs it to specialized agents, with results synthesized into a combined response. This pattern excels when your organization’s knowledge lives across distinct verticals (separate knowledge domains that each require their own agent with specialized tools and prompts). In this tutorial, you’ll build a multi-source knowledge base router that demonstrates these benefits through a realistic enterprise scenario. The system will coordinate three specialists:
  • A GitHub agent that searches code, issues, and pull requests.
  • A Notion agent that searches internal documentation and wikis.
  • A Slack agent that searches relevant threads and discussions.
When a user asks “How do I authenticate API requests?”, the router decomposes the query into source-specific sub-questions, routes them to the relevant agents in parallel, and synthesizes results into a coherent answer.

Why use a router?

The router pattern provides several advantages:
  • Parallel execution: Query multiple sources simultaneously, reducing latency compared to sequential approaches.
  • Specialized agents: Each vertical has focused tools and prompts optimized for its domain.
  • Selective routing: Not every query needs every source—the router intelligently selects relevant verticals.
  • Targeted sub-questions: Each agent receives a question tailored to its domain, improving result quality.
  • Clean synthesis: Results from multiple sources are combined into a single, coherent response.

Concepts

We will cover the following concepts:
Router vs. Subagents: The subagents pattern can also route to multiple agents. Use the router pattern when you need specialized preprocessing, custom routing logic, or want explicit control over parallel execution. Use the subagents pattern when you want the LLM to decide which agents to call dynamically.

Setup

Installation

This tutorial requires the langchain and langgraph packages:
For more details, see our Installation guide.

LangSmith

Set up LangSmith to inspect what is happening inside your agent. Then set the following environment variables:

Select an LLM

Select a chat model from LangChain’s suite of integrations:
👉 Read the OpenAI chat model integration docs

1. Define state

First, define the state schemas. We use three types:
  • AgentInput: Simple state passed to each subagent (just a query)
  • AgentOutput: Result returned by each subagent (source name + result)
  • RouterState: Main workflow state tracking the query, classifications, results, and final answer
The results field uses a reducer (operator.add in Python, a concat function in JS) to collect outputs from parallel agent executions into a single list.

2. Define tools for each vertical

Create tools for each knowledge domain. In a production system, these would call actual APIs. For this tutorial, we use stub implementations that return mock data. We define 7 tools across 3 verticals: GitHub (search code, issues, PRs), Notion (search docs, get page), and Slack (search messages, get thread).

3. Create specialized agents

Create an agent for each vertical. Each agent has domain-specific tools and a prompt optimized for its knowledge source. All three follow the same pattern—only the tools and system prompt differ.

4. Build the router workflow

Now build the router workflow using a StateGraph. The workflow has four main steps:
  1. Classify: Analyze the query and determine which agents to invoke with what sub-questions
  2. Route: Fan out to selected agents in parallel using Send
  3. Query agents: Each agent receives a simple AgentInput and returns an AgentOutput
  4. Synthesize: Combine collected results into a coherent response

5. Compile the workflow

Now assemble the workflow by connecting nodes with edges. The key is using add_conditional_edges with the routing function to enable parallel execution:
The add_conditional_edges call connects the classify node to the agent nodes through the route_to_agents function. When route_to_agents returns multiple Send objects, those nodes execute in parallel.

6. Use the router

Test your router with queries that span multiple knowledge domains:
Expected output:
The router analyzed the query, classified it to determine which agents to invoke (GitHub and Notion, but not Slack for this technical question), queried both agents in parallel, and synthesized the results into a coherent answer.

7. Understanding the architecture

The router workflow follows a clear pattern:

Classification phase

The classify_query function uses structured output to analyze the user’s query and determine which agents to invoke. This is where the routing intelligence lives:
  • Uses a Pydantic model (Python) or Zod schema (JS) to ensure valid output
  • Returns a list of Classification objects, each with a source and targeted query
  • Only includes relevant sources—irrelevant ones are simply omitted
This structured approach is more reliable than free-form JSON parsing and makes the routing logic explicit.

Parallel execution with send

The route_to_agents function maps classifications to Send objects. Each Send specifies the target node and the state to pass:
Each agent node receives a simple AgentInput with just a query field—not the full router state. This keeps the interface clean and explicit.

Result collection with reducers

Agent results flow back to the main state via a reducer. Each agent returns:
The reducer (operator.add in Python) concatenates these lists, collecting all parallel results into state["results"].

Synthesis phase

After all agents complete, the synthesize_results function iterates over the collected results:
  • Waits for all parallel branches to complete (LangGraph handles this automatically)
  • References the original query to ensure the answer addresses what the user asked
  • Combines information from all sources without redundancy
Partial results: In this tutorial, all selected agents must complete before synthesis.

8. Complete working example

Here’s everything together in a runnable script:

9. Advanced: Stateful routers

The router we’ve built so far is stateless (each request is handled independently with no memory between calls). For multi-turn conversations, you need a stateful approach.

Tool wrapper approach

The simplest way to add conversation memory is to wrap the stateless router as a tool that a conversational agent can call:
This approach keeps the router stateless while the conversational agent handles memory and context. The user can have a multi-turn conversation, and the agent will call the router tool as needed.
The tool wrapper approach is recommended for most use cases. It provides clean separation: the router handles multi-source querying, while the conversational agent handles context and memory.

Full persistence approach

If you need the router itself to maintain state—for example, to use previous search results in routing decisions—use persistence to store message history at the router level.
Stateful routers add complexity. When routing to different agents across turns, conversations may feel inconsistent if agents have different tones or prompts. Consider the handoffs pattern or subagents pattern instead—both provide clearer semantics for multi-turn conversations with different agents.

10. Key takeaways

The router pattern excels when you have:
  • Distinct verticals: Separate knowledge domains that each require specialized tools and prompts
  • Parallel query needs: Questions that benefit from querying multiple sources simultaneously
  • Synthesis requirements: Results from multiple sources need to be combined into a coherent response
The pattern has three phases: decompose (analyze the query and generate targeted sub-questions), route (execute queries in parallel), and synthesize (combine results).
When to use the router patternUse the router pattern when you have multiple independent knowledge sources, need low-latency parallel queries, and want explicit control over routing logic.For simpler cases with dynamic tool selection, consider the subagents pattern. For workflows where agents need to converse with users sequentially, consider handoffs.

Next steps