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.

  1. import asyncio
  2. import json
  3. import os
  4. from agentscope.agent import ReActAgent, UserAgent
  5. from agentscope.memory import InMemoryMemory
  6. from agentscope.formatter import (
  7. DashScopeChatFormatter,
  8. DashScopeMultiAgentFormatter,
  9. )
  10. from agentscope.model import DashScopeChatModel
  11. from agentscope.message import Msg
  12. from agentscope.pipeline import MsgHub
  13. from agentscope.tool import Toolkit

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 user-agent for more details.

  1. friday = ReActAgent(
  2. name="Friday",
  3. sys_prompt="You're a helpful assistant named Friday",
  4. model=DashScopeChatModel(
  5. model_name="qwen-max",
  6. api_key=os.environ["DASHSCOPE_API_KEY"],
  7. ),
  8. formatter=DashScopeChatFormatter(), # The formatter for user-agent conversation
  9. memory=InMemoryMemory(),
  10. toolkit=Toolkit(),
  11. )
  12. # Create a user agent
  13. user = UserAgent(name="User")

Now, we can program the conversation by exchanging messages between these two agents until the user types “exit” to end the conversation.

  1. async def run_conversation() -> None:
  2. """Run a simple conversation between Friday and User."""
  3. msg = None
  4. while True:
  5. msg = await friday(msg)
  6. msg = await user(msg)
  7. if msg.get_text_content() == "exit":
  8. break
  9. asyncio.run(run_conversation())

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 Prompt Formatter.

  1. async def example_multi_agent_prompt() -> None:
  2. msgs = [
  3. Msg("system", "You're a helpful assistant named Bob.", "system"),
  4. Msg("Alice", "Hi!", "user"),
  5. Msg("Bob", "Hi! Nice to meet you guys.", "assistant"),
  6. Msg("Charlie", "Me too! I'm Charlie, by the way.", "assistant"),
  7. ]
  8. formatter = DashScopeMultiAgentFormatter()
  9. prompt = await formatter.format(msgs)
  10. print("Formatted prompt:")
  11. print(json.dumps(prompt, indent=4, ensure_ascii=False))
  12. # We print the content of the combined user message here for better
  13. # understanding:
  14. print("-------------")
  15. print("Combined message")
  16. print(prompt[1]["content"])
  17. asyncio.run(example_multi_agent_prompt())
  1. Formatted prompt:
  2. [
  3. {
  4. "role": "system",
  5. "content": "You're a helpful assistant named Bob."
  6. },
  7. {
  8. "role": "user",
  9. "content": "# Conversation History\nThe content between <history></history> tags contains your conversation history\n<history>\nAlice: Hi!\nBob: Hi! Nice to meet you guys.\nCharlie: Me too! I'm Charlie, by the way.\n</history>"
  10. }
  11. ]
  12. -------------
  13. Combined message
  14. # Conversation History
  15. The content between <history></history> tags contains your conversation history
  16. <history>
  17. Alice: Hi!
  18. Bob: Hi! Nice to meet you guys.
  19. Charlie: Me too! I'm Charlie, by the way.
  20. </history>

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.

  1. model = DashScopeChatModel(
  2. model_name="qwen-max",
  3. api_key=os.environ["DASHSCOPE_API_KEY"],
  4. )
  5. formatter = DashScopeMultiAgentFormatter()
  6. alice = ReActAgent(
  7. name="Alice",
  8. sys_prompt="You're a student named Alice.",
  9. model=model,
  10. formatter=formatter,
  11. toolkit=Toolkit(),
  12. memory=InMemoryMemory(),
  13. )
  14. bob = ReActAgent(
  15. name="Bob",
  16. sys_prompt="You're a student named Bob.",
  17. model=model,
  18. formatter=formatter,
  19. toolkit=Toolkit(),
  20. memory=InMemoryMemory(),
  21. )
  22. charlie = ReActAgent(
  23. name="Charlie",
  24. sys_prompt="You're a student named Charlie.",
  25. model=model,
  26. formatter=formatter,
  27. toolkit=Toolkit(),
  28. memory=InMemoryMemory(),
  29. )
  30. async def example_msghub() -> None:
  31. """Example of using MsgHub for multi-agent conversation."""
  32. async with MsgHub(
  33. [alice, bob, charlie],
  34. announcement=Msg(
  35. "system",
  36. "Now you meet each other with a brief self-introduction.",
  37. "system",
  38. ),
  39. ):
  40. await alice()
  41. await bob()
  42. await charlie()
  43. asyncio.run(example_msghub())
  1. Alice: Hello! I'm Alice, a student with a passion for learning and exploring new ideas. It's nice to meet you. Could you tell me a bit about yourself?
  2. Bob: Hello Alice! I'm Bob, and just like you, I'm a student. I enjoy diving into new subjects and gaining knowledge. It's great to meet another curious mind. What kind of topics are you interested in?
  3. Charlie: Hi Bob, it's great to meet you! I'm really into science and technology. I find the advancements in AI and robotics fascinating. What about you, what are your interests?

Now we print the memory of Alice to check if her memory is updated correctly.

  1. async def example_memory() -> None:
  2. """Print the memory of Alice."""
  3. print("Memory of Alice:")
  4. for msg in await alice.memory.get_memory():
  5. print(f"{msg.name}: {msg.get_text_content()}")
  6. asyncio.run(example_memory())
  1. Memory of Alice:
  2. system: Now you meet each other with a brief self-introduction.
  3. Alice: None
  4. system: None
  5. Alice: Hello! I'm Alice, a student with a passion for learning and exploring new ideas. It's nice to meet you. Could you tell me a bit about yourself?
  6. Bob: Hello Alice! I'm Bob, and just like you, I'm a student. I enjoy diving into new subjects and gaining knowledge. It's great to meet another curious mind. What kind of topics are you interested in?
  7. Charlie: Hi Bob, it's great to meet you! I'm really into science and technology. I find the advancements in AI and robotics fascinating. What about you, what are your interests?

Further Reading

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

Download Jupyter notebook: workflow_conversation.ipynb

Download Python source code: workflow_conversation.py

Download zipped: workflow_conversation.zip

Gallery generated by Sphinx-Gallery