微软AutoGen介绍:Custom Agents创建自己的Agents

介绍

大家好,这次给大家分享的内容是微软AutoGen框架一个重要的功能模块Custom Agents(自定义智能体)。本次分享的内容需要大家具备一定的面向对象编程经验。那么本次分享的Custom Agents又是什么呢,我们直接进入正题。

Custom Agents

我们可能会遇到行为不符合预设的智能体。在这种情况下,我们可以构建自定义智能体。

AgentChat中的所有智能体都继承自BaseChatAgent类,并实现以下抽象方法和属性:

  • on_messages():这是一个抽象方法,用于定义智能体在收到消息时的响应行为。当在run()中要求智能体提供响应时,会调用此方法。它返回一个Response对象。
  • on_reset():此抽象方法用于将智能体重置为初始状态。当要求智能体自行重置时,会调用此方法。
  • produced_message_types:智能体在其响应中可能生成的ChatMessage消息类型列表。

我们也可以选择实现on_messages_stream()方法,以便在智能体生成消息时将其流式输出。如果未实现此方法,智能体将使用on_messages_stream()的默认实现,该默认实现会调用on_messages()方法,并逐一生成响应中的所有消息。

CountDownAgent

我们写个示例来演示。我们创建一个简单的智能体,它从给定数字倒数到零,并生成一系列包含当前计数的消息流。

完整代码

import asyncio
from typing import AsyncGenerator, List, Sequence, Tuple
from autogen_agentchat.agents import BaseChatAgent
from autogen_agentchat.base import Response
from autogen_agentchat.messages import AgentEvent, ChatMessage, TextMessage
from autogen_core import CancellationToken


class CountDownAgent(BaseChatAgent):
    def __init__(self, name: str, count: int = 3):
        super().__init__(name, "A simple agent that counts down.")
        self._count = count

    @property
    def produced_message_types(self) -> Sequence[type[ChatMessage]]:
        return (TextMessage,)

    async def on_messages(self, messages: Sequence[ChatMessage], cancellation_token: CancellationToken) -> Response:
        # 调用on_messages_stream方法。
        response: Response | None = None
        async for message in self.on_messages_stream(messages, cancellation_token):
            if isinstance(message, Response):
                response = message
        assert response is not None
        return response

    async def on_messages_stream(
            self, messages: Sequence[ChatMessage], cancellation_token: CancellationToken
    ) -> AsyncGenerator[AgentEvent | ChatMessage | Response, None]:
        inner_messages: List[AgentEvent | ChatMessage] = []
        for i in range(self._count, 0, -1):
            msg = TextMessage(content=f"{i}...", source=self.name)
            inner_messages.append(msg)
            yield msg
        # 响应会在流结束时返回。
        # 它包含最终消息以及所有内部消息。
        yield Response(chat_message=TextMessage(content="Done!", source=self.name), inner_messages=inner_messages)

    async def on_reset(self, cancellation_token: CancellationToken) -> None:
        pass


async def run_countdown_agent() -> None:
    # 创建一个倒计时智能体。
    countdown_agent = CountDownAgent("cou
### 如何在 AutoGen 中集成和调用其他 AI 模型 AutoGen 提供了一个灵活的框架来实现不同类型的代理,这些代理可以通过配置相互协作完成复杂任务。对于希望在 AutoGen 中集成第三方模型的需求来说,主要通过创建特定功能的代理对象并与现有体系结构无缝对接。 #### 创建自定义代理类 为了使外部模型能够被纳入到对话流程当中,首先需要设计一个新的代理子类继承自 `AssistantAgent` 或者 `UserProxyAgent` ,这取决于所引入的服务性质以及其预期角色定位[^2]。 ```python from autogen import AssistantAgent, UserProxyAgent class CustomModelAgent(AssistantAgent): """A custom agent that integrates an external model.""" def __init__(self, name, llm_config=None, **kwargs): super().__init__(name=name, is_termination_msg=None, human_input_mode="NEVER", max_consecutive_auto_reply=5, default_auto_reply="I am a custom model.", llm_config=llm_config, system_message="Custom Model Agent", **kwargs) def generate_response(self, message_history, config_list=None, temperature=0, request_timeout=180): # Here you would implement the logic to call your external model. pass ``` 在这个基础上,开发者可以根据实际需求重写 `generate_response()` 方法,在其中加入针对目标平台 API 请求的具体处理逻辑;比如发送 HTTP POST 请求给远程服务器获取预测结果,并将其解析返回作为下一步操作依据。 #### 配置多模态交互环境 当多个异构组件共同参与会话过程时,则需考虑如何合理安排它们之间的工作流顺序及数据传递机制。借助于 AutoGen 所提供的工具集,可以方便地设置一组由不同类型实例组成的群体来进行协同工作: ```python config_list = [ { "model": "custom_model", "api_base": "<your_custom_api_endpoint>", "api_key": "<your_api_key>" }, ] # Initialize agents with configurations assistant_agent = CustomModelAgent(name="assistant", llm_config=config_list[0]) user_proxy_agent = UserProxyAgent( name="proxy_user", code_execution_config={"work_dir": "coding"}, human_input_mode="TERMINATE" ) # Start conversation loop between user and assistant conversation = Conversation(agents=[assistant_agent, user_proxy_agent], chatbot_name="<chatbot_name>") conversation.initiate_chat() ``` 上述代码片段展示了怎样初始化包含自定义模型在内的两个参与者,并启动一轮完整的交流周期。值得注意的是,这里假设已经实现了适配器模式下的接口函数用于桥接内部消息格式同外界服务协议间的差异转换。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老赵爱学习

您的鼓励是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值