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

  1. import asyncio
  2. import json
  3. import os
  4. from typing import Literal
  5. from pydantic import BaseModel, Field
  6. from agentscope.agent import ReActAgent
  7. from agentscope.formatter import DashScopeChatFormatter
  8. from agentscope.memory import InMemoryMemory
  9. from agentscope.message import Msg
  10. from agentscope.model import DashScopeChatModel
  11. from agentscope.tool import Toolkit, ToolResponse
  12. router = ReActAgent(
  13. name="Router",
  14. sys_prompt="You're a routing agent. Your target is to route the user query to the right follow-up task.",
  15. model=DashScopeChatModel(
  16. model_name="qwen-max",
  17. api_key=os.environ["DASHSCOPE_API_KEY"],
  18. stream=False,
  19. ),
  20. formatter=DashScopeChatFormatter(),
  21. )
  22. # Use structured output to specify the routing task
  23. class RoutingChoice(BaseModel):
  24. your_choice: Literal[
  25. "Content Generation",
  26. "Programming",
  27. "Information Retrieval",
  28. None,
  29. ] = Field(
  30. description="Choose the right follow-up task, and choose ``None`` if the task is too simple or no suitable task",
  31. )
  32. task_description: str | None = Field(
  33. description="The task description",
  34. default=None,
  35. )
  36. async def example_router_explicit() -> None:
  37. """Example of explicit routing with structured output."""
  38. msg_user = Msg(
  39. "user",
  40. "Help me to write a poem",
  41. "user",
  42. )
  43. # Route the query
  44. msg_res = await router(
  45. msg_user,
  46. structured_model=RoutingChoice,
  47. )
  48. # The structured output is stored in the metadata field
  49. print("The structured output:")
  50. print(json.dumps(msg_res.metadata, indent=4, ensure_ascii=False))
  51. asyncio.run(example_router_explicit())
  1. 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?
  2. The structured output:
  3. {
  4. "your_choice": "Content Generation",
  5. "task_description": "To write a poem based on the user's provided theme or elements."
  6. }

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:

  1. async def generate_python(demand: str) -> ToolResponse:
  2. """Generate Python code based on the demand.
  3. Args:
  4. demand (``str``):
  5. The demand for the Python code.
  6. """
  7. # An example demand agent
  8. python_agent = ReActAgent(
  9. name="PythonAgent",
  10. sys_prompt="You're a Python expert, your target is to generate Python code based on the demand.",
  11. model=DashScopeChatModel(
  12. model_name="qwen-max",
  13. api_key=os.environ["DASHSCOPE_API_KEY"],
  14. stream=False,
  15. ),
  16. memory=InMemoryMemory(),
  17. formatter=DashScopeChatFormatter(),
  18. toolkit=Toolkit(),
  19. )
  20. msg_res = await python_agent(Msg("user", demand, "user"))
  21. return ToolResponse(
  22. content=msg_res.get_content_blocks("text"),
  23. )
  24. # Fake some other tool functions for demonstration purposes
  25. async def generate_poem(demand: str) -> ToolResponse:
  26. """Generate a poem based on the demand.
  27. Args:
  28. demand (``str``):
  29. The demand for the poem.
  30. """
  31. pass
  32. async def web_search(query: str) -> ToolResponse:
  33. """Search the web for the query.
  34. Args:
  35. query (``str``):
  36. The query to search.
  37. """
  38. pass

After that, we define a routing agent and equip it with the above tool functions.

  1. toolkit = Toolkit()
  2. toolkit.register_tool_function(generate_python)
  3. toolkit.register_tool_function(generate_poem)
  4. toolkit.register_tool_function(web_search)
  5. # Initialize the routing agent with the toolkit
  6. router_implicit = ReActAgent(
  7. name="Router",
  8. sys_prompt="You're a routing agent. Your target is to route the user query to the right follow-up task.",
  9. model=DashScopeChatModel(
  10. model_name="qwen-max",
  11. api_key=os.environ["DASHSCOPE_API_KEY"],
  12. stream=False,
  13. ),
  14. formatter=DashScopeChatFormatter(),
  15. toolkit=toolkit,
  16. memory=InMemoryMemory(),
  17. )
  18. async def example_router_implicit() -> None:
  19. """Example of implicit routing with tool calls."""
  20. msg_user = Msg(
  21. "user",
  22. "Help me to generate a quick sort function in Python",
  23. "user",
  24. )
  25. # Route the query
  26. await router_implicit(msg_user)
  27. asyncio.run(example_router_implicit())
  1. Router: {
  2. "type": "tool_use",
  3. "name": "generate_python",
  4. "input": {
  5. "demand": "a quick sort function"
  6. },
  7. "id": "call_97b0e9769a9a41f68573d1"
  8. }
  9. 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.
  10. ```python
  11. def quick_sort(arr):
  12. if len(arr) <= 1:
  13. return arr
  14. else:
  15. pivot = arr[len(arr) // 2]
  16. left = [x for x in arr if x < pivot]
  17. middle = [x for x in arr if x == pivot]
  18. right = [x for x in arr if x > pivot]
  19. return quick_sort(left) + middle + quick_sort(right)
  20. # Example usage:
  21. # sorted_list = quick_sort([3, 6, 8, 10, 1, 2, 1])
  22. # print(sorted_list)
  23. ```
  24. 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.
  25. system: {
  26. "type": "tool_result",
  27. "id": "call_97b0e9769a9a41f68573d1",
  28. "name": "generate_python",
  29. "output": [
  30. {
  31. "type": "text",
  32. "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."
  33. }
  34. ]
  35. }
  36. 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.
  37. ```python
  38. def quick_sort(arr):
  39. if len(arr) <= 1:
  40. return arr
  41. else:
  42. pivot = arr[len(arr) // 2]
  43. left = [x for x in arr if x < pivot]
  44. middle = [x for x in arr if x == pivot]
  45. right = [x for x in arr if x > pivot]
  46. return quick_sort(left) + middle + quick_sort(right)
  47. # Example usage:
  48. # sorted_list = quick_sort([3, 6, 8, 10, 1, 2, 1])
  49. # print(sorted_list)
  50. ```
  51. 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

Download zipped: workflow_routing.zip

Gallery generated by Sphinx-Gallery