.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "build_tutorial/agent.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_build_tutorial_agent.py: .. _build-agent: Build Agent ==================== AgentScope supports to build LLM-empowered agents by providing a basic agent class `agentscope.agents.AgentBase`. In the following, we will build a simple dialog agent that can interact with the others. .. GENERATED FROM PYTHON SOURCE LINES 15-23 .. code-block:: Python from agentscope.agents import AgentBase from agentscope.memory import TemporaryMemory from agentscope.message import Msg from agentscope.models import DashScopeChatWrapper import json .. GENERATED FROM PYTHON SOURCE LINES 24-43 Define the Agent -------------------------------- We define a `DialogAgent` class by inheriting from `agentscope.agents.AgentBase`, and implement the constructor and `reply` methods to make the agent work. Within the constructor, we initialize the agent with its name, system prompt, memory, and model. In this example, we take `qwen-max` in DashScope Chat API for model serving. You can replace it with other model wrappers under `agentscope.models`. The `reply` method is the core of the agent, which takes message(s) as input and returns a reply message. Within the method, we implement the basic logic of the agent: - record the input message in memory, - construct the prompt with system prompt and memory, - call the model to get the response, - record the response in memory and return it. .. GENERATED FROM PYTHON SOURCE LINES 43-86 .. code-block:: Python class JarvisAgent(AgentBase): def __init__(self): super().__init__("Jarvis") self.name = "Jarvis" self.sys_prompt = "You're a helpful assistant named Jarvis." self.memory = TemporaryMemory() self.model = DashScopeChatWrapper( config_name="_", model_name="qwen-max", ) def reply(self, msg): # Record the message in memory self.memory.add(msg) # Construct the prompt with system prompt and memory prompt = self.model.format( Msg( name="system", content=self.sys_prompt, role="system", ), self.memory.get_memory(), ) # Call the model to get the response response = self.model(prompt) # Record the response in memory and return it msg = Msg( name=self.name, content=response.text, role="assistant", ) self.memory.add(msg) self.speak(msg) return msg .. GENERATED FROM PYTHON SOURCE LINES 87-90 After creating the agent class, we can instantiate it and interact with it by sending messages. .. GENERATED FROM PYTHON SOURCE LINES 90-106 .. code-block:: Python jarvis = JarvisAgent() msg = Msg( name="user", content="Hi! Jarvis.", role="user", ) msg_reply = jarvis(msg) print(f"The sender name of the replied message: {msg_reply.name}") print(f"The role of the sender: {msg_reply.role}") print(f"The content of the replied message: {msg_reply.content}") .. rst-class:: sphx-glr-script-out .. code-block:: none Jarvis: Hello! How can I assist you today? The sender name of the replied message: Jarvis The role of the sender: assistant The content of the replied message: Hello! How can I assist you today? .. GENERATED FROM PYTHON SOURCE LINES 107-121 ====================== Components ---------- Now we briefly introduce the basic components of the above agent, including * memory * model Memory ^^^^^^^ The [memory module](#memory) provides basic operations for memory management, including adding, deleting and getting memory. .. GENERATED FROM PYTHON SOURCE LINES 121-135 .. code-block:: Python memory = TemporaryMemory() # Add a message memory.add(Msg("system", "You're a helpful assistant named Jarvis.", "system")) # Add multiple messages at once memory.add( [ Msg("Stank", "Hi!", "user"), Msg("Jarvis", "How can I help you?", "assistant"), ], ) print(f"The current memory: {memory.get_memory()}") print(f"The current size: {memory.size()}") .. rst-class:: sphx-glr-script-out .. code-block:: none The current memory: [Msg(id='5182bd10691847c4880c0e29ad9b3fd3', name='system', role='system', content="You're a helpful assistant named Jarvis.", metadata=None, timestamp='2025-09-09 06:19:53'), Msg(id='89ed4f79da7f47d19e498f29a12abbd0', name='Stank', role='user', content='Hi!', metadata=None, timestamp='2025-09-09 06:19:53'), Msg(id='12383b77f6f94f52a50afdcf0f941ed9', name='Jarvis', role='assistant', content='How can I help you?', metadata=None, timestamp='2025-09-09 06:19:53')] The current size: 3 .. GENERATED FROM PYTHON SOURCE LINES 136-138 Obtain the last two messages with parameter `recent_n`. .. GENERATED FROM PYTHON SOURCE LINES 138-145 .. code-block:: Python recent_two_msgs = memory.get_memory(recent_n=2) for i, msg in enumerate(recent_two_msgs): print( f"MSG{i}: Sender: {msg.name}, Role: {msg.role}, Content: {msg.content}", ) .. rst-class:: sphx-glr-script-out .. code-block:: none MSG0: Sender: Stank, Role: user, Content: Hi! MSG1: Sender: Jarvis, Role: assistant, Content: How can I help you? .. GENERATED FROM PYTHON SOURCE LINES 146-147 Delete the first message within the memory. .. GENERATED FROM PYTHON SOURCE LINES 147-151 .. code-block:: Python memory.delete(0) print(f"The memory after deletion: {memory.get_memory()}") print(f"The size after deletion: {memory.size()}") .. rst-class:: sphx-glr-script-out .. code-block:: none The memory after deletion: [Msg(id='89ed4f79da7f47d19e498f29a12abbd0', name='Stank', role='user', content='Hi!', metadata=None, timestamp='2025-09-09 06:19:53'), Msg(id='12383b77f6f94f52a50afdcf0f941ed9', name='Jarvis', role='assistant', content='How can I help you?', metadata=None, timestamp='2025-09-09 06:19:53')] The size after deletion: 2 .. GENERATED FROM PYTHON SOURCE LINES 152-160 Model ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The `agentscope.models` module encapsulates different model API, and provides basic prompt engineering strategies for different APIs in their `format` function. Take DashScope Chat API as an example: .. GENERATED FROM PYTHON SOURCE LINES 160-174 .. code-block:: Python messages = [ Msg("system", "You're a helpful assistant named Jarvis.", "system"), Msg("Stank", "Hi!", "user"), Msg("Jarvis", "How can I help you?", "assistant"), ] model = DashScopeChatWrapper( config_name="api", model_name="qwen-max", ) prompt = model.format(messages) print(json.dumps(prompt, indent=4)) .. rst-class:: sphx-glr-script-out .. code-block:: none [ { "role": "system", "content": [ { "text": "You're a helpful assistant named Jarvis." } ] }, { "role": "user", "content": [ { "text": "## Conversation History\nStank: Hi!\nJarvis: How can I help you?" } ] } ] .. GENERATED FROM PYTHON SOURCE LINES 175-179 Further Reading --------------------- - :ref:`builtin_agent` - :ref:`model_api` .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 2.381 seconds) .. _sphx_glr_download_build_tutorial_agent.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: agent.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: agent.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: agent.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_