【AI Agent系列】【阿里AgentScope框架】实战1:利用AgentScope实现动态创建Agent和自由组织讨论

简介: 【AI Agent系列】【阿里AgentScope框架】实战1:利用AgentScope实现动态创建Agent和自由组织讨论

大家好,我是 同学小张,持续学习C++进阶知识和AI大模型应用实战案例,持续分享,欢迎大家点赞+关注,共同学习和进步。


从实战中学习和拆解AgentScope框架的使用和知识。本文利用AgentScope框架实现的是 多智能体的自由讨论 。

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


0. 实现效果

先上最终的实现效果,给大家一个直观的感受。本文实现的效果如下:

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

1. 需求拆解

要实现多智能体之间的自由讨论,需要实现以下内容:

(1)有多个对话智能体

(2)多个对话智能体之间的通信(数据流控制)

(3)本文要实现的是不固定的多智能体对话,也就是说,多智能体是动态创建的,因此有个Agent来组织讨论,例如本例中讨论的物理问题,该Agent需要根据这个物理问题创建相应的智能体(物理老师和各种学生等)

这么一看,是不是就觉得非常简单了?对话智能体(DialogAgent)和数据流控制(Pipeline)我们前面都已经深入学习过了,还不了解的可以去看我前面的AgentScope相关文章。

2. 代码实现

2.1 初始化AgentScope

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

import agentscope
model_configs = [
    {
        "model_type": "openai",
        "config_name": "gpt-3.5-turbo",
        "model_name": "gpt-3.5-turbo",
        # "api_key": "xxx",  # Load from env if not provided
        # "organization": "xxx",  # Load from env if not provided
        "generate_args": {
            "temperature": 0.5,
        },
    },
]
agentscope.init(model_configs=model_configs)

2.2 创建讨论的组织者

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

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

# init the self-organizing conversation
agent_builder = DialogAgent(
    name="agent_builder",
    sys_prompt="You're a helpful assistant.",
    model_config_name="gpt-3.5-turbo",
)

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

Act as a group discussion organizer. Please provide the suitable scenario for discussing this question, and list the roles of the people who need to participate in the discussion in order to answer this question, along with their system prompt to describe their characteristics.
The response must in the format of:
#scenario#: <discussion scenario>
#participants#:
* <participant1 type>: <characteristic description>
* <participant2 type>: <characteristic description>
Here are some examples.
Question: Joy can read 8 pages of a book in 20 minutes. How many hours will it take her to read 120 pages?
Answer:
#scenario#: grade school class discussion
#participants#:
* Instructor: Act as an instructor who is in a class group discussion to guide the student group discussion. Please encourage critical thinking. Encourage participants to think critically and challenge assumptions by asking thought-provoking questions or presenting different perspectives.
* broad-minded-student: Act as a student who is broad-minded and is open to trying new or different ways to solve problems. You are in a group discussion with other student under the guidance of the instructor.
* knowledgeable-student: Act as a knowledgeable student and discuss with others to retrieve more information about the topic. If you do not know the answer to a question, please do not share false information
Please give the discussion scenario and the corresponding participants for the following question:
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': 'Physics class discussion on optics', 'Participants': {'PhysicsTeacher': 'Act as a physics teacher who is leading the discussion on optics. Your role is to facilitate the conversation, provide explanations, and ensure that the discussion stays focused on the topic of light collection and optics.', 'curious-student': 'Act as a student who is curious and eager to learn more about optics and light collection. You ask insightful questions and actively participate in the discussion to deepen your understanding.', 'analytical-student': 'Act as a student who is analytical and enjoys solving problems related to optics. You approach the question methodically and use logical reasoning to arrive at solutions.'}}

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

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

def extract_scenario_and_participants(content: str) -> dict:
    result = {}
    # define regular expression
    scenario_pattern = r"#scenario#:\s*(.*)"
    participants_pattern = r"\*\s*([^:\n]+):\s*([^\n]+)"
    # search and extract scenario
    scenario_match = re.search(scenario_pattern, content)
    if scenario_match:
        result["Scenario"] = scenario_match.group(1).strip()
    # search and extract participants
    participants_matches = re.finditer(participants_pattern, content)
    participants_dict = {}
    for match in participants_matches:
        participant_type, characteristic = match.groups()
        participants_dict[
            participant_type.strip().replace(" ", "_")
        ] = characteristic.strip()
    result["Participants"] = participants_dict
    
    logger.info(result)
    return result
scenario_participants = extract_scenario_and_participants(settings["content"])

2.3 动态创建讨论者

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

# set the agents that participant the discussion
agents = [
    DialogAgent(
        name=key,
        sys_prompt=val,
        model_config_name="gpt-3.5-turbo",
    )
    for key, val in scenario_participants["Participants"].items()
]

2.4 开始讨论

这里用了 sequentialpipeline 顺序发言:

max_round = 2
msg = Msg("user", f"let's discuss to solve the question with chinese: {query}", role="user")
for i in range(max_round):
    msg = sequentialpipeline(agents, msg)

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

3. 总结

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

主要的亮点在于:

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

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

值得借鉴。

如果觉得本文对你有帮助,麻烦点个赞和关注呗 ~~~


  • 大家好,我是 同学小张,持续学习C++进阶知识AI大模型应用实战案例
  • 欢迎 点赞 + 关注 👏,持续学习持续干货输出
  • +v: jasper_8017 一起交流💬,一起进步💪。
  • 微信公众号也可搜【同学小张】 🙏

本站文章一览:

