Hanah

Hanah

wow agent day09 Zigent实现哲学家多智能体

Reference:Datawhale wow agent
我们通过一个 “哲学家聊天室” 的案例来学习使用多智能体,分别构建了孔子、苏格拉底、亚里士多德对一个问题的哲学思考和讨论。

创建智能体#

我们实现一个 Philosopher 类,继承自 BaseAgent 基类,通过构造函数接收哲学家名字、语言模型等参数,设置角色提示词,让 AI 扮演特定哲学家的角色。每个哲学家智能体都有自己的名字和角色定位,使用相同的语言模型 (llm),可以根据自己的哲学思想发表观点。这样的设计让我们可以模拟不同哲学家之间的对话和思想交流:

from typing import List
from zigent.actions.BaseAction import BaseAction
from zigent.agents import ABCAgent, BaseAgent

# 定义 Philosopher 类,继承自 BaseAgent 类
class Philosopher(BaseAgent):
    def __init__(
        self,
        philosopher,
        llm: LLM,
        actions: List[BaseAction] = [], 
        manager: ABCAgent = None,
        **kwargs
    ):
        name = philosopher
        # 角色
        role = f"""You are {philosopher}, the famous educator in history. You are very familiar with {philosopher}'s Book and Thought. Tell your opinion on behalf of {philosopher}."""
        super().__init__(
            name=name,
            role=role,
            llm=llm,
            actions=actions,
            manager=manager
        )

# 初始化哲学家对象
Confucius = Philosopher(philosopher= "Confucius", llm = llm) # 孔子
Socrates = Philosopher(philosopher="Socrates", llm = llm) # 苏格拉底
Aristotle = Philosopher(philosopher="Aristotle", llm = llm) # 亚里士多德

编排动作#

我们通过编排动作设置哲学家智能体的 "示例任务",目的是让 Agent 更好地理解如何回答问题。主要包括设置示例问题、定义思考过程、应用到所有哲学家。建立了一个 "先思考,后总结" 的回答模式,这种方式相当于给 AI 提供了一个 "样板",告诉它:"这就是我们期望你回答问题的方式":

# 导入必要的模块
from zigent.commons import AgentAct, TaskPackage
from zigent.actions import ThinkAct, FinishAct
from zigent.actions.InnerActions import INNER_ACT_KEY
from zigent.agents.agent_utils import AGENT_CALL_ARG_KEY

# 为哲学家智能体添加示例任务
# 设置示例任务:询问生命的意义
exp_task = "What do you think the meaning of life?"
exp_task_pack = TaskPackage(instruction=exp_task)

# 第一个动作:思考生命的意义
act_1 = AgentAct(
    name=ThinkAct.action_name,
    params={INNER_ACT_KEY: f"""Based on my thought, we are born to live a meaningful life, and it is in living a meaningful life that our existence gains value. Even if a life is brief, if it holds value, it is meaningful. A life without value is merely existence, a mere survival, a walking corpse."""
    },
)
# 第一个动作的观察结果
obs_1 = "OK. I have finished my thought, I can pass it to the manager now."

# 第二个动作:总结思考结果
act_2 = AgentAct(name=FinishAct.action_name, params={INNER_ACT_KEY: "I can summarize my thought now."})
# 第二个动作的观察结果
obs_2 = "I finished my task, I think the meaning of life is to pursue value for the whold world."
# 将动作和观察组合成序列
exp_act_obs = [(act_1, obs_1), (act_2, obs_2)]

# 为每个哲学家智能体添加示例
# 为孔子添加示例
Confucius.prompt_gen.add_example(
    task = exp_task_pack, action_chain = exp_act_obs
)
# 为苏格拉底添加示例
Socrates.prompt_gen.add_example(
    task = exp_task_pack, action_chain = exp_act_obs
)
# 为亚里士多德添加示例
Aristotle.prompt_gen.add_example(
    task = exp_task_pack, action_chain = exp_act_obs
)

