參考: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 [94mmanager_agent[0m receives the following [4mTaskPackage[0m:
[96m[
Task ID: 1d0d0f38-88c5-4231-a73a-d3d3a6f501b3
Instruction: 先有雞還是先有蛋?
][0m
====[94mmanager_agent[0m starts execution on TaskPackage 1d0d0f38-88c5-4231-a73a-d3d3a6f501b3====
Agent [94mmanager_agent[0m takes 0-step [4mAction[0m:
[94m{
name: Think
params: {}
}[0m
Observation: [92mOK[0m
Agent [94mmanager_agent[0m takes 1-step [4mAction[0m:
[94m{
name: Confucius
params: {'Task': 'What is your opinion on whether the chicken or the egg came first?'}
}[0m
Agent [94mConfucius[0m receives the following [4mTaskPackage[0m:
[96m[
Task ID: 1d0d0f38-88c5-4231-a73a-d3d3a6f501b3
Instruction: What is your opinion on whether the chicken or the egg came first?
][0m
====[94mConfucius[0m starts execution on TaskPackage 1d0d0f38-88c5-4231-a73a-d3d3a6f501b3====
Agent [94mConfucius[0m takes 0-step [4mAction[0m:
[94m{
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.'}
}[0m
Observation: [92mOK[0m
Agent [94mConfucius[0m takes 1-step [4mAction[0m:
[94m{
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.'}
}[0m
Observation: [92mTask Completed.[0m
=========[94mConfucius[0m finish execution. TaskPackage[ID:1d0d0f38-88c5-4231-a73a-d3d3a6f501b3] status:
[96m[
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.
][0m
==========
Observation: [92mThus, according to Confucian thought, the question of the chicken or the egg is not a question of pr[TLDR][0m
Agent [94mmanager_agent[0m takes 2-step [4mAction[0m:
[94m{
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."}
}[0m
Observation: [92mOK[0m
Agent [94mmanager_agent[0m takes 3-step [4mAction[0m:
[94m{
name: Socrates
params: {'Task': 'What is your opinion on whether the chicken or the egg came first?'}
}[0m
Agent [94mSocrates[0m receives the following [4mTaskPackage[0m:
[96m[
Task ID: 1d0d0f38-88c5-4231-a73a-d3d3a6f501b3
Instruction: What is your opinion on whether the chicken or the egg came first?
][0m
====[94mSocrates[0m starts execution on TaskPackage 1d0d0f38-88c5-4231-a73a-d3d3a6f501b3====
Agent [94mSocrates[0m takes 0-step [4mAction[0m:
[94m{
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."}
}[0m
Observation: [92mOK[0m
Agent [94mSocrates[0m takes 1-step [4mAction[0m:
[94m{
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.'}
}[0m
Observation: [92mTask Completed.[0m
=========[94mSocrates[0m finish execution. TaskPackage[ID:1d0d0f38-88c5-4231-a73a-d3d3a6f501b3] status:
[96m[
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.
][0m
==========
Observation: [92mThus, in the grand tapestry of life, the egg is the precursor, while the chicken is the result of th[TLDR][0m
Agent [94mmanager_agent[0m takes 4-step [4mAction[0m:
[94m{
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.'}
}[0m
Observation: [92mOK[0m
Agent [94mmanager_agent[0m takes 5-step [4mAction[0m:
[94m{
name: Aristotle
params: {'Task': 'What is your opinion on whether the chicken or the egg came first?'}
}[0m
Agent [94mAristotle[0m receives the following [4mTaskPackage[0m:
[96m[
Task ID: 1d0d0f38-88c5-4231-a73a-d3d3a6f501b3
Instruction: What is your opinion on whether the chicken or the egg came first?
][0m
====[94mAristotle[0m starts execution on TaskPackage 1d0d0f38-88c5-4231-a73a-d3d3a6f501b3====
Agent [94mAristotle[0m takes 0-step [4mAction[0m:
[94m{
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."}
}[0m
Observation: [92mOK[0m
Agent [94mAristotle[0m takes 1-step [4mAction[0m:
[94m{
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.'}
}[0m
Observation: [92mTask Completed.[0m
=========[94mAristotle[0m finish execution. TaskPackage[ID:1d0d0f38-88c5-4231-a73a-d3d3a6f501b3] status:
[96m[
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.
][0m
==========
Observation: [92mThus, according to my perspective, the chicken and the egg are not separate entities that emerged on[TLDR][0m
Agent [94mmanager_agent[0m takes 6-step [4mAction[0m:
[94m{
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.'}
}[0m
Observation: [92mTask Completed.[0m
=========[94mmanager_agent[0m finish execution. TaskPackage[ID:1d0d0f38-88c5-4231-a73a-d3d3a6f501b3] status:
[96m[
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.
][0m
==========