Agent

In this tutorial, we first focus on introducing the ReAct agent in AgentScope, then we briefly introduce how to customize your own agent from scratch.

ReAct Agent

In AgentScope, the ReActAgent class integrates various features into a final implementation, including

Features of ReActAgent

Feature

Reference

Support realtime steering

Support parallel tool calls

Support structured output

Support fine-grained MCP control

MCP

Support agent-controlled tools management (Meta tool)

Tool

Support self-controlled long-term memory

Long-Term Memory

Support automatic state management

State/Session Management

Due to limited space, in this tutorial we only demonstrate the first three features of ReActAgent class, leaving the others to the corresponding sections listed above.

  1. import asyncio
  2. import json
  3. import os
  4. from datetime import datetime
  5. import time
  6. from pydantic import BaseModel, Field
  7. from agentscope.agent import ReActAgent
  8. from agentscope.formatter import DashScopeChatFormatter
  9. from agentscope.memory import InMemoryMemory
  10. from agentscope.message import TextBlock, Msg
  11. from agentscope.model import DashScopeChatModel
  12. from agentscope.tool import Toolkit, ToolResponse

Realtime Steering

The realtime steering allows user to interrupt the agent’s reply at any time, which is implemented based on the asyncio cancellation mechanism.

Specifically, when calling the interrupt method of the agent, it will cancel the current reply task, and execute the handle_interrupt method for postprocessing.

Hint

With the feature of supporting streaming tool results in Tool, users can interrupt the tool execution if it takes too long or deviates from user expectations by Ctrl+C in the terminal or calling the interrupt method of the agent in your code.

The interruption logic has been implemented in the AgentBase class as a basic feature, leaving a handle_interrupt method for users to customize the post-processing of interruption as follows:

  1. # code snippet of AgentBase
  2. class AgentBase:
  3. ...
  4. async def __call__(self, *args: Any, **kwargs: Any) -> Msg:
  5. ...
  6. reply_msg: Msg | None = None
  7. try:
  8. self._reply_task = asyncio.current_task()
  9. reply_msg = await self.reply(*args, **kwargs)
  10. except asyncio.CancelledError:
  11. # Catch the interruption and handle it by the handle_interrupt method
  12. reply_msg = await self.handle_interrupt(*args, **kwargs)
  13. ...
  14. @abstractmethod
  15. async def handle_interrupt(self, *args: Any, **kwargs: Any) -> Msg:
  16. pass

In ReActAgent class, we return a fixed message “I noticed that you have interrupted me. What can I do for you?” as follows:

Example of interruption

Example of interruption

You can override it with your own implementation, for example, calling the LLM to generate a simple response to the interruption.

Parallel Tool Calls

ReActAgent supports parallel tool calls by providing a parallel_tool_calls argument in its constructor. When multiple tool calls are generated, and parallel_tool_calls is set to True, they will be executed in parallel by the asyncio.gather function.

  1. # prepare a tool function
  2. def example_tool_function(tag: str) -> ToolResponse:
  3. """A sample example tool function"""
  4. start_time = datetime.now().strftime("%H:%M:%S.%f")
  5. # Sleep for 3 seconds to simulate a long-running task
  6. time.sleep(3)
  7. end_time = datetime.now().strftime("%H:%M:%S.%f")
  8. return ToolResponse(
  9. content=[
  10. TextBlock(
  11. type="text",
  12. text=f"Tag {tag} started at {start_time} and ended at {end_time}. ",
  13. ),
  14. ],
  15. )
  16. toolkit = Toolkit()
  17. toolkit.register_tool_function(example_tool_function)
  18. # Create an ReAct agent
  19. agent = ReActAgent(
  20. name="Jarvis",
  21. sys_prompt="You're a helpful assistant named Jarvis.",
  22. model=DashScopeChatModel(
  23. model_name="qwen-max",
  24. api_key=os.environ["DASHSCOPE_API_KEY"],
  25. ),
  26. memory=InMemoryMemory(),
  27. formatter=DashScopeChatFormatter(),
  28. toolkit=toolkit,
  29. parallel_tool_calls=True,
  30. )
  31. async def example_parallel_tool_calls() -> None:
  32. """Example of parallel tool calls"""
  33. # prompt the agent to generate two tool calls at once
  34. await agent(
  35. Msg(
  36. "user",
  37. "Generate two tool calls of the 'example_tool_function' function with tag as 'tag1' and 'tag2' AT ONCE so that they can execute in parallel.",
  38. "user",
  39. ),
  40. )
  41. asyncio.run(example_parallel_tool_calls())
  1. Jarvis: {
  2. "type": "tool_use",
  3. "id": "call_ca51caf9577140efa9914e",
  4. "name": "example_tool_function",
  5. "input": {
  6. "tag": "tag1"
  7. }
  8. }
  9. system: {
  10. "type": "tool_result",
  11. "id": "call_ca51caf9577140efa9914e",
  12. "name": "example_tool_function",
  13. "output": [
  14. {
  15. "type": "text",
  16. "text": "Tag tag1 started at 07:46:31.576289 and ended at 07:46:34.579360. "
  17. }
  18. ]
  19. }
  20. Jarvis: {
  21. "type": "tool_use",
  22. "id": "call_6d3a4aec1bfe464f829738",
  23. "name": "example_tool_function",
  24. "input": {
  25. "tag": "tag2"
  26. }
  27. }
  28. system: {
  29. "type": "tool_result",
  30. "id": "call_6d3a4aec1bfe464f829738",
  31. "name": "example_tool_function",
  32. "output": [
  33. {
  34. "type": "text",
  35. "text": "Tag tag2 started at 07:46:37.369972 and ended at 07:46:40.373039. "
  36. }
  37. ]
  38. }
  39. Jarvis: Both function calls to 'example_tool_function' have been executed in parallel. The first call with tag 'tag1' started at 07:46:31.576289 and ended at 07:46:34.579360, while the second call with tag 'tag2' started at 07:46:37.369972 and ended at 07:46:40.373039.