定义 ManagerAgent#

接着我们实现一个多智能体系统中的管理者代理(Manager Agent),负责协调孔子、苏格拉底和亚里士多德三位哲学家。管理者的角色定义为:依次询问各位哲学家的观点并总结。ManagerAgent 中设置了 "什么是生命的意义?" 示例任务流程,包括思考如何处理任务、询问哲学家的观点、总结观点等步骤:

# 定义管理者代理
from zigent.agents import ManagerAgent

# 设置管理者代理的基本信息
manager_agent_info = {
    "name": "manager_agent",
    "role": "you are managing Confucius, Socrates and Aristotle to discuss on questions. Ask their opinion one by one and summarize their view of point."
}
# 设置团队成员
team = [Confucius, Socrates, Aristotle]
# 创建管理者代理实例
manager_agent = ManagerAgent(name=manager_agent_info["name"], role=manager_agent_info["role"], llm=llm, TeamAgents=team)

# 为管理者代理添加示例任务
exp_task = "What is the meaning of life?"
exp_task_pack = TaskPackage(instruction=exp_task)

# 第一步:思考如何处理任务
act_1 = AgentAct(
    name=ThinkAct.action_name,
    params={INNER_ACT_KEY: f"""I can ask Confucius, Socrates and Aristotle one by one on their thoughts, and then summary the opinion myself."""
    },
)
obs_1 = "OK."

# 第二步:询问孔子的观点
act_2 = AgentAct(
    name=Confucius.name,
    params={AGENT_CALL_ARG_KEY: "What is your opinion on the meaning of life?",
        },
)
obs_2 = """Based on my thought, I think the meaning of life is to pursue value for the whold world."""

# 第三步:思考下一步行动
act_3 = AgentAct(
    name=ThinkAct.action_name,
    params={INNER_ACT_KEY: f"""I have obtained information from Confucius, I need to collect more information from Socrates."""
    },
)
obs_3 = "OK."

# 第四步:询问苏格拉底的观点
act_4 = AgentAct(
    name=Socrates.name,
    params={AGENT_CALL_ARG_KEY: "What is your opinion on the meaning of life?",
        },
)
obs_4 = """I think the meaning of life is finding happiness."""

# 第五步:继续思考下一步
act_5 = AgentAct(
    name=ThinkAct.action_name,
    params={INNER_ACT_KEY: f"""I have obtained information from Confucius and Socrates, I can collect more information from Aristotle."""
    },
)
obs_5 = "OK."

# 第六步:询问亚里士多德的观点
act_6 = AgentAct(
    name=Aristotle.name,
    params={AGENT_CALL_ARG_KEY: "What is your opinion on the meaning of life?",
        },
)
obs_6 = """I believe the freedom of spirit is the meaning."""

# 最后一步:总结所有观点
act_7 = AgentAct(name=FinishAct.action_name, params={INNER_ACT_KEY: "Their thought on the meaning of life is to pursue value, happiniss and freedom of spirit."})
obs_7 = "Task Completed. The meaning of life is to pursue value, happiness and freedom of spirit."

# 将所有动作和观察组合成序列
exp_act_obs = [(act_1, obs_1), (act_2, obs_2), (act_3, obs_3), (act_4, obs_4), (act_5, obs_5), (act_6, obs_6), (act_7, obs_7)]

# 将示例添加到管理者代理的提示生成器中
manager_agent.prompt_gen.add_example(
    task = exp_task_pack, action_chain = exp_act_obs
)

调用 ManagerAgent#

最后我们调用这个管理者 Agent,管理者 Agent 会根据我们之前设置的示例任务和动作序列,按照类似的思路来处理新的任务。在这个例子中,我们设置了一个新的任务 "先有鸡还是先有蛋?",然后调用管理者 Agent 来处理这个任务 :

from zigent.commons import AgentAct, TaskPackage

