注意
Go to the end 下载完整示例代码。
对话¶
对话是一种设计模式,智能体们通过它互相交换和分享信息, 常见于游戏博弈、聊天机器人和多智能体讨论场景中。
在AgentScope中,对话建立在显式消息交换的基础上。本教程将展示如何构建对话
在用户和智能体 (聊天机器人) 之间
在多个智能体之间(游戏对弈、讨论等)
它们的主要区别在于
提示是如何构建的,以及
信息如何在智能体之间传播/共享。
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
用户-智能体对话¶
用户-智能体对话,也被称为聊天机器人,是LLM赋能的智能体最常见的应用场景,也是多数LLM API的设计目标。此类对话仅包含两个参与者:用户和智能体。
在AgentScope中,带有“Chat”的格式化器设计用于用户-智能体对话,例如DashScopeChatFormatter,
AnthropicChatFormatter等。
它们使用消息中的role字段来区分用户和智能体,并相应地格式化消息。
在这里我们构建一个智能体 Friday 和用户之间的简单对话。
提示
AgentScope提供了一个内置的UserAgent类用于人在回路(HITL)交互。更多详情请参阅user-agent。
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")
现在,我们可以通过在这两个智能体之间交换消息来编写对话程序,直到用户输入“exit”来结束对话。
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())
超出两个智能体¶
如开头所述,我们展示了如何在提示构建和信息共享方面构建多智能体对话。
Welcome to AgentScope's documentation!¶
Prompt Construction¶
在AgentScope中,我们为多智能体对话提供内置格式化器,其名称中包含“MultiAgent”,例如DashScopeMultiAgentFormatter, AnthropicMultiAgentFormatter等。
name字段来区分不同的智能体,并将对话历史格式化为单一用户消息。
以DashScopeMultiAgentFormatter为例:
提示
更多关于格式化器的详细信息可以在Prompt Formatter中找到.
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())
Formatted prompt:
[
{
"role": "system",
"content": "You're a helpful assistant named Bob."
},
{
"role": "user",
"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>"
}
]
-------------
Combined message
# Conversation History
The content between <history></history> tags contains your conversation history
<history>
Alice: Hi!
Bob: Hi! Nice to meet you guys.
Charlie: Me too! I'm Charlie, by the way.
</history>
消息共享¶
在多智能体对话中,显式交换消息可能不够高效和便捷,特别是在多个智能体之间广播消息时。
因此,AgentScope提供了一个名为MsgHub的异步上下文管理器来简化广播消息的操作。
具体来说,位于同一个MsgHub中的智能体将自动接收来自同一MsgHub中其他参与者的消息。
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())
Alice: Hello! I'm Alice, a student who's always eager to learn and explore new things. Nice to meet you! Could you tell me a bit about yourself?
Bob: Hello Alice! I'm Bob, and like you, I'm also a student. I have a curious mind and enjoy delving into all sorts of subjects, from science to literature. It's great to meet another enthusiastic learner like myself. What kind of things are you interested in?
Charlie: Alice: It's wonderful to meet you, Bob! I'm really into science and technology, especially artificial intelligence and robotics. I also love reading, particularly fantasy and science fiction. What about you, what are your main interests?
Charlie: That sounds fascinating, Alice! I share a similar interest in science and tech, but I lean more towards the natural sciences like biology and ecology. For literature, I enjoy both classic and contemporary works. It seems we have quite a bit in common, as well as some diverse interests to learn from each other.
现在我们来打印Alice的记忆,以检查她的记忆是否正确更新。
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())
Memory of Alice:
system: Now you meet each other with a brief self-introduction.
Alice: None
system: None
Alice: Hello! I'm Alice, a student who's always eager to learn and explore new things. Nice to meet you! Could you tell me a bit about yourself?
Bob: Hello Alice! I'm Bob, and like you, I'm also a student. I have a curious mind and enjoy delving into all sorts of subjects, from science to literature. It's great to meet another enthusiastic learner like myself. What kind of things are you interested in?
Charlie: That sounds fascinating, Alice! I share a similar interest in science and tech, but I lean more towards the natural sciences like biology and ecology. For literature, I enjoy both classic and contemporary works. It seems we have quite a bit in common, as well as some diverse interests to learn from each other.
扩展阅读¶
脚本总运行时间: (0 分钟 22.344 秒)