多智能体辩论#
多智能体辩论是一种多智能体设计模式,它模拟了多轮交互,在每一轮中,智能体之间交换响应,并根据其他智能体的响应改进其响应。
此示例展示了多智能体辩论模式的一种实现,用于解决来自 GSM8K 基准的数学问题。
此模式中有两种类型的智能体:求解器智能体和聚合器智能体。 求解器智能体以稀疏的方式连接,遵循 使用稀疏通信拓扑改进多智能体辩论 中描述的技术。 求解器智能体负责解决数学问题并相互交换响应。 聚合器智能体负责将数学问题分发给求解器智能体,等待他们的最终响应,并聚合这些响应以获得最终答案。
该模式的工作方式如下
用户向聚合器智能体发送一个数学问题。
聚合器智能体将问题分发给求解器智能体。
每个求解器智能体处理该问题,并向其邻居发布响应。
每个求解器智能体使用来自其邻居的响应来改进其响应,并发布新的响应。
重复步骤 4 固定轮数。 在最后一轮中,每个求解器智能体发布最终响应。
聚合器智能体使用多数投票来聚合来自所有求解器智能体的最终响应以获得最终答案,并发布该答案。
我们将使用广播 API,即 publish_message()
,并且我们将使用主题和订阅来实现通信拓扑。 阅读 主题和订阅 以了解它们的工作原理。
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
消息协议#
首先,我们定义智能体使用的消息。 IntermediateSolverResponse
是求解器智能体在每一轮中交换的消息,FinalSolverResponse
是求解器智能体在最后一轮中发布的消息。
@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 生成答案。 然后,它根据轮数发布 IntermediateSolverResponse
或 FinalSolverResponse
。
求解器智能体被赋予一个主题类型,用于指示智能体应发布中间响应的主题。 它的邻居订阅此主题以接收来自该智能体的响应 - 我们稍后将展示如何完成此操作。
我们使用 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
| |
| |
D --- C
每个求解器智能体都连接到其他两个求解器智能体。 例如,智能体 A 连接到智能体 B 和 C。
让我们首先创建一个运行时并注册智能体类型。
runtime = SingleThreadedAgentRuntime()
model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")
await MathSolver.register(
runtime,
"MathSolverA",
lambda: MathSolver(
model_client=model_client,
topic_type="MathSolverA",
num_neighbors=2,
max_round=3,
),
)
await MathSolver.register(
runtime,
"MathSolverB",
lambda: MathSolver(
model_client=model_client,
topic_type="MathSolverB",
num_neighbors=2,
max_round=3,
),
)
await MathSolver.register(
runtime,
"MathSolverC",
lambda: MathSolver(
model_client=model_client,
topic_type="MathSolverC",
num_neighbors=2,
max_round=3,
),
)
await MathSolver.register(
runtime,
"MathSolverD",
lambda: MathSolver(
model_client=model_client,
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())
# Wait for the runtime to stop when idle.
await runtime.stop_when_idle()
# Close the connection to the model client.
await model_client.close()
--------------------------------------------------------------------------------
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