Routing
There are two ways to implement routing in AgentScope, both simple and easy to implement:
Routing by structured output
Routing by tool calls
Tip
Considering there is no unified standard/definition for agent routing, we follow the setting in Building effective agents
Routing by Structured Output
By this way, we can directly use the structured output of the agent to determine which agent to route the message to.
Initialize a routing agent
import asyncioimport jsonimport osfrom typing import Literalfrom pydantic import BaseModel, Fieldfrom agentscope.agent import ReActAgentfrom agentscope.formatter import DashScopeChatFormatterfrom agentscope.memory import InMemoryMemoryfrom agentscope.message import Msgfrom agentscope.model import DashScopeChatModelfrom agentscope.tool import Toolkit, ToolResponserouter = ReActAgent(name="Router",sys_prompt="You're a routing agent. Your target is to route the user query to the right follow-up task.",model=DashScopeChatModel(model_name="qwen-max",api_key=os.environ["DASHSCOPE_API_KEY"],stream=False,),formatter=DashScopeChatFormatter(),)# Use structured output to specify the routing taskclass RoutingChoice(BaseModel):your_choice: Literal["Content Generation","Programming","Information Retrieval",None,] = Field(description="Choose the right follow-up task, and choose ``None`` if the task is too simple or no suitable task",)task_description: str | None = Field(description="The task description",default=None,)async def example_router_explicit() -> None:"""Example of explicit routing with structured output."""msg_user = Msg("user","Help me to write a poem","user",)# Route the querymsg_res = await router(msg_user,structured_model=RoutingChoice,)# The structured output is stored in the metadata fieldprint("The structured output:")print(json.dumps(msg_res.metadata, indent=4, ensure_ascii=False))asyncio.run(example_router_explicit())
Router: Of course, I can help with that. Could you please give me a theme or some elements you'd like to include in the poem?The structured output:{"your_choice": "Content Generation","task_description": "To write a poem based on the user's provided theme or elements."}
Routing by Tool Calls
Another way is to wrap the downstream agents into a tool function, so that the routing agent decides which tool to call based on the user query.
We first define several tool functions:
async def generate_python(demand: str) -> ToolResponse:"""Generate Python code based on the demand.Args:demand (``str``):The demand for the Python code."""# An example demand agentpython_agent = ReActAgent(name="PythonAgent",sys_prompt="You're a Python expert, your target is to generate Python code based on the demand.",model=DashScopeChatModel(model_name="qwen-max",api_key=os.environ["DASHSCOPE_API_KEY"],stream=False,),memory=InMemoryMemory(),formatter=DashScopeChatFormatter(),toolkit=Toolkit(),)msg_res = await python_agent(Msg("user", demand, "user"))return ToolResponse(content=msg_res.get_content_blocks("text"),)# Fake some other tool functions for demonstration purposesasync def generate_poem(demand: str) -> ToolResponse:"""Generate a poem based on the demand.Args:demand (``str``):The demand for the poem."""passasync def web_search(query: str) -> ToolResponse:"""Search the web for the query.Args:query (``str``):The query to search."""pass
After that, we define a routing agent and equip it with the above tool functions.
toolkit = Toolkit()toolkit.register_tool_function(generate_python)toolkit.register_tool_function(generate_poem)toolkit.register_tool_function(web_search)# Initialize the routing agent with the toolkitrouter_implicit = ReActAgent(name="Router",sys_prompt="You're a routing agent. Your target is to route the user query to the right follow-up task.",model=DashScopeChatModel(model_name="qwen-max",api_key=os.environ["DASHSCOPE_API_KEY"],stream=False,),formatter=DashScopeChatFormatter(),toolkit=toolkit,memory=InMemoryMemory(),)async def example_router_implicit() -> None:"""Example of implicit routing with tool calls."""msg_user = Msg("user","Help me to generate a quick sort function in Python","user",)# Route the queryawait router_implicit(msg_user)asyncio.run(example_router_implicit())
Router: {"type": "tool_use","name": "generate_python","input": {"demand": "a quick sort function"},"id": "call_97b0e9769a9a41f68573d1"}PythonAgent: Here is a quick sort function implemented in Python. This function sorts the elements of a list in ascending order using the Quick Sort algorithm.```pythondef quick_sort(arr):if len(arr) <= 1:return arrelse:pivot = arr[len(arr) // 2]left = [x for x in arr if x < pivot]middle = [x for x in arr if x == pivot]right = [x for x in arr if x > pivot]return quick_sort(left) + middle + quick_sort(right)# Example usage:# sorted_list = quick_sort([3, 6, 8, 10, 1, 2, 1])# print(sorted_list)```You can use the `quick_sort` function by passing an unsorted list to it, and it will return a new list with the elements sorted. If you want to test it out, just remove the `#` at the beginning of the example usage lines and run the code.system: {"type": "tool_result","id": "call_97b0e9769a9a41f68573d1","name": "generate_python","output": [{"type": "text","text": "Here is a quick sort function implemented in Python. This function sorts the elements of a list in ascending order using the Quick Sort algorithm.\n\n```python\ndef quick_sort(arr):\n if len(arr) <= 1:\n return arr\n else:\n pivot = arr[len(arr) // 2]\n left = [x for x in arr if x < pivot]\n middle = [x for x in arr if x == pivot]\n right = [x for x in arr if x > pivot]\n return quick_sort(left) + middle + quick_sort(right)\n\n# Example usage:\n# sorted_list = quick_sort([3, 6, 8, 10, 1, 2, 1])\n# print(sorted_list)\n```\n\nYou can use the `quick_sort` function by passing an unsorted list to it, and it will return a new list with the elements sorted. If you want to test it out, just remove the `#` at the beginning of the example usage lines and run the code."}]}Router: Here is a quick sort function implemented in Python. This function sorts the elements of a list in ascending order using the Quick Sort algorithm.```pythondef quick_sort(arr):if len(arr) <= 1:return arrelse:pivot = arr[len(arr) // 2]left = [x for x in arr if x < pivot]middle = [x for x in arr if x == pivot]right = [x for x in arr if x > pivot]return quick_sort(left) + middle + quick_sort(right)# Example usage:# sorted_list = quick_sort([3, 6, 8, 10, 1, 2, 1])# print(sorted_list)```You can use the `quick_sort` function by passing an unsorted list to it, and it will return a new list with the elements sorted. If you want to test it out, just remove the `#` at the beginning of the example usage lines and run the code.
Total running time of the script: (0 minutes 32.325 seconds)
Download Jupyter notebook: workflow_routing.ipynb
Download Python source code: workflow_routing.py