返回顶部
热门问答 更多热门问答
技术文章 更多技术文章

让智能体自己开个会 - 用AgentScope实现Agent动态创建,轻松组织讨论

[复制链接]
链载Ai 显示全部楼层 发表于 昨天 09:54 |阅读模式 打印 上一主题 下一主题
ingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;border-left: none;padding: 1em;border-radius: 8px;color: rgba(0, 0, 0, 0.5);background: rgb(247, 247, 247);margin: 0px 8px 2em;">从实战中学习和拆解AgentScope框架的使用和知识。本文利用AgentScope框架实现的是 多智能体的自由讨论 。

ingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;border-left: none;padding: 1em;border-radius: 8px;color: rgba(0, 0, 0, 0.5);background: rgb(247, 247, 247);margin: 2em 8px;">

代码参考:https://github.com/modelscope/agentscope/tree/main/examples/conversation_self_organizing

ingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;font-size: 1.2em;font-weight: bold;display: table;margin: 2em auto 1em;padding-right: 1em;padding-left: 1em;border-bottom: 2px solid rgb(15, 76, 129);color: rgb(63, 63, 63);">0. 实现效果

ingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;margin: 1.5em 8px;letter-spacing: 0.1em;color: rgb(63, 63, 63);">先上最终的实现效果,给大家一个直观的感受。本文实现的效果如下:

有多个Agent(例如案例中的 PhysicsTeacher物理老师、curious student好奇的学生、analytical student分析型学生),针对一个话题展开讨论,每个Agent轮流发言。

ingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;font-size: 1.2em;font-weight: bold;display: table;margin: 2em auto 1em;padding-right: 1em;padding-left: 1em;border-bottom: 2px solid rgb(15, 76, 129);color: rgb(63, 63, 63);">1. 需求拆解

ingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;margin: 1.5em 8px;letter-spacing: 0.1em;color: rgb(63, 63, 63);">要实现多智能体之间的自由讨论,需要实现以下内容:

ingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;margin: 1.5em 8px;letter-spacing: 0.1em;color: rgb(63, 63, 63);">(1)有多个对话智能体

ingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;margin: 1.5em 8px;letter-spacing: 0.1em;color: rgb(63, 63, 63);">(2)多个对话智能体之间的通信(数据流控制)

ingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;margin: 1.5em 8px;letter-spacing: 0.1em;color: rgb(63, 63, 63);">(3)本文要实现的是不固定的多智能体对话,也就是说,多智能体是动态创建的,因此有个Agent来组织讨论,例如本例中讨论的物理问题,该Agent需要根据这个物理问题创建相应的智能体(物理老师和各种学生等)

ingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;margin: 1.5em 8px;letter-spacing: 0.1em;color: rgb(63, 63, 63);">这么一看,是不是就觉得非常简单了?对话智能体(DialogAgent)和数据流控制(Pipeline)我们前面都已经深入学习过了,还不了解的可以去看我前面的AgentScope相关文章。

2. 代码实现

2.1 初始化AgentScope

AgentScope在使用前,需要先初始化配置,主要是将要使用的大模型和相关的API Key 设置一下:

importagentscope
model_configs=[
{
"model_type":"openai",
"config_name":"gpt-3.5-turbo",
"model_name":"gpt-3.5-turbo",
#"api_key":"xxx",#Loadfromenvifnotprovided
#"organization":"xxx",#Loadfromenvifnotprovided
"generate_args":{
"temperature":0.5,
},
},
]
agentscope.init(model_configs=model_configs)

2.2 创建讨论的组织者

根据前面的需求分析,我们首先需要有一个Agent来根据问题动态生成讨论问题的Agent们。

这里使用一个对话智能体DialogAgent即可:

#inittheself-organizingconversation
agent_builder=DialogAgent(
name="agent_builder",
sys_prompt="You'reahelpfulassistant.",
model_config_name="gpt-3.5-turbo",
)

有了这个agent实例,可以通过传入Prompt和问题来获取参与讨论的Agents以及各Agents的设定。这里的Prompt是比较重要的,看下示例中的Prompt:

Actasagroupdiscussionorganizer.Pleaseprovidethesuitablescenariofordiscussingthisquestion,andlisttherolesofthepeoplewhoneedtoparticipateinthediscussioninordertoanswerthisquestion,alongwiththeirsystemprompttodescribetheircharacteristics.
Theresponsemustintheformatof:
#scenario#:<discussionscenario>
#participants#:
*<participant1type>:<characteristicdescription>
*<participant2type>:<characteristicdescription>