Structured Output

To generate a structured output, the ReActAgent instance receives a child class of the pydantic.BaseModel as the structured_model argument in its __call__ function. Then we can get the structured output from the metadata field of the returned message.

Taking introducing Einstein as an example:

  1. # Create an ReAct agent
  2. agent = ReActAgent(
  3. name="Jarvis",
  4. sys_prompt="You're a helpful assistant named Jarvis.",
  5. model=DashScopeChatModel(
  6. model_name="qwen-max",
  7. api_key=os.environ["DASHSCOPE_API_KEY"],
  8. # Preset the generation kwargs to enable parallel tool calls
  9. generate_kwargs={
  10. "parallel_tool_calls": True,
  11. },
  12. ),
  13. memory=InMemoryMemory(),
  14. formatter=DashScopeChatFormatter(),
  15. toolkit=Toolkit(),
  16. parallel_tool_calls=True,
  17. )
  18. # The structured model
  19. class Model(BaseModel):
  20. name: str = Field(description="The name of the person")
  21. description: str = Field(
  22. description="A one-sentence description of the person",
  23. )
  24. age: int = Field(description="The age")
  25. honor: list[str] = Field(description="A list of honors of the person")
  26. async def example_structured_output() -> None:
  27. """The example structured output"""
  28. res = await agent(
  29. Msg(
  30. "user",
  31. "Introduce Einstein",
  32. "user",
  33. ),
  34. structured_model=Model,
  35. )
  36. print("\nThe structured output:")
  37. print(json.dumps(res.metadata, indent=4))
  38. asyncio.run(example_structured_output())
  1. Jarvis: Albert Einstein was a renowned physicist who developed the theory of relativity, one of the two pillars of modern physics. He is best known for his mass–energy equivalence formula E=mc².
  2. The structured output:
  3. {
  4. "name": "Albert Einstein",
  5. "description": "A theoretical physicist who is widely regarded as one of the most influential scientists of the 20th century.",
  6. "age": 76,
  7. "honor": [
  8. "Nobel Prize in Physics (1921)",
  9. "Copley Medal (1925)",
  10. "Max Planck Medal (1929)"
  11. ]
  12. }

Customizing Agent

AgentScope provides two base classes, AgentBase and ReActAgentBase, which differ in the abstract methods they define and the hooks they support. Specifically, the ReActAgentBase extends AgentBase with additional _reasoning and _acting abstract methods, as well as their pre- and post- hooks.

Developers can choose to inherit from either of these base classes based on their needs. We summarize the agent under agentscope.agent module as follows:

Agent classes in AgentScope

Class

Abstract Method

Support Hooks

Description

AgentBase

reply
observe
print
handleinterrupt
pre/postreply
pre/postobserve
pre/postprint

The base class for all agents, providing the basic interface and hooks.

ReActAgentBase

reply
observe
print
handle_interrupt
_reasoning
_acting
pre/postreply
pre/postobserve
pre/postprint
pre/postreasoning
pre/postacting

The abstract class for ReAct agent, extending AgentBase with reasoning and acting abstract methods and their hooks.

ReActAgent

-

pre/postreply
pre/postobserve
pre/postprint
pre/postreasoning
pre/post_acting

An implementation of ReActAgentBase

UserAgent

A special agent that represents the user, used to interact with the agent

Further Reading

Total running time of the script: (0 minutes 31.818 seconds)

Download Jupyter notebook: task_agent.ipynb

Download Python source code: task_agent.py

Download zipped: task_agent.zip

Gallery generated by Sphinx-Gallery