autogen 自定义agent (2)

ArithmeticAgent

1. ArithmeticAgent 类
class ArithmeticAgent(BaseChatAgent):
    def __init__(self, name: str, description: str, operator_func: Callable[[int], int]) -> None:
        super().__init__(name, description=description)
        self._operator_func = operator_func
        self._message_history: List[ChatMessage] = []

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

    async def on_messages(self, messages: Sequence[ChatMessage], cancellation_token: CancellationToken) -> Response:
        self._message_history.extend(messages)
        assert isinstance(self._message_history[-1], TextMessage)
        number = int(self._message_history[-1].content)
        result = self._operator_func(number)
        response_message = TextMessage(content=str(result), source=self.name)
        self._message_history.append(response_message)
        return Response(chat_message=response_message)

    async def on_reset(self, cancellation_token: CancellationToken) -> None:
        pass
  • ArithmeticAgent 是一个继承自 BaseChatAgent 的类,用于执行特定的算术操作。
  • __init__ 方法:初始化代理,接收代理名称、描述和一个操作函数 operator_func,该函数用于对输入的数字进行特定的算术操作。
  • produced_message_types 属性:指定该代理产生的消息类型为 TextMessage
  • on_messages 方法:当代理接收到消息时,会调用此方法。它会将接收到的消息添加到消息历史中,解析最后一个消息中的数字,应用操作函数,生成新的消息并返回。
  • on_reset 方法:用于重置代理状态,当前为空实现。
