add_active_agent_router(
builder: StateGraph,
*,
route_to: list[str],
default_active_agent: str| Name | Type | Description |
|---|---|---|
builder* | StateGraph | |
route_to* | list[str] | |
default_active_agent* | str |
Add a router to the currently active agent to the StateGraph.
Example:
from langchain.checkpoint.memory import InMemorySaver
from langchain.agents import create_agent
from langgraph.graph import StateGraph
from langgraph_swarm import SwarmState, create_handoff_tool, add_active_agent_router
def add(a: int, b: int) -> int:
'''Add two numbers'''
return a + b
alice = create_agent(
"openai:gpt-4o",
tools=[
add,
create_handoff_tool(
agent_name="Bob",
description="Transfer to Bob",
),
],
system_prompt="You are Alice, an addition expert.",
name="Alice",
)
bob = create_agent(
"openai:gpt-4o",
tools=[
create_handoff_tool(
agent_name="Alice",
description="Transfer to Alice, she can help with math",
),
],
system_prompt="You are Bob, you speak like a pirate.",
name="Bob",
)
checkpointer = InMemorySaver()
workflow = (
StateGraph(SwarmState)
.add_node(alice, destinations=("Bob",))
.add_node(bob, destinations=("Alice",))
)
# this is the router that enables us to keep track of the last active agent
workflow = add_active_agent_router(
builder=workflow,
route_to=["Alice", "Bob"],
default_active_agent="Alice",
)
# compile the workflow
app = workflow.compile(checkpointer=checkpointer)
config = {"configurable": {"thread_id": "1"}}
turn_1 = app.invoke(
{"messages": [{"role": "user", "content": "i'd like to speak to Bob"}]},
config,
)
turn_2 = app.invoke(
{"messages": [{"role": "user", "content": "what's 5 + 7?"}]},
config,
)The graph builder (StateGraph) to add the router to.
A list of agent (node) names to route to.
Name of the agent to route to by default (if no agents are currently active).