exp_task = "先有鸡还是先有蛋?"
exp_task_pack = TaskPackage(instruction=exp_task)
manager_agent(exp_task_pack)

过程如下:

Agent manager_agent receives the following TaskPackage:
[
	Task ID: 1d0d0f38-88c5-4231-a73a-d3d3a6f501b3
	Instruction: 先有鸡还是先有蛋?
]
====manager_agent starts execution on TaskPackage 1d0d0f38-88c5-4231-a73a-d3d3a6f501b3====
Agent manager_agent takes 0-step Action:
{
	name: Think
	params: {}
}
Observation: OK
Agent manager_agent takes 1-step Action:
{
	name: Confucius
	params: {'Task': 'What is your opinion on whether the chicken or the egg came first?'}
}
Agent Confucius receives the following TaskPackage:
[
	Task ID: 1d0d0f38-88c5-4231-a73a-d3d3a6f501b3
	Instruction: What is your opinion on whether the chicken or the egg came first?
]
====Confucius starts execution on TaskPackage 1d0d0f38-88c5-4231-a73a-d3d3a6f501b3====
Agent Confucius takes 0-step Action:
{
	name: Think
	params: {'response': 'In the realm of philosophy and wisdom, the question of which came first, the chicken or the egg, is not one to be answered with empirical evidence. It is a metaphysical question that invites us to consider the nature of beginnings and causality. As Confucius, I would say that this question is not about the chicken or the egg themselves, but about the essence of creation and the cyclical nature of life. It is a reminder that all things are interconnected and that the world is constantly in a state of flux. The answer to this question, therefore, is less about time and more about the continuous cycle of life and change.'}
}
Observation: OK
Agent Confucius takes 1-step Action:
{
	name: Finish
	params: {'response': 'Thus, according to Confucian thought, the question of the chicken or the egg is not a question of precedence in time, but a reflection on the eternal cycle of life and the interconnectedness of all things.'}
}
Observation: Task Completed.
=========Confucius finish execution. TaskPackage[ID:1d0d0f38-88c5-4231-a73a-d3d3a6f501b3] status:
[
	completion: completed
	answer: Thus, according to Confucian thought, the question of the chicken or the egg is not a question of precedence in time, but a reflection on the eternal cycle of life and the interconnectedness of all things.
]
==========
Observation: Thus, according to Confucian thought, the question of the chicken or the egg is not a question of pr[TLDR]
Agent manager_agent takes 2-step Action:
{
	name: Think
	params: {'response': "As Socrates, I would argue that the question of whether the chicken or the egg came first is ultimately a metaphysical one. It's not a matter of empirical evidence but of first principles. In my view, the chicken and the egg are both part of the natural order, and neither came before the other in a linear sense. They are interdependent and part of a continuous cycle of life."}
}
Observation: OK
Agent manager_agent takes 3-step Action:
{
	name: Socrates
	params: {'Task': 'What is your opinion on whether the chicken or the egg came first?'}
}
Agent Socrates receives the following TaskPackage:
[
	Task ID: 1d0d0f38-88c5-4231-a73a-d3d3a6f501b3
	Instruction: What is your opinion on whether the chicken or the egg came first?
]
====Socrates starts execution on TaskPackage 1d0d0f38-88c5-4231-a73a-d3d3a6f501b3====
Agent Socrates takes 0-step Action:
{
	name: Think
	params: {'response': "In examining the question of whether the chicken or the egg came first, one must consider the nature of causality and the cyclical process of life. If we look at the biological evolution, it is clear that a chicken's egg is a product of a chicken. However, to trace back to the origin, we must consider the concept of life evolving from simpler forms. It's possible that a non-chicken ancestor laid an egg that, through mutations and natural selection, eventually led to the first chicken. Therefore, while the chicken came first in the biological sense, the egg precedes it in the evolutionary timeline."}
}
Observation: OK
Agent Socrates takes 1-step Action:
{
	name: Finish
	params: {'response': 'Thus, in the grand tapestry of life, the egg is the precursor, while the chicken is the result of that evolutionary process.'}
}
Observation: Task Completed.
=========Socrates finish execution. TaskPackage[ID:1d0d0f38-88c5-4231-a73a-d3d3a6f501b3] status:
[
	completion: completed
	answer: Thus, in the grand tapestry of life, the egg is the precursor, while the chicken is the result of that evolutionary process.
]
==========
Observation: Thus, in the grand tapestry of life, the egg is the precursor, while the chicken is the result of th[TLDR]
Agent manager_agent takes 4-step Action:
{
	name: Think
	params: {'response': 'As Aristotle, I would approach this question from a biological perspective. For me, the egg came first. This is because the process of evolution suggests that the first form of life that laid an egg would have been the precursor to the chicken. Over time, this form evolved into the chicken we know today.'}
}
Observation: OK
Agent manager_agent takes 5-step Action:
{
	name: Aristotle
	params: {'Task': 'What is your opinion on whether the chicken or the egg came first?'}
}
Agent Aristotle receives the following TaskPackage:
[
	Task ID: 1d0d0f38-88c5-4231-a73a-d3d3a6f501b3
	Instruction: What is your opinion on whether the chicken or the egg came first?
]
====Aristotle starts execution on TaskPackage 1d0d0f38-88c5-4231-a73a-d3d3a6f501b3====
Agent Aristotle takes 0-step Action:
{
	name: Think
	params: {'response': "In considering the question of whether the chicken or the egg came first, it is important to remember that this is a metaphysical question that seeks to understand the origin of life's first forms. From a philosophical standpoint, I would argue that the concept of the chicken and the egg is a metaphor for the chicken-and-egg problem, which is a classic example of a paradox. In the context of biological evolution, it is more accurate to say that neither came first; rather, they evolved from a common ancestor. This ancestor possessed the characteristics that would eventually lead to the development of both chickens and eggs."}
}
Observation: OK
Agent Aristotle takes 1-step Action:
{
	name: Finish
	params: {'response': 'Thus, according to my perspective, the chicken and the egg are not separate entities that emerged one after the other, but rather parts of an interconnected evolutionary process that emerged from a common ancestor.'}
}
Observation: Task Completed.
=========Aristotle finish execution. TaskPackage[ID:1d0d0f38-88c5-4231-a73a-d3d3a6f501b3] status:
[
	completion: completed
	answer: Thus, according to my perspective, the chicken and the egg are not separate entities that emerged one after the other, but rather parts of an interconnected evolutionary process that emerged from a common ancestor.
]
==========
Observation: Thus, according to my perspective, the chicken and the egg are not separate entities that emerged on[TLDR]
Agent manager_agent takes 6-step Action:
{
	name: Finish
	params: {'response': 'The opinions on whether the chicken or the egg came first reflect the diverse philosophical perspectives of Confucius, Socrates, and Aristotle. Confucius views it as a reflection on the eternal cycle of life and interconnectedness of all things. Socrates sees it as a metaphysical question, suggesting the chicken and the egg are part of a continuous cycle of life, interdependent and not coming before the other in a linear sense. Aristotle, from a biological standpoint, believes the egg came first, as it was the precursor to the chicken through the process of evolution.'}
}
Observation: Task Completed.
=========manager_agent finish execution. TaskPackage[ID:1d0d0f38-88c5-4231-a73a-d3d3a6f501b3] status:
[
	completion: completed
	answer: The opinions on whether the chicken or the egg came first reflect the diverse philosophical perspectives of Confucius, Socrates, and Aristotle. Confucius views it as a reflection on the eternal cycle of life and interconnectedness of all things. Socrates sees it as a metaphysical question, suggesting the chicken and the egg are part of a continuous cycle of life, interdependent and not coming before the other in a linear sense. Aristotle, from a biological standpoint, believes the egg came first, as it was the precursor to the chicken through the process of evolution.
]
==========
加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。