Herearesomeexamples.
Question:Joycanread8pagesofabookin20minutes.Howmanyhourswillittakehertoread120pages?
Answer:
#scenario#:gradeschoolclassdiscussion
#participants#:
*Instructor:Actasaninstructorwhoisinaclassgroupdiscussiontoguidethestudentgroupdiscussion.Pleaseencouragecriticalthinking.Encourageparticipantstothinkcriticallyandchallengeassumptionsbyaskingthought-provokingquestionsorpresentingdifferentperspectives.
*broad-minded-student:Actasastudentwhoisbroad-mindedandisopentotryingnewordifferentwaystosolveproblems.Youareinagroupdiscussionwithotherstudentundertheguidanceoftheinstructor.
*knowledgeable-student:Actasaknowledgeablestudentanddiscusswithotherstoretrievemoreinformationaboutthetopic.Ifyoudonotknowtheanswertoaquestion,pleasedonotsharefalseinformation

Pleasegivethediscussionscenarioandthecorrespondingparticipantsforthefollowingquestion:
Question:{question}
Answer:

Prompt里,要求要给出讨论的流程、讨论的参与者与讨论参与者各自的“system prompt”。

运行时,将Prompt与问题组合传给Agent:

query="假设你眼睛的瞳孔直径为5毫米,你有一台孔径为50厘米的望远镜。望远镜能比你的眼睛多收集多少光?"

x=load_txt(
"D:\\GitHub\\LEARN_LLM\\agentscope\\start_0\\conversation_self_organizing\\agent_builder_instruct.txt",
).format(
question=query,
)

x=Msg("user",x,role="user")
settings=agent_builder(x)

看下这个Agent的运行结果:

文字版运行结果:

tools:extract_scenario_and_participants:82-{'Scenario':'Physicsclassdiscussiononoptics','Participants':{'PhysicsTeacher':'Actasaphysicsteacherwhoisleadingthediscussiononoptics.Yourroleistofacilitatetheconversation,provideexplanations,andensurethatthediscussionstaysfocusedonthetopicoflightcollectionandoptics.','curious-student':'Actasastudentwhoiscuriousandeagertolearnmoreaboutopticsandlightcollection.Youaskinsightfulquestionsandactivelyparticipateinthediscussiontodeepenyourunderstanding.','analytical-student':'Actasastudentwhoisanalyticalandenjoyssolvingproblemsrelatedtooptics.Youapproachthequestionmethodicallyanduselogicalreasoningtoarriveatsolutions.'}}

输出结果给出了 Scenario 以及该问题的 Participants参与者,参与者有 PhysicsTeacher、curious-student 和 analytical-student。并给出了这几个参与者的角色设定。

之后通过一个解析函数,将里面的角色和设定解析出来就可以用来动态创建这些Agent了。

defextract_scenario_and_participants(content:str)->dict:
result={}
#defineregularexpression
scenario_pattern=r"#scenario#:\s*(.*)"
participants_pattern=r"\*\s*([^:\n]+):\s*([^\n]+)"

#searchandextractscenario
scenario_match=re.search(scenario_pattern,content)
ifscenario_match:
result["Scenario"]=scenario_match.group(1).strip()

#searchandextractparticipants
participants_matches=re.finditer(participants_pattern,content)
participants_dict={}
formatchinparticipants_matches:
participant_type,characteristic=match.groups()
participants_dict[
participant_type.strip().replace("","_")
]=characteristic.strip()
result["Participants"]=participants_dict

logger.info(result)

returnresult

scenario_participants=extract_scenario_and_participants(settings["content"])

2.3 动态创建讨论者

有了参与者及其描述,直接用循环语句创建这些Agent:

#settheagentsthatparticipantthediscussion
agents=[
DialogAgent(
name=key,
sys_prompt=val,
model_config_name="gpt-3.5-turbo",
)
forkey,valinscenario_participants["Participants"].items()
]

2.4 开始讨论

这里用了 sequentialpipeline 顺序发言:

max_round=2
msg=Msg("user",f"let'sdiscusstosolvethequestionwithchinese:{query}",role="user")
foriinrange(max_round):
msg=sequentialpipeline(agents,msg)

运行结果见文章刚开始的实现效果,实现讨论。

3. 总结

本文主要拆解了一个利用AgentScope框架实现的多智能体自由讨论案例,先由一个Agent根据问题生成讨论流程和讨论者,然后根据讨论者动态创建Agent。

主要的亮点在于:

(1)有一个Agent把控全局,生成流程和各参与者的描述

(2)动态创建讨论者Agent,这让这个系统有了更好的通用性,根据不同的问题有不同类型和不同数量的Agent会被创建。

值得借鉴。

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

链载AI是专业的生成式人工智能教程平台。提供Stable Diffusion、Midjourney AI绘画教程,Suno AI音乐生成指南,以及Runway、Pika等AI视频制作与动画生成实战案例。从提示词编写到参数调整,手把手助您从入门到精通。
  • 官方手机版

  • 微信公众号

  • 商务合作

  • Powered by Discuz! X3.5 | Copyright © 2025-2025. | 链载Ai
  • 桂ICP备2024021734号 | 营业执照 | |广西笔趣文化传媒有限公司|| QQ