2. run_number_agents 函数
async def run_number_agents() -> None:
    add_agent = ArithmeticAgent("add_agent", "Adds 1 to the number.", lambda x: x + 1)
    multiply_agent = ArithmeticAgent("multiply_agent", "Multiplies the number by 2.", lambda x: x * 2)
    subtract_agent = ArithmeticAgent("subtract_agent", "Subtracts 1 from the number.", lambda x: x - 1)
    divide_agent = ArithmeticAgent("divide_agent", "Divides the number by 2 and rounds down.", lambda x: x // 2)
    identity_agent = ArithmeticAgent("identity_agent", "Returns the number as is.", lambda x: x)

    termination_condition = MaxMessageTermination(10)

    model_client = OpenAIChatCompletionClient(
                    model="GLM-4-plus",
                    api_key = "your api key",
                    base_url="https://open.bigmodel.cn/api/paas/v4/",
                    model_capabilities={
                "vision": False,
                "function_calling": True,
                "json_output": True,
            },
                )
    
    selector_group_chat = SelectorGroupChat(
        [add_agent, multiply_agent, subtract_agent, divide_agent, identity_agent],
        model_client=model_client,
        termination_condition=termination_condition,
        allow_repeated_speaker=True,
        selector_prompt=(
            "Available roles:\n{roles}\nTheir job descriptions:\n{participants}\n"
            "Current conversation history:\n{history}\n"
            "Please select the most appropriate role for the next message, and only return the role name."
        ),
    )

    task: List[ChatMessage] = [
        TextMessage(content="Apply the operations to turn the given number into 25.", source="user"),
        TextMessage(content="10", source="user"),
    ]
    stream = selector_group_chat.run_stream(task=task)
    await Console(stream)
  • run_number_agents 函数:这是一个异步函数,用于创建多个 ArithmeticAgent 实例,并通过 SelectorGroupChat 进行协作。
  • 创建代理:创建了五个不同的 ArithmeticAgent 实例,分别执行加1、乘2、减1、除2和保持原数的操作。
  • 终止条件:设置了 MaxMessageTermination(10),表示在发送10条消息后终止对话。
  • 模型客户端:创建了一个 OpenAIChatCompletionClient 实例,用于与指定的模型进行交互。
  • SelectorGroupChat:创建了一个 SelectorGroupChat 实例,将上述代理添加到群聊中,并设置了允许重复发言和选择器提示。
  • 任务:定义了初始任务,要求将数字10通过一系列操作转换为25。
  • 运行群聊:调用 run_stream 方法启动群聊,并通过 Console 输出结果。
3. 运行结果
---------- user ----------
Apply the operations to turn the given number into 25.
---------- user ----------
10
---------- multiply_agent ----------
20
---------- add_agent ----------
21
---------- subtract_agent ----------
20
---------- add_agent ----------
21
---------- add_agent ----------
22
---------- add_agent ----------
23
---------- add_agent ----------
24
---------- add_agent ----------
25
  • 运行结果:展示了群聊的运行过程。初始数字为10,经过一系列操作后最终达到了目标数字25。
  • 操作顺序:首先 multiply_agent 将10乘以2得到20,然后 add_agent 将20加1得到21,接着 subtract_agent 将21减1得到20,最后 add_agent 连续加1直到达到25。
4.总结

这段代码展示了如何使用多个代理协作完成一个简单的算术任务。每个代理负责执行特定的算术操作,并通过 SelectorGroupChat 进行协调,最终达到目标数字。

注意事项

chatglm模型调用时遵循 system, user 的消息方式, 如果只是system传过去,会报错:
BadRequestError: Error code: 400 - {'error': {'code': '1214', 'message': 'messages 参数非法。请检查文档。'}}
可以在SelectorGroupChatManager类中添加usermessage,具体为:
autogen 自定义agent (2)_第1张图片
修改后测试:

import asyncio
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import SelectorGroupChat
from autogen_agentchat.conditions import TextMentionTermination
from autogen_agentchat.ui import Console

model_client = OpenAIChatCompletionClient(
                    model="GLM-4-plus",
                    api_key = "your api key",
                    base_url="https://open.bigmodel.cn/api/paas/v4/",
                    model_capabilities={
                "vision": False,
                "function_calling": True,
                "json_output": True,
            },
                )


async def main() -> None:
    

    async def lookup_hotel(location: str) -> str:
        return f"Here are some hotels in {location}: hotel1, hotel2, hotel3."

    async def lookup_flight(origin: str, destination: str) -> str:
        return f"Here are some flights from {origin} to {destination}: flight1, flight2, flight3."

    async def book_trip() -> str:
        return "Your trip is booked!"

    travel_advisor = AssistantAgent(
        "Travel_Advisor",
        model_client,
        tools=[book_trip],
        description="Helps with travel planning.",
    )
    hotel_agent = AssistantAgent(
        "Hotel_Agent",
        model_client,
        tools=[lookup_hotel],
        description="Helps with hotel booking.",
    )
    flight_agent = AssistantAgent(
        "Flight_Agent",
        model_client,
        tools=[lookup_flight],
        description="Helps with flight booking.",
    )
    termination = TextMentionTermination("TERMINATE")
    team = SelectorGroupChat(
        [travel_advisor, hotel_agent, flight_agent],
        model_client=model_client,
        termination_condition=termination,
    )
    await Console(team.run_stream(task="Book a 3-day trip to new york."))


await main()

---------- user ----------
Book a 3-day trip to new york.
---------- Travel_Advisor ----------
[FunctionCall(id='call_-9030674033155240617', arguments='{}', name='book_trip')]
---------- Travel_Advisor ----------
[FunctionExecutionResult(content='Your trip is booked!', call_id='call_-9030674033155240617')]
---------- Travel_Advisor ----------
Your trip is booked!
---------- Flight_Agent ----------
TERMINATE

另一个例子: LogicalAgent

from typing import Callable, Sequence, List

from autogen_agentchat.agents import BaseChatAgent
from autogen_agentchat.base import Response
from autogen_agentchat.conditions import MaxMessageTermination
from autogen_agentchat.messages import ChatMessage, TextMessage
from autogen_agentchat.teams import SelectorGroupChat
from autogen_agentchat.ui import Console
from autogen_core import CancellationToken
from autogen_ext.models.openai import OpenAIChatCompletionClient


class LogicalAgent(BaseChatAgent):
    def __init__(self, name: str, description: str, operator_func: Callable[[int], int]) -> None:
        super().__init__(name, description=description)
        self._operator_func = operator_func
        self._message_history: List[ChatMessage] = []

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

    async def on_messages(self, messages: Sequence[ChatMessage], cancellation_token: CancellationToken) -> Response:
        self._message_history.extend(messages)
        assert isinstance(self._message_history[-1], TextMessage)
        
        number = int(self._message_history[-1].content)
        result = self._operator_func(number)

        response_message = TextMessage(content=str(result), source=self.name)
        self._message_history.append(response_message)
        return Response(chat_message=response_message)

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


async def run_logical_agents() -> None:
    # 创建逻辑运算代理
    and_agent = LogicalAgent("and_agent", "Performs a bitwise AND operation between the input value and 1, effectively determining whether the input is odd or even. Returns 1 if the input is odd, otherwise returns 0.", lambda x: x & 1)
    or_agent = LogicalAgent("or_agent", "Performs a bitwise OR operation between the input value and 1, ensuring the result is always an odd number. If the input is even, it increments by 1; if already odd, it remains unchanged.", lambda x: x | 1)
    xor_agent = LogicalAgent("xor_agent", "Performs a bitwise XOR operation between the input value and 1, flipping the least significant bit. This effectively toggles the input between odd and even.", lambda x: x ^ 1)
    not_agent = LogicalAgent("not_agent", "Performs a bitwise NOT operation, inverting all bits of the input. This is equivalent to computing -(x + 1) due to two's complement representation.", lambda x: ~x)
    lshift_agent = LogicalAgent("lshift_agent", "Performs a left shift operation (x << 1), shifting all bits one position to the left. This effectively multiplies the input by 2.", lambda x: x << 1)
    rshift_agent = LogicalAgent("rshift_agent", "Performs a right shift operation (x >> 1), shifting all bits one position to the right. This effectively performs integer division by 2, discarding the remainder.", lambda x: x >> 1)

    termination_condition = MaxMessageTermination(10)

    model_client = OpenAIChatCompletionClient(
        model="GLM-4-plus",
        api_key="your api key",
        base_url="https://open.bigmodel.cn/api/paas/v4/",
        model_capabilities={"vision": False, "function_calling": True, "json_output": True},
    )

    # 选择组对话
    selector_group_chat = SelectorGroupChat(
        [and_agent, or_agent, xor_agent, not_agent, lshift_agent, rshift_agent],
        model_client=model_client,
        termination_condition=termination_condition,
        allow_repeated_speaker=True,
        selector_prompt=(
            "Available roles:\n{roles}\nTheir job descriptions:\n{participants}\n"
            "Current conversation history:\n{history}\n"
            "Please select the most appropriate role for the next message, and only return the role name."
        ),
    )

    task: List[ChatMessage] = [
        TextMessage(content="Apply logical operations to transform the number into 5.", source="user"),
        TextMessage(content="10", source="user"),
    ]
    
    stream = selector_group_chat.run_stream(task=task)
    await Console(stream)


# 在脚本中使用 asyncio.run(run_logical_agents()) 运行
await run_logical_agents()

---------- user ----------
Apply logical operations to transform the number into 5.
---------- user ----------
10
---------- xor_agent ----------
11
---------- rshift_agent ----------
5
---------- rshift_agent ----------
2
---------- xor_agent ----------
3
---------- xor_agent ----------
2
---------- xor_agent ----------
3
---------- xor_agent ----------
2
---------- rshift_agent ----------
1

参考链接:https://microsoft.github.io/autogen/stable/user-guide/agentchat-user-guide/tutorial/custom-agents.html

你可能感兴趣的:(autogen,人工智能,agent)