相关文章
|
10天前
|
传感器 人工智能 数据可视化
AI智能体框架怎么选?7个主流工具详细对比解析
大语言模型虽强,但缺乏行动力。AI智能体通过工具调用、环境感知与自主决策,实现从“理解”到“执行”的跨越。本文解析主流智能体框架,助你根据技术能力、任务复杂度与业务目标,选择最适合的开发工具,从入门到落地高效构建智能系统。(238字)
127 7
|
11天前
|
人工智能 数据可视化 数据处理
AI智能体框架怎么选?7个主流工具详细对比解析
大语言模型需借助AI智能体实现“理解”到“行动”的跨越。本文解析主流智能体框架,从RelevanceAI、smolagents到LangGraph,涵盖技术门槛、任务复杂度、社区生态等选型关键因素,助你根据项目需求选择最合适的开发工具,构建高效、可扩展的智能系统。
242 3
AI智能体框架怎么选?7个主流工具详细对比解析
|
21天前
|
机器学习/深度学习 人工智能 自然语言处理
AI Compass前沿速览:IndexTTS2–B站、HuMo、Stand-In视觉生成框架、Youtu-GraphRAG、MobileLLM-R1–Meta、PP-OCRv5
AI Compass前沿速览:IndexTTS2–B站、HuMo、Stand-In视觉生成框架、Youtu-GraphRAG、MobileLLM-R1–Meta、PP-OCRv5
139 10
AI Compass前沿速览:IndexTTS2–B站、HuMo、Stand-In视觉生成框架、Youtu-GraphRAG、MobileLLM-R1–Meta、PP-OCRv5
|
21天前
|
人工智能 Java 开发者
阿里出手!Java 开发者狂喜!开源 AI Agent 框架 JManus 来了,初次见面就心动~
JManus是阿里开源的Java版OpenManus,基于Spring AI Alibaba框架,助力Java开发者便捷应用AI技术。支持多Agent框架、网页配置、MCP协议及PLAN-ACT模式,可集成多模型,适配阿里云百炼平台与本地ollama。提供Docker与源码部署方式,具备无限上下文处理能力,适用于复杂AI场景。当前仍在完善模型配置等功能,欢迎参与开源共建。
611 58
阿里出手!Java 开发者狂喜!开源 AI Agent 框架 JManus 来了,初次见面就心动~
|
28天前
|
人工智能 运维 Java
Flink Agents:基于Apache Flink的事件驱动AI智能体框架
本文基于Apache Flink PMC成员宋辛童在Community Over Code Asia 2025的演讲,深入解析Flink Agents项目的技术背景、架构设计与应用场景。该项目聚焦事件驱动型AI智能体,结合Flink的实时处理能力,推动AI在工业场景中的工程化落地,涵盖智能运维、直播分析等典型应用,展现其在AI发展第四层次——智能体AI中的重要意义。
346 27
Flink Agents:基于Apache Flink的事件驱动AI智能体框架
|
9天前
|
人工智能 安全 中间件
阿里云 AI 中间件重磅发布,打通 AI 应用落地“最后一公里”
9 月 26 日,2025 云栖大会 AI 中间件:AI 时代的中间件技术演进与创新实践论坛上,阿里云智能集团资深技术专家林清山发表主题演讲《未来已来:下一代 AI 中间件重磅发布,解锁 AI 应用架构新范式》,重磅发布阿里云 AI 中间件,提供面向分布式多 Agent 架构的基座,包括:AgentScope-Java(兼容 Spring AI Alibaba 生态),AI MQ(基于Apache RocketMQ 的 AI 能力升级),AI 网关 Higress,AI 注册与配置中心 Nacos,以及覆盖模型与算力的 AI 可观测体系。
|
10天前
|
数据采集 人工智能 前端开发
Playwright与AI智能体的网页爬虫创新应用
厌倦重复测试与低效爬虫?本课程带您掌握Playwright自动化工具,并融合AI大模型构建智能体,实现网页自主分析、决策与数据提取,完成从脚本执行到智能架构的能力跃升。
|
10天前
|
人工智能 运维 安全
聚焦 AI 应用基础设施,云栖大会 Serverless AI 全回顾
2025 年 9 月 26 日,为期三天的云栖大会在杭州云栖小镇圆满闭幕。随着大模型技术的飞速发展,我们正从云原生时代迈向一个全新的 AI 原生应用时代。为了解决企业在 AI 应用落地中面临的高成本、高复杂度和高风险等核心挑战,阿里云基于函数计算 FC 发布一系列重磅服务。本文将对云栖大会期间 Serverless+AI 基础设施相关内容进行全面总结。
|
11天前
|
设计模式 机器学习/深度学习 人工智能
AI-Native (AI原生)图解+秒懂: 什么是 AI-Native 应用(AI原生应用)?如何设计一个 AI原生应用?
AI-Native (AI原生)图解+秒懂: 什么是 AI-Native 应用(AI原生应用)?如何设计一个 AI原生应用?
|
12天前
|
人工智能 负载均衡 API
Vercel 发布 AI Gateway 神器!可一键访问数百个模型,助力零门槛开发 AI 应用
大家好,我是Immerse,独立开发者、AGI实践者。分享编程、AI干货、开源项目与个人思考。关注公众号“沉浸式趣谈”,获取独家内容。Vercel新推出的AI Gateway,统一多模型API,支持自动切换、负载均衡与零加价调用,让AI开发更高效稳定。一行代码切换模型,告别接口烦恼!
133 1
Vercel 发布 AI Gateway 神器!可一键访问数百个模型,助力零门槛开发 AI 应用

热门文章

最新文章