.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "tutorial/workflow_conversation.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_tutorial_workflow_conversation.py: .. _conversation: Conversation ====================== Conversation is a design pattern that agents exchange and share information between each other, most commonly in game playing, chatbot, and multi-agent discussion scenarios. In AgentScope, the conversation is built upon the **explicit message exchange**. In this tutorial, we will demonstrate how to build a conversation - between a user and an agent (chatbot) - between multiple agents (game playing, discussion, etc.) Their main difference lies in - how the **prompt is constructed**, and - how the information is **propagated/shared** among agents. .. GENERATED FROM PYTHON SOURCE LINES 23-38 .. code-block:: Python import asyncio import json import os from agentscope.agent import ReActAgent, UserAgent from agentscope.memory import InMemoryMemory from agentscope.formatter import ( DashScopeChatFormatter, DashScopeMultiAgentFormatter, ) from agentscope.model import DashScopeChatModel from agentscope.message import Msg from agentscope.pipeline import MsgHub from agentscope.tool import Toolkit .. GENERATED FROM PYTHON SOURCE LINES 39-55 User-Agent Conversation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ User-agent conversation, also known as chatbot, is the most common usage scenario of LLM-empowered agents, and the design target of most LLM APIs. Such conversation features only two participants: a user and an agent. In AgentScope, the formatters with **"Chat"** in its name are designed for user-agent conversation, such as ``DashScopeChatFormatter``, ``AnthropicChatFormatter``, etc. They use the ``role`` field in the message to distinguish the user and the agent, and format the messages accordingly. Here we build a simple conversation between agent ``Friday`` and user. .. tip:: AgentScope provides a built-in ``UserAgent`` class for human-in-the-loop (HITL) interaction. Refer to :ref:`user-agent` for more details. .. GENERATED FROM PYTHON SOURCE LINES 55-71 .. code-block:: Python friday = ReActAgent( name="Friday", sys_prompt="You're a helpful assistant named Friday", model=DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], ), formatter=DashScopeChatFormatter(), # The formatter for user-agent conversation memory=InMemoryMemory(), toolkit=Toolkit(), ) # Create a user agent user = UserAgent(name="User") .. GENERATED FROM PYTHON SOURCE LINES 72-87 Now, we can program the conversation by exchanging messages between these two agents until the user types "exit" to end the conversation. .. code-block:: python async def run_conversation() -> None: """Run a simple conversation between Friday and User.""" msg = None while True: msg = await friday(msg) msg = await user(msg) if msg.get_text_content() == "exit": break asyncio.run(run_conversation()) .. GENERATED FROM PYTHON SOURCE LINES 89-102 More than Two Agents ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ As stated in the beginning, we demonstrate how to build conversation with multiple agents in terms of **prompt construction** and **information sharing**. Prompt Construction ------------------------------- In AgentScope, we provide built-in formatters for multi-agent conversation, featuring **"MultiAgent"** in their names, such as ``DashScopeMultiAgentFormatter``, ``AnthropicMultiAgentFormatter``, etc. Specifically, they use the ``name`` field in the message to distinguish different agents, and format the conversation history into a single user message. Taking ``DashScopeMultiAgentFormatter`` as an example: .. tip:: More details about the formatter can be found in :ref:`prompt`. .. GENERATED FROM PYTHON SOURCE LINES 102-128 .. code-block:: Python async def example_multi_agent_prompt() -> None: msgs = [ Msg("system", "You're a helpful assistant named Bob.", "system"), Msg("Alice", "Hi!", "user"), Msg("Bob", "Hi! Nice to meet you guys.", "assistant"), Msg("Charlie", "Me too! I'm Charlie, by the way.", "assistant"), ] formatter = DashScopeMultiAgentFormatter() prompt = await formatter.format(msgs) print("Formatted prompt:") print(json.dumps(prompt, indent=4, ensure_ascii=False)) # We print the content of the combined user message here for better # understanding: print("-------------") print("Combined message") print(prompt[1]["content"]) asyncio.run(example_multi_agent_prompt()) .. rst-class:: sphx-glr-script-out .. code-block:: none Formatted prompt: [ { "role": "system", "content": "You're a helpful assistant named Bob." }, { "role": "user", "content": "# Conversation History\nThe content between tags contains your conversation history\n\nAlice: Hi!\nBob: Hi! Nice to meet you guys.\nCharlie: Me too! I'm Charlie, by the way.\n" } ] ------------- Combined message # Conversation History The content between tags contains your conversation history Alice: Hi! Bob: Hi! Nice to meet you guys. Charlie: Me too! I'm Charlie, by the way. .. GENERATED FROM PYTHON SOURCE LINES 129-136 Message Sharing ------------------------------- In multi-agent conversation, exchanging messages explicitly may not be efficient and convenient, especially when broadcasting messages among multiple agents. Therefore, AgentScope provides an async context manager named ``MsgHub`` to simplify the operation of broadcasting messages. Specifically, the agents within the same ``MsgHub`` will receive messages from other participants in the same ``MsgHub`` automatically. .. GENERATED FROM PYTHON SOURCE LINES 136-188 .. code-block:: Python model = DashScopeChatModel( model_name="qwen-max", api_key=os.environ["DASHSCOPE_API_KEY"], ) formatter = DashScopeMultiAgentFormatter() alice = ReActAgent( name="Alice", sys_prompt="You're a student named Alice.", model=model, formatter=formatter, toolkit=Toolkit(), memory=InMemoryMemory(), ) bob = ReActAgent( name="Bob", sys_prompt="You're a student named Bob.", model=model, formatter=formatter, toolkit=Toolkit(), memory=InMemoryMemory(), ) charlie = ReActAgent( name="Charlie", sys_prompt="You're a student named Charlie.", model=model, formatter=formatter, toolkit=Toolkit(), memory=InMemoryMemory(), ) async def example_msghub() -> None: """Example of using MsgHub for multi-agent conversation.""" async with MsgHub( [alice, bob, charlie], announcement=Msg( "system", "Now you meet each other with a brief self-introduction.", "system", ), ): await alice() await bob() await charlie() asyncio.run(example_msghub()) .. rst-class:: sphx-glr-script-out .. code-block:: none Alice: Hi there! I'm Alice, a student with a keen interest in technology and the environment. I love exploring how we can use tech to help solve some of the big challenges facing our planet. What about you? Bob: Hi Alice! I'm Bob. It's great to meet you! I'm also a student, and I'm really into sports and fitness. I like to keep active and I'm always looking for new ways to stay healthy. It's cool that you're interested in technology and the environment; those are such important fields! Charlie: Hey Alice and Bob! I'm Charlie, and I'm a student too. I have a bit of an artistic side; I love painting and drawing, and I also enjoy writing short stories. It's awesome to hear about your interests in tech and the environment, Alice, and sports and fitness, Bob. We all seem to have quite diverse interests! .. GENERATED FROM PYTHON SOURCE LINES 189-191 Now we print the memory of Alice to check if her memory is updated correctly. .. GENERATED FROM PYTHON SOURCE LINES 191-202 .. code-block:: Python async def example_memory() -> None: """Print the memory of Alice.""" print("Memory of Alice:") for msg in await alice.memory.get_memory(): print(f"{msg.name}: {msg.get_text_content()}") asyncio.run(example_memory()) .. rst-class:: sphx-glr-script-out .. code-block:: none Memory of Alice: system: Now you meet each other with a brief self-introduction. Alice: Hi there! I'm Alice, a student with a keen interest in technology and the environment. I love exploring how we can use tech to help solve some of the big challenges facing our planet. What about you? Bob: Hi Alice! I'm Bob. It's great to meet you! I'm also a student, and I'm really into sports and fitness. I like to keep active and I'm always looking for new ways to stay healthy. It's cool that you're interested in technology and the environment; those are such important fields! Charlie: Hey Alice and Bob! I'm Charlie, and I'm a student too. I have a bit of an artistic side; I love painting and drawing, and I also enjoy writing short stories. It's awesome to hear about your interests in tech and the environment, Alice, and sports and fitness, Bob. We all seem to have quite diverse interests! .. GENERATED FROM PYTHON SOURCE LINES 203-209 Further Reading ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - :ref:`prompt` - :ref:`pipeline` .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 10.383 seconds) .. _sphx_glr_download_tutorial_workflow_conversation.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: workflow_conversation.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: workflow_conversation.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: workflow_conversation.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_