AutoGen系列六: SelectorGroupChat 的原理与实践
AutoGen 技术博客系列 (七):状态管理与组件序列化解析
AutoGen 技术博客系列 (八):# 深入剖析 Swarm—— 智能体协作的新范式
AutoGen 技术博客系列 (九):从 v0.2 到 v0.4 的迁移指南
在上一篇博客中,我们对 AutoGen 框架进行了基础介绍,并演示了如何创建和使用预设的智能体以及简单的智能体团队。本篇博客将深入探讨 AutoGen 的一个核心特性:如何创建和使用自定义智能体。自定义智能体允许我们根据特定需求扩展 AutoGen 的功能,从而构建更加灵活和强大的智能体应用。
为什么需要自定义智能体?
虽然 AutoGen 提供了如 AssistantAgent 和 UserProxyAgent 等多种预设智能体,但这些预设智能体可能无法完全满足所有应用场景的需求。在以下情况下,可能需要创建自定义智能体:
•特定的行为模式: 当你需要智能体具有特定的交互逻辑、决策流程或行为模式时。
•特殊的工具集成: 当你需要智能体使用特定的工具或服务时,这些工具在预设智能体中没有提供。
•独特的系统消息: 当你需要智能体具有独特的个性和角色,需要通过自定义系统消息来控制其行为时。
•复杂的交互逻辑: 当智能体需要执行复杂的任务或与其他智能体进行复杂的交互时。
自定义智能体的核心概念
在 AutoGen 中,自定义智能体通常通过继承 BaseChatAgent 类来实现。BaseChatAgent 类提供了创建智能体的基本框架,我们可以在其基础上进行扩展,以满足特定的需求。以下是创建自定义智能体的关键概念:
•继承 BaseChatAgent: 自定义智能体必须继承 BaseChatAgent 类,从而获得 AutoGen 框架的基本功能。
•init 方法: 在 init 方法中,可以初始化智能体的各种属性,如名称、描述、系统消息等。
•receive 方法: receive 方法是智能体接收消息的入口点。可以重写此方法以实现自定义的消息处理逻辑。
•send 方法: send 方法用于向其他智能体发送消息。可以重写此方法以实现自定义的消息发送逻辑。
•工具集成: 自定义智能体可以集成各种外部工具,从而扩展自身的能力。
•系统消息: 系统消息用于指导智能体的行为。可以为自定义智能体设计独特的系统消息。
创建自定义智能体的步骤
1.定义新的智能体类: 首先,创建一个继承自 BaseChatAgent 的新类。 例如,我们创建一个名为 CustomAssistant 的智能体,该智能体具有自定义的系统消息和消息处理逻辑。
2.初始化智能体属性: 在 init 方法中,初始化智能体的名称,模型客户端 (model_client) 以及系统消息 (system_message)。系统消息用于控制智能体的行为和性格。
3.实现消息处理逻辑 重写 receive 方法以实现自定义的消息处理逻辑。 在这个示例中,当接收到 TextMessage 时,智能体会将其内容发送到模型客户端并返回模型输出。
4.集成工具 (可选): 如果自定义智能体需要使用特定的工具,你可以在 receive 方法中调用这些工具。例如,你可以在智能体中集成网络搜索工具或代码执行工具。这个部分将在后续的博客中详细介绍,这里只简单展示如何加入一个工具:
### 使用自定义智能体
创建自定义智能体后,可以像使用其他智能体一样,将其添加到智能体团队中进行协作。下面是一个简单的例子:
```python
import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.conditions import TextMentionTermination
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_core import CancellationToken
class CustomAssistant(BaseChatAgent):
def __init__(self, name, model_client, system_message):
super().__init__(name=name)
self.model_client = model_client
self.system_message = system_message
async def receive(self, message, sender):
if isinstance(message, TextMessage):
response = await self.model_client.get_chat_completion(
messages=[
{"role": "system", "content": self.system_message},
{"role": "user", "content": message.content}
],
)
return TextMessage(content=response.content, source=self.name)
else:
return None
async def main():
model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")
custom_writer = CustomAssistant(
name="custom_writer",
model_client=model_client,
system_message="You are a creative writer. Respond with a short poem.",
)
critic = AssistantAgent(
name="critic",
model_client=model_client,
system_message="You are a helpful critic. Respond with 'APPROVE' when you are satisfied.",
)
termination = TextMentionTermination("APPROVE")
team = RoundRobinGroupChat([custom_writer, critic], termination_condition=termination)
await Console(team.run_stream(task="写一个关于春天的三行诗"))
asyncio.run(main())
在这个例子中,我们创建了一个 CustomAssistant 智能体作为 writer,并与一个 AssistantAgent 作为 critic 组成一个 RoundRobinGroupChat 团队。
自定义智能体实战案例
为了更好地理解自定义智能体的实际应用,我们来构建一个简单的实战案例。假设我们需要一个智能体团队,其中一个智能体负责生成文章的初稿,另一个智能体负责对文章进行润色和校对。我们可以使用自定义智能体来实现此功能:
1.创建自定义的 BlogWriter 智能体
2.这个 BlogWriter 智能体具有一个特定的系统消息,它会根据用户提供的提示生成技术博客文章的初稿。
3.创建 BlogEditor 智能体 (使用预设的 AssistantAgent):
from autogen_agentchat.agents import AssistantAgent
editor = AssistantAgent(
name="editor",
model_client=OpenAIChatCompletionClient(model="gpt-4o-mini"),
system_message="You are a helpful blog editor. Provide feedback on the content and grammar, and respond with 'APPROVE' when you are satisfied.",
)
3.组合智能体并运行
import asyncio
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.conditions import TextMentionTermination
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_core import CancellationToken
class BlogWriter(BaseChatAgent):
def __init__(self, name, model_client):
super().__init__(name=name)
self.model_client = model_client
self.system_message = "You are an expert technical blogger. Write a draft of a technical blog post based on the user's prompt."
async def receive(self, message, sender):
if isinstance(message, TextMessage):
response = await self.model_client.get_chat_completion(
messages=[
{"role": "system", "content": self.system_message},
{"role": "user", "content": message.content}
],
)
return TextMessage(content=response.content, source=self.name)
else:
return None
async def main():
model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")
writer = BlogWriter(
name="writer",
model_client=model_client,
)
editor = AssistantAgent(
name="editor",
model_client=model_client,
system_message="You are a helpful blog editor. Provide feedback on the content and grammar, and respond with 'APPROVE' when you are satisfied.",
)
termination = TextMentionTermination("APPROVE")
team = RoundRobinGroupChat([writer, editor], termination_condition=termination)
await Console(team.run_stream(task="请写一篇关于 AutoGen 的入门博客"))
asyncio.run(main())
总结
本文介绍了 AutoGen 中自定义智能体的创建和使用方法。通过继承 BaseChatAgent 类,我们可以根据实际需求创建各种类型的自定义智能体,并通过自定义消息处理逻辑、集成外部工具和设计独特的系统消息来扩展 AutoGen 的功能。自定义智能体是 AutoGen 框架的重要组成部分,也是构建复杂智能体应用的关键。