GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing doc.agentscope.io — Agent - AgentScope Note Go to the end to download the full example code. 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
Due to limited space, in this tutorial we only demonstrate the first three
features of import asyncio import json import os from datetime import datetime import time from pydantic import BaseModel, Field from agentscope.agent import ReActAgent from agentscope.formatter import DashScopeChatFormatter from agentscope.memory import InMemoryMemory from agentscope.message import TextBlock, Msg from agentscope.model import DashScopeChatModel 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 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
The interruption logic has been implemented in the # code snippet of AgentBase class AgentBase: ... async def __call__(self, *args: Any, **kwargs: Any) -> Msg: ... reply_msg: Msg | None = None try: self._reply_task = asyncio.current_task() reply_msg = await self.reply(*args, **kwargs) except asyncio.CancelledError: # Catch the interruption and handle it by the handle_interrupt method reply_msg = await self.handle_interrupt(*args, **kwargs) ... @abstractmethod async def handle_interrupt(self, *args: Any, **kwargs: Any) -> Msg: pass In
Example of interruption¶ You can override it with your own implementation, for example, calling the LLM to generate a simple response to the interruption. Memory Compression¶As conversations grow longer, the token count in memory can exceed model context
limits or slow down inference. Basic Usage To enable memory compression, provide a from agentscope.agent import ReActAgent from agentscope.token import CharTokenCounter agent = ReActAgent( name="Assistant", sys_prompt="You are a helpful assistant.", model=model, formatter=formatter, compression_config=ReActAgent.CompressionConfig( enable=True, agent_token_counter=CharTokenCounter(), # The token counter for the agent trigger_threshold=10000, # Trigger compression when exceeding 10000 tokens keep_recent=3, # Keep the most recent 3 messages uncompressed ), ) When memory compression is enabled, the agent monitors the token count in its memory.
Once it exceeds the
Important The compression uses a marking mechanism rather than replacing messages. Old messages are marked as compressed and excluded from future retrievals via By default, the compressed summary is structured into five key fields:
Customizing Compression You can customize how compression works by specifying
Here’s an example of customizing the compression: from pydantic import BaseModel, Field # Define a custom summary structure class CustomSummary(BaseModel): main_topic: str = Field( max_length=200, description="The main topic of the conversation" ) key_points: str = Field( max_length=400, description="Important points discussed" ) pending_tasks: str = Field( max_length=200, description="Tasks that remain to be done" ) # Create agent with custom compression configuration agent = ReActAgent( name="Assistant", sys_prompt="You are a helpful assistant.", model=model, formatter=formatter, compression_config=ReActAgent.CompressionConfig( enable=True, agent_token_counter=CharTokenCounter(), trigger_threshold=10000, keep_recent=3, # Custom schema for structured summary summary_schema=CustomSummary, # Custom prompt to guide compression compression_prompt=( "<system-hint>Please summarize the above conversation " "focusing on the main topic, key discussion points, " "and any pending tasks.</system-hint>" ), # Custom template to format the summary summary_template=( "<system-info>Conversation Summary:\n" "Main Topic: {main_topic}\n\n" "Key Points:\n{key_points}\n\n" "Pending Tasks:\n{pending_tasks}" "</system-info>" ), ), ) The Note The agent ensures that tool use and tool result pairs are kept together during compression to maintain the integrity of the conversation flow. Tip You can use a smaller, faster model for compression by specifying a different Parallel Tool Calls¶
Note The parallel tool execution in Note When running, please ensure that parallel tool calling is supported at the model level and the corresponding parameters are set correctly (can be passed through # prepare a tool function async def example_tool_function(tag: str) -> ToolResponse: """A sample example tool function""" start_time = datetime.now().strftime("%H:%M:%S.%f") # Sleep for 3 seconds to simulate a long-running task await asyncio.sleep(3) end_time = datetime.now().strftime("%H:%M:%S.%f") return ToolResponse( content=[ TextBlock( type="text", text=f"Tag {tag} started at {start_time} and ended at {end_time}. ", ), ], ) toolkit = Toolkit() toolkit.register_tool_function(example_tool_function) # Create an ReAct agent agent = ReActAgent( name="Jarvis", sys_prompt="You're a helpful assistant named Jarvis.", model=DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], # Preset the generation kwargs to enable parallel tool calls generate_kwargs={ "parallel_tool_calls": True, }, ), memory=InMemoryMemory(), formatter=DashScopeChatFormatter(), toolkit=toolkit, parallel_tool_calls=True, ) async def example_parallel_tool_calls() -> None: """Example of parallel tool calls""" # prompt the agent to generate two tool calls at once await agent( Msg( "user", "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.", "user", ), ) asyncio.run(example_parallel_tool_calls()) Jarvis: {
"type": "tool_use",
"id": "call_38b65c2e73454d0281fffa",
"name": "example_tool_function",
"input": {
"tag": "tag1"
},
"raw_input": "{\"tag\": \"tag1\"}"
}
Jarvis: {
"type": "tool_use",
"id": "call_0700193136494b28bf1f5a",
"name": "example_tool_function",
"input": {
"tag": "tag2"
},
"raw_input": "{\"tag\": \"tag2\"}"
}
system: {
"type": "tool_result",
"id": "call_38b65c2e73454d0281fffa",
"name": "example_tool_function",
"output": [
{
"type": "text",
"text": "Tag tag1 started at 08:42:07.808456 and ended at 08:42:10.811685. "
}
]
}
system: {
"type": "tool_result",
"id": "call_0700193136494b28bf1f5a",
"name": "example_tool_function",
"output": [
{
"type": "text",
"text": "Tag tag2 started at 08:42:07.808508 and ended at 08:42:10.812372. "
}
]
}
Jarvis: The 'example_tool_function' has been called in parallel with the tags 'tag1' and 'tag2'. Here are the results:
- For tag1, the function started at 08:42:07.808456 and ended at 08:42:10.811685.
- For tag2, the function started at 08:42:07.808508 and ended at 08:42:10.812372.
Both calls have executed successfully.
Structured Output¶To generate a structured output, the Taking introducing Einstein as an example: # Create an ReAct agent agent = ReActAgent( name="Jarvis", sys_prompt="You're a helpful assistant named Jarvis.", model=DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], # Preset the generation kwargs to enable parallel tool calls generate_kwargs={ "parallel_tool_calls": True, }, ), memory=InMemoryMemory(), formatter=DashScopeChatFormatter(), toolkit=Toolkit(), parallel_tool_calls=True, ) # The structured model class Model(BaseModel): name: str = Field(description="The name of the person") description: str = Field( description="A one-sentence description of the person", ) age: int = Field(description="The age") honor: list[str] = Field(description="A list of honors of the person") async def example_structured_output() -> None: """The example structured output""" res = await agent( Msg( "user", "Introduce Einstein", "user", ), structured_model=Model, ) print("\nThe structured output:") print(json.dumps(res.metadata, indent=4)) asyncio.run(example_structured_output()) /home/runner/work/agentscope/agentscope/src/agentscope/model/_dashscope_model.py:232: DeprecationWarning: 'required' is not supported by DashScope API. It will be converted to 'auto'.
warnings.warn(
Jarvis: {
"type": "tool_use",
"id": "call_bf833e4e387a4a498f8632",
"name": "generate_response",
"input": {
"name": "Albert Einstein",
"description": "A renowned theoretical physicist, best known for developing the theory of relativity.",
"age": 76,
"honor": [
"Nobel Prize in Physics (1921)",
"Copley Medal (1925)",
"Max Planck Medal (1929)"
]
},
"raw_input": "{\"name\": \"Albert Einstein\", \"description\": \"A renowned theoretical physicist, best known for developing the theory of relativity.\", \"age\": 76, \"honor\": [\"Nobel Prize in Physics (1921)\", \"Copley Medal (1925)\", \"Max Planck Medal (1929)\"]}"
}
system: {
"type": "tool_result",
"id": "call_bf833e4e387a4a498f8632",
"name": "generate_response",
"output": [
{
"type": "text",
"text": "Successfully generated response."
}
]
}
Jarvis: Albert Einstein was a renowned theoretical physicist, celebrated for his groundbreaking contributions to the field of physics, most notably the development of the theory of relativity. Born in 1879, Einstein's work profoundly influenced the way we understand the universe. He lived to be 76 years old, during which time he received numerous accolades for his scientific achievements. Among these honors were the Nobel Prize in Physics in 1921, the Copley Medal in 1925, and the Max Planck Medal in 1929. His legacy continues to inspire and challenge scientists around the world.
The structured output:
{
"name": "Albert Einstein",
"description": "A renowned theoretical physicist, best known for developing the theory of relativity.",
"age": 76,
"honor": [
"Nobel Prize in Physics (1921)",
"Copley Medal (1925)",
"Max Planck Medal (1929)"
]
}
Customizing Agent¶AgentScope provides two base classes, Developers can choose to inherit from either of these base classes based on their needs.
We summarize the agent under
Further Reading¶Total running time of the script: (0 minutes 29.667 seconds) | ||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |