多代理辩论#

多代理辩论是一种多代理设计模式,模拟了多轮交互,其中在每一轮中,代理们相互交换他们的回应,并根据其他代理的回应来精炼自己的回应。

此示例展示了用于解决从GSM8K基准而来的数学问题的多代理辩论模式的实现。

在这种模式中有两种类型的代理:求解代理和聚合代理。 求解代理按照通过稀疏通信拓扑改进多代理辩论中描述的技术以稀疏的方式连接。 求解代理负责解决数学问题并相互交换响应。 聚合代理负责将数学问题分配给求解代理,等待它们的最终响应,并将这些响应聚合以得到最终答案。

该模式的运作方式如下:

  1. 用户将数学问题发送给聚合代理。

  2. 聚合代理将问题分配给求解器代理。

  3. 每个求解器代理处理问题,并向其邻居发布响应。

  4. 每个求解器代理利用其邻居的响应来优化其响应,并发布一个新的响应。

  5. 重复步骤4进行固定轮数。在最后一轮,每个求解器代理发布最终响应。

  6. 聚合代理使用多数投票来汇总来自所有求解代理的最终响应,以得到最终答案,并发布该答案。

我们将使用广播API,即publish_message(), 并通过topic和subscription来实现通信拓扑。 阅读Topics and Subscriptions以了解它们的工作原理。

import re
from dataclasses import dataclass
from typing import Dict, List

from autogen_core import (
    DefaultTopicId,
    MessageContext,
    RoutedAgent,
    SingleThreadedAgentRuntime,
    TypeSubscription,
    default_subscription,
    message_handler,
)
from autogen_core.models import (
    AssistantMessage,
    ChatCompletionClient,
    LLMMessage,
    SystemMessage,
    UserMessage,
)
from autogen_ext.models.openai import OpenAIChatCompletionClient

消息协议#

首先,我们定义了由agents使用的消息。 IntermediateSolverResponse 是在每一轮中由solver agents之间交换的消息, 而 FinalSolverResponse 是由solver agents在最后一轮发布的消息。

@dataclass
class Question:
    content: str


@dataclass
class Answer:
    content: str


@dataclass
class SolverRequest:
    content: str
    question: str


@dataclass
class IntermediateSolverResponse:
    content: str
    question: str
    answer: str
    round: int


@dataclass
class FinalSolverResponse:
    answer: str

求解器代理#

求解器代理负责解决数学问题并与其他求解器代理交换响应。 在收到一个SolverRequest后,求解器代理使用LLM生成答案。 然后,根据轮次发布IntermediateSolverResponseFinalSolverResponse

求解器代理被赋予一个主题类型,用于指示代理应发布中间响应的主题。这个主题由它的邻居订阅,以接收来自该代理的响应——我们稍后将展示这是如何完成的。

我们使用default_subscription()来让 解题代理订阅默认主题,聚合代理使用该主题从解题代理收集最终响应。

@default_subscription
class MathSolver(RoutedAgent):
    def __init__(self, model_client: ChatCompletionClient, topic_type: str, num_neighbors: int, max_round: int) -> None:
        super().__init__("A debator.")
        self._topic_type = topic_type
        self._model_client = model_client
        self._num_neighbors = num_neighbors
        self._history: List[LLMMessage] = []
        self._buffer: Dict[int, List[IntermediateSolverResponse]] = {}
        self._system_messages = [
            SystemMessage(
                content=(
                    "You are a helpful assistant with expertise in mathematics and reasoning. "
                    "Your task is to assist in solving a math reasoning problem by providing "
                    "a clear and detailed solution. Limit your output within 100 words, "
                    "and your final answer should be a single numerical number, "
                    "in the form of {{answer}}, at the end of your response. "
                    "For example, 'The answer is {{42}}.'"
                )
            )
        ]
        self._round = 0
        self._max_round = max_round

    @message_handler
    async def handle_request(self, message: SolverRequest, ctx: MessageContext) -> None:
        # Add the question to the memory.
        self._history.append(UserMessage(content=message.content, source="user"))
        # Make an inference using the model.
        model_result = await self._model_client.create(self._system_messages + self._history)
        assert isinstance(model_result.content, str)
        # Add the response to the memory.
        self._history.append(AssistantMessage(content=model_result.content, source=self.metadata["type"]))
        print(f"{'-'*80}\nSolver {self.id} round {self._round}:\n{model_result.content}")
        # Extract the answer from the response.
        match = re.search(r"\{\{(\-?\d+(\.\d+)?)\}\}", model_result.content)
        if match is None:
            raise ValueError("The model response does not contain the answer.")
        answer = match.group(1)
        # Increment the counter.
        self._round += 1
        if self._round == self._max_round:
            # If the counter reaches the maximum round, publishes a final response.
            await self.publish_message(FinalSolverResponse(answer=answer), topic_id=DefaultTopicId())
        else:
            # Publish intermediate response to the topic associated with this solver.
            await self.publish_message(
                IntermediateSolverResponse(
                    content=model_result.content,
                    question=message.question,
                    answer=answer,
                    round=self._round,
                ),
                topic_id=DefaultTopicId(type=self._topic_type),
            )

    @message_handler
    async def handle_response(self, message: IntermediateSolverResponse, ctx: MessageContext) -> None:
        # Add neighbor's response to the buffer.
        self._buffer.setdefault(message.round, []).append(message)
        # Check if all neighbors have responded.
        if len(self._buffer[message.round]) == self._num_neighbors:
            print(
                f"{'-'*80}\nSolver {self.id} round {message.round}:\nReceived all responses from {self._num_neighbors} neighbors."
            )
            # Prepare the prompt for the next question.
            prompt = "These are the solutions to the problem from other agents:\n"
            for resp in self._buffer[message.round]:
                prompt += f"One agent solution: {resp.content}\n"
            prompt += (
                "Using the solutions from other agents as additional information, "
                "can you provide your answer to the math problem? "
                f"The original math problem is {message.question}. "
                "Your final answer should be a single numerical number, "
                "in the form of {{answer}}, at the end of your response."
            )
            # Send the question to the agent itself to solve.
            await self.send_message(SolverRequest(content=prompt, question=message.question), self.id)
            # Clear the buffer.
            self._buffer.pop(message.round)

聚合器代理#

聚合器代理负责处理用户问题并将数学问题分发给求解器代理。

聚合器使用default_subscription()订阅默认主题。默认主题用于接收用户问题,接收求解器代理的最终响应,并将最终答案发布回用户。

在一个更复杂的应用中,当你想要将多代理辩论隔离到一个子组件时,你应该使用 type_subscription()来为聚合器-求解器通信设置一个特定的主题类型, 并让求解器和聚合器都发布和订阅该主题类型。

@default_subscription
class MathAggregator(RoutedAgent):
    def __init__(self, num_solvers: int) -> None:
        super().__init__("Math Aggregator")
        self._num_solvers = num_solvers
        self._buffer: List[FinalSolverResponse] = []

    @message_handler
    async def handle_question(self, message: Question, ctx: MessageContext) -> None:
        print(f"{'-'*80}\nAggregator {self.id} received question:\n{message.content}")
        prompt = (
            f"Can you solve the following math problem?\n{message.content}\n"
            "Explain your reasoning. Your final answer should be a single numerical number, "
            "in the form of {{answer}}, at the end of your response."
        )
        print(f"{'-'*80}\nAggregator {self.id} publishes initial solver request.")
        await self.publish_message(SolverRequest(content=prompt, question=message.content), topic_id=DefaultTopicId())

    @message_handler
    async def handle_final_solver_response(self, message: FinalSolverResponse, ctx: MessageContext) -> None:
        self._buffer.append(message)
        if len(self._buffer) == self._num_solvers:
            print(f"{'-'*80}\nAggregator {self.id} received all final answers from {self._num_solvers} solvers.")
            # Find the majority answer.
            answers = [resp.answer for resp in self._buffer]
            majority_answer = max(set(answers), key=answers.count)
            # Publish the aggregated response.
            await self.publish_message(Answer(content=majority_answer), topic_id=DefaultTopicId())
            # Clear the responses.
            self._buffer.clear()
            print(f"{'-'*80}\nAggregator {self.id} publishes final answer:\n{majority_answer}")

设置辩论#

我们现在将设置一个有4个求解器代理和1个聚合器代理的多代理辩论。 求解器代理将以稀疏的方式连接,如下图所示:

A --- B
|     |
|     |
C --- D

每个求解器代理都连接到其他两个求解器代理。 例如,代理A连接到代理B和C。

首先创建一个运行时并注册代理类型。

runtime = SingleThreadedAgentRuntime()
await MathSolver.register(
    runtime,
    "MathSolverA",
    lambda: MathSolver(
        model_client=OpenAIChatCompletionClient(model="gpt-4o-mini"),
        topic_type="MathSolverA",
        num_neighbors=2,
        max_round=3,
    ),
)
await MathSolver.register(
    runtime,
    "MathSolverB",
    lambda: MathSolver(
        model_client=OpenAIChatCompletionClient(model="gpt-4o-mini"),
        topic_type="MathSolverB",
        num_neighbors=2,
        max_round=3,
    ),
)
await MathSolver.register(
    runtime,
    "MathSolverC",
    lambda: MathSolver(
        model_client=OpenAIChatCompletionClient(model="gpt-4o-mini"),
        topic_type="MathSolverC",
        num_neighbors=2,
        max_round=3,
    ),
)
await MathSolver.register(
    runtime,
    "MathSolverD",
    lambda: MathSolver(
        model_client=OpenAIChatCompletionClient(model="gpt-4o-mini"),
        topic_type="MathSolverD",
        num_neighbors=2,
        max_round=3,
    ),
)
await MathAggregator.register(runtime, "MathAggregator", lambda: MathAggregator(num_solvers=4))
AgentType(type='MathAggregator')

现在我们将使用TypeSubscription来创建求解器代理的拓扑结构, 它将每个求解器代理的发布主题类型映射到其邻居代理的类型。

# Subscriptions for topic published to by MathSolverA.
await runtime.add_subscription(TypeSubscription("MathSolverA", "MathSolverD"))
await runtime.add_subscription(TypeSubscription("MathSolverA", "MathSolverB"))

# Subscriptions for topic published to by MathSolverB.
await runtime.add_subscription(TypeSubscription("MathSolverB", "MathSolverA"))
await runtime.add_subscription(TypeSubscription("MathSolverB", "MathSolverC"))

# Subscriptions for topic published to by MathSolverC.
await runtime.add_subscription(TypeSubscription("MathSolverC", "MathSolverB"))
await runtime.add_subscription(TypeSubscription("MathSolverC", "MathSolverD"))

# Subscriptions for topic published to by MathSolverD.
await runtime.add_subscription(TypeSubscription("MathSolverD", "MathSolverC"))
await runtime.add_subscription(TypeSubscription("MathSolverD", "MathSolverA"))

# All solvers and the aggregator subscribe to the default topic.

解决数学问题#

现在让我们运行辩论来解决一个数学问题。 我们发布一个SolverRequest到默认主题, 聚合器代理将开始辩论。

question = "Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did Natalia sell altogether in April and May?"
runtime.start()
await runtime.publish_message(Question(content=question), DefaultTopicId())
await runtime.stop_when_idle()
--------------------------------------------------------------------------------
Aggregator MathAggregator:default received question:
Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. How many clips did Natalia sell altogether in April and May?
--------------------------------------------------------------------------------
Aggregator MathAggregator:default publishes initial solver request.
--------------------------------------------------------------------------------
Solver MathSolverC:default round 0:
In April, Natalia sold 48 clips. In May, she sold half as many, which is 48 / 2 = 24 clips. To find the total number of clips sold in April and May, we add the amounts: 48 (April) + 24 (May) = 72 clips. 

Thus, the total number of clips sold by Natalia is {{72}}.
--------------------------------------------------------------------------------
Solver MathSolverB:default round 0:
In April, Natalia sold 48 clips. In May, she sold half as many clips, which is 48 / 2 = 24 clips. To find the total clips sold in April and May, we add both amounts: 

48 (April) + 24 (May) = 72.

Thus, the total number of clips sold altogether is {{72}}.
--------------------------------------------------------------------------------
Solver MathSolverD:default round 0:
Natalia sold 48 clips in April. In May, she sold half as many, which is \( \frac{48}{2} = 24 \) clips. To find the total clips sold in both months, we add the clips sold in April and May together:

\[ 48 + 24 = 72 \]

Thus, Natalia sold a total of 72 clips.

The answer is {{72}}.
--------------------------------------------------------------------------------
Solver MathSolverC:default round 1:
Received all responses from 2 neighbors.
--------------------------------------------------------------------------------
Solver MathSolverA:default round 1:
Received all responses from 2 neighbors.
--------------------------------------------------------------------------------
Solver MathSolverA:default round 0:
In April, Natalia sold clips to 48 friends. In May, she sold half as many, which is calculated as follows:

Half of 48 is \( 48 \div 2 = 24 \).

Now, to find the total clips sold in April and May, we add the totals from both months:

\( 48 + 24 = 72 \).

Thus, the total number of clips Natalia sold altogether in April and May is {{72}}.
--------------------------------------------------------------------------------
Solver MathSolverD:default round 1:
Received all responses from 2 neighbors.
--------------------------------------------------------------------------------
Solver MathSolverB:default round 1:
Received all responses from 2 neighbors.
--------------------------------------------------------------------------------
Solver MathSolverC:default round 1:
In April, Natalia sold 48 clips. In May, she sold half as many, which is 48 / 2 = 24 clips. The total number of clips sold in April and May is calculated by adding the two amounts: 48 (April) + 24 (May) = 72 clips. 

Therefore, the answer is {{72}}.
--------------------------------------------------------------------------------
Solver MathSolverA:default round 1:
In April, Natalia sold 48 clips. In May, she sold half of that amount, which is 48 / 2 = 24 clips. To find the total clips sold in both months, we sum the clips from April and May: 

48 (April) + 24 (May) = 72.

Thus, Natalia sold a total of {{72}} clips. 

The answer is {{72}}.
--------------------------------------------------------------------------------
Solver MathSolverD:default round 2:
Received all responses from 2 neighbors.
--------------------------------------------------------------------------------
Solver MathSolverB:default round 2:
Received all responses from 2 neighbors.
--------------------------------------------------------------------------------
Solver MathSolverD:default round 1:
Natalia sold 48 clips in April. In May, she sold half of that, which is \( 48 \div 2 = 24 \) clips. To find the total clips sold, we add the clips sold in both months:

\[ 48 + 24 = 72 \]

Therefore, the total number of clips sold by Natalia is {{72}}.
--------------------------------------------------------------------------------
Solver MathSolverB:default round 1:
In April, Natalia sold 48 clips. In May, she sold half that amount, which is 48 / 2 = 24 clips. To find the total clips sold in both months, we add the amounts: 

48 (April) + 24 (May) = 72.

Therefore, the total number of clips sold altogether by Natalia is {{72}}.
--------------------------------------------------------------------------------
Solver MathSolverA:default round 2:
Received all responses from 2 neighbors.
--------------------------------------------------------------------------------
Solver MathSolverC:default round 2:
Received all responses from 2 neighbors.
--------------------------------------------------------------------------------
Solver MathSolverA:default round 2:
In April, Natalia sold 48 clips. In May, she sold half of that amount, which is \( 48 \div 2 = 24 \) clips. To find the total clips sold in both months, we add the amounts from April and May:

\( 48 + 24 = 72 \).

Thus, the total number of clips sold by Natalia is {{72}}.
--------------------------------------------------------------------------------
Solver MathSolverC:default round 2:
In April, Natalia sold 48 clips. In May, she sold half of that amount, which is \( 48 \div 2 = 24 \) clips. To find the total number of clips sold in both months, we add the clips sold in April and May: 

48 (April) + 24 (May) = 72. 

Thus, the total number of clips sold altogether by Natalia is {{72}}.
--------------------------------------------------------------------------------
Solver MathSolverB:default round 2:
In April, Natalia sold 48 clips. In May, she sold half as many, calculated as \( 48 \div 2 = 24 \) clips. To find the total clips sold over both months, we sum the totals: 

\( 48 (April) + 24 (May) = 72 \).

Therefore, the total number of clips Natalia sold is {{72}}.
--------------------------------------------------------------------------------
Solver MathSolverD:default round 2:
To solve the problem, we know that Natalia sold 48 clips in April. In May, she sold half that amount, which is calculated as \( 48 \div 2 = 24 \) clips. To find the total number of clips sold over both months, we add the two amounts together:

\[ 48 + 24 = 72 \]

Thus, the total number of clips sold by Natalia is {{72}}.
--------------------------------------------------------------------------------
Aggregator MathAggregator:default received all final answers from 4 solvers.
--------------------------------------------------------------------------------
Aggregator MathAggregator:default publishes final answer:
72