AutoGen多角色、多用户、多智能体对话系统

2023-03-11-AutoGen

使用【autoGen+chainlit+deepSeek】实现【多角色、多用户、多智能体对话系统】


1-核心思路

  • 01)技术要点:autoGen+chainlit+deepSeek
  • 02)什么是autoGen->autogen是微软旗下的多智能体的框架
  • 03)什么是chainlit->模型前端展示框架
  • 04)要做什么?->快速实现多角色、多用户、多智能体对话系统
  • 05)什么是RoundRobinGroupChat?->反复调用
  • 06)单智能体-nurses_station_ai ->进行大模型问题咨询
  • 07)智能体与FunctionCall-> 大模型调用FunctionCall
  • 08)多智能体自动选择-> Selector Group Chat
  • 09)为什么设置TextMentionTermination->终止符
  • 10)什么是AutoGen Studio工作流UI->上面都是python代码实现,有没有拖拖拽拽就可以的UI编排
  • 11)最终目标->3分钟复刻Manus智能体!AutoGen+MCP Server+Cline构建最强AI智能体https://www.bilibili.com/video/BV119RHYmEPF

2-参考网址


3-上手实操

1-安装依赖

复制代码
# 版本说明
- python,3.11
- AutoGen,0.4.2
- chainlit,2.0.2
- 大模型,deepseek

# 安装依赖-autogen
pip install -U "autogen-agentchat" "autogen-ext[openai]"

# 安装依赖-UI交互界面
pip install chainlit

# 运行脚本
chainlit run .\a_01_nurses_station_ai.py -w

2-a_01_nurses_station_ai内容如下

复制代码
import chainlit as cl
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_ext.models.openai import OpenAIChatCompletionClient


@cl.on_chat_start
async def main():
    await cl.Message(content="您好,这里是超级无敌大医院,有什么可以帮您?").send()


async def run_team(query: str):
    model_client = OpenAIChatCompletionClient(model="deepseek-chat", base_url="https://api.deepseek.com",
                                              api_key="sk-6d775065fa8c405caebed674c125e67e",
                                              model_info={
                                                  "vision": False,
                                                  "function_calling": False,
                                                  "json_output": True,
                                                  "family": "unknown",
                                              }, )
    assistant_agent = AssistantAgent("assistant", model_client=model_client,
                                     system_message="你是一所口腔医院的导诊台机器人,负责解答用户的挂号问题,用户描述症状需求,你回答应该挂的科室。"
                                                    "在本医院中有以下科室:牙体牙髓科、口腔修复科、口腔外科、口腔种植科、儿童口腔专科。"
                                                    "如果用户的问题与挂号咨询不符合,回答:"您的描述与症状无关,暂不支持"")
    team = RoundRobinGroupChat(participants=[assistant_agent], max_turns=1)
    response_stream = team.run_stream(task=query)
    async for msg in response_stream:
        if hasattr(msg, "source") and msg.source != "user" and hasattr(msg, "content"):
            msg = cl.Message(content=msg.content, author="Agent Team")
            await msg.send()


@cl.on_message
async def main(message: cl.Message):
    await run_team(message.content)

3-智能体与FunctionCall

复制代码
import chainlit as cl
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_ext.models.openai import OpenAIChatCompletionClient


@cl.password_auth_callback
def auth_callback(username: str, password: str):
    if (username, password) == ("admin", "admin"):
        return cl.User(
            identifier="admin", metadata={"role": "admin", "provider": "credentials"}
        )
    elif (username, password) == ("puhaiyang", "123456"):
        return cl.User(
            identifier="puhaiyang", metadata={"role": "admin", "provider": "credentials"}
        )
    else:
        return None


@cl.on_chat_start
async def main():
    await cl.Message(content="您好,这里是牙体牙髓科,您牙齿哪里不适?").send()


async def x_p_search(tooth_position: str) -> str:
    """Find information on the web"""
    app_user = cl.user_session.get("user")
    print(f"模拟查询{app_user.identifier}的{tooth_position}牙片数据")
    if tooth_position == "46":
        return "牙根尖处有阴影,疑似感染,需要进一步分析诊断"
    else:
        return f"{tooth_position}无影像"


async def run_team(query: str):
    model_client = OpenAIChatCompletionClient(model="deepseek-chat", base_url="https://api.deepseek.com",
                                              api_key="sk-6d775065fa8c405caebed674c125e67e",
                                              model_info={
                                                  "vision": False,
                                                  "function_calling": True,
                                                  "json_output": True,
                                                  "family": "unknown",
                                              })
    assistant_agent = AssistantAgent("assistant", model_client=model_client, tools=[x_p_search],
                                     system_message="你是一个牙体牙髓科的病情诊断机器人,负责对用户输入的症状描述分析原因,在分析病因前先询问出用户是具体哪一颗牙齿需要治疗。"
                                                    "在知道了具体的牙位号后,再调用x_p_search工具进行问题回答,传入给x_p_search工具的参数需要自动转为牙位号,如:28"
                                                    "如果用户的问题与病情咨询无关,回答:"您的描述与症状无关,暂不支持"")
    team = RoundRobinGroupChat(participants=[assistant_agent], max_turns=1)
    response_stream = team.run_stream(task=query)
    async for msg in response_stream:
        if hasattr(msg, "source") and (msg.type == "ToolCallExecutionEvent" or msg.type == "ToolCallRequestEvent"):
            # functionCall事件消息不显示给用户
            continue
        if hasattr(msg, "source") and msg.source != "user" and hasattr(msg, "content"):
            if msg.content.endswith("无影像"):
                res = await cl.AskActionMessage(
                    content=f"{msg.content},是否需要帮您申请拍摄此牙的CT影像?",
                    actions=[
                        cl.Action(name="continue", payload={"value": "申请"}, label="✅ 申请牙片"),
                        cl.Action(name="cancel", payload={"value": "取消"}, label="❌ 取消"),
                    ],
                ).send()

                if res and res.get("payload").get("value") == "申请":
                    await cl.Message(
                        content="牙片申请已提交!待审核通过后前往第3影像室进行拍摄。",
                    ).send()
            else:
                msg = cl.Message(content=msg.content, author="Agent Team")
                await msg.send()


@cl.on_message
async def main(message: cl.Message):
    await run_team(message.content)
  • 执行脚本

    1-因为添加了chainlit认证配置

    conda activate AutoGen3_11
    chainlit create-secret

    2-配置JWT-创建.env文件

    CHAINLIT_AUTH_SECRET="-Nj%Z@l^x0FQcEKYuNBxJ@mYr~2L>_ua6EUzSsR6M~Fd.ssav5GFANVyR4%SZf"

    3-执行脚本

    chainlit run .\a_02_endodontics_dentistry_ai.py -w

  • 触发大模型的FunctionCall功能


4-如何解决chainlit报错

ValueError: You must provide a JWT secret in the environment to use authentication. Run chainlit create-secret to

generate one.

这个错误信息表明,在使用需要身份验证的功能时,你没有在环境变量中提供 JWT(JSON Web Token)密钥。JWT

是一种用于在网络应用中安全传输信息的开放标准,通常用于身份验证和授权。下面为你详细分析和解决这个问题:

1. 生成 JWT 密钥

依据错误提示,你可以运行 chainlit create-secret 命令来生成一个 JWT 密钥。打开命令行终端,激活你的 Python

虚拟环境(AutoGen3_11),然后执行以下命令:

bash 复制代码
conda activate AutoGen3_11
chainlit create-secret

执行该命令后,会输出一个随机生成的 JWT 密钥,类似如下:

复制代码
CHAINLIT_AUTH_SECRET="-Nj%Z@l^x0FQcEKYuNBxJ@mYr~2L>_ua6EU$zSsR6M~Fd.ssav5GFANVyR4%S$Zf"
2. 根目录创建.env文件

将刚才的生成的信息复制进去

复制代码
CHAINLIT_AUTH_SECRET="-Nj%Z@l^x0FQcEKYuNBxJ@mYr~2L>_ua6EU$zSsR6M~Fd.ssav5GFANVyR4%S$Zf"

5-多智能体自动选择

核心代码:创建多个AssistantAgent放入到SelectorGroupChat供大模型根据上线文进行选择

复制代码
import chainlit as cl

from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination
from autogen_agentchat.teams import SelectorGroupChat
from autogen_ext.models.openai import OpenAIChatCompletionClient

model_client = OpenAIChatCompletionClient(model="deepseek-chat", base_url="https://api.deepseek.com",
                                          api_key="sk-6d775065fa8c405caebed674c125e67e",
                                          model_info={
                                              "vision": False,
                                              "function_calling": True,
                                              "json_output": True,
                                              "family": "unknown",
                                          }, )

planning_agent = AssistantAgent("PlanningAgent",
                                description="用于规划的Agent,当一个任务到达时此Agent是第一个参与者",
                                model_client=model_client,
                                system_message="""
                                你是一个任务规划智能体。
                                你的工作是将复杂的任务分解为更小的、可管理的子任务。
                                你的团队成员有3个,分别是:
                                    DentalPulpAgent: 牙体牙髓科智能体
                                    RestorativeAgent: 牙齿修复科智能体
                                    DentalImplantAgent: 牙齿种植科智能体

                                你只计划和委派任务,而不自己执行它们

                                分配任务时,请使用此格式:
                                1. <agent> : <task>

                                当所有智能体把任务完成后,再总结结果以"TERMINATE"结束。                        
                                """
                                )

dental_pulp_agent = AssistantAgent("DentalPulpAgent",
                                   description="牙体牙髓科智能体",
                                   model_client=model_client,
                                   system_message="""
                                你是一个口腔医院的牙体牙髓科智能体。
                                你可以解答关于牙体牙髓科中患者提出的问题,你的解答非常专业,且可靠。
                                """
                                   )

restorative_agent = AssistantAgent("RestorativeAgent",
                                   description="牙齿修复科智能体",
                                   model_client=model_client,
                                   system_message="""
                                你是一个口腔医院的牙齿修复科智能体。
                                你可以解答关于牙齿修复中患者提出的问题,比如牙冠、烤瓷牙、嵌体修复等。你的解答非常专业,且可靠。
                                """
                                   )

dental_implant_agent = AssistantAgent("DentalImplantAgent",
                                      description="牙齿种植科智能体",
                                      model_client=model_client,
                                      system_message="""
                                你是一个口腔医院的牙齿种植科的智能体。
                                你可以解答关于牙齿种植科中患者提出的问题,你的解答非常专业,且可靠。
                                """
                                      )


@cl.on_chat_start
async def main():
    await cl.Message(content="您好,这里是口腔医院专家团队,有什么可以帮您?").send()


async def run_team(query: str):
    text_mention_termination = TextMentionTermination("TERMINATE")
    max_messages_termination = MaxMessageTermination(max_messages=25)
    termination = text_mention_termination | max_messages_termination

    team = SelectorGroupChat(
        [planning_agent, dental_pulp_agent, restorative_agent, dental_implant_agent],
        model_client=model_client,
        termination_condition=termination,
    )

    response_stream = team.run_stream(task=query)
    async for msg in response_stream:
        if hasattr(msg, "source") and msg.source != "user" and hasattr(msg, "content"):
            msg = cl.Message(content=msg.content, author=msg.source)
            await msg.send()


@cl.on_message
async def main(message: cl.Message):
    await run_team(message.content)
  • 执行脚本

    chainlit run .\a_03_dentistry_selector_ai.py -w


  • 测试问题

    什么是烤瓷牙?
    什么是根管治疗?


5-AutoGen Studio工作流UI

比较好的是AutoGen中也提供了与Dify类似UI界面操作的方式,即:AutoGen Studio。

  • 安装命令

    安装autogenstudio

    pip install -U autogenstudio

    运行脚本-指定一个文件夹进行数据存放

    autogenstudio ui --port 8081 --appdir autogenstuido_test

    程序运行打印

    2025-03-12 01:07:58.662 | INFO | autogenstudio.web.app:lifespan:35 - Application startup complete. Navigate to http://127.0.0.1:8081

相关推荐
小杜不吃糖4 小时前
llama源码学习·model.py[1]RMSNorm归一化
python·llama
qq_白羊座4 小时前
UI自动化:poium测试库使用文档
python·selenium·ui·appium
小白学大数据5 小时前
Python爬虫:从人民网提取视频链接的完整指南
大数据·开发语言·爬虫·python·音视频
小王子10245 小时前
设计模式Python版 模板方法模式(下)
python·设计模式·模板方法模式
愚戏师5 小时前
Python:函数(一)
开发语言·windows·python
莓事哒6 小时前
数据采集技术之python网络爬虫(中国天气网的爬取)
爬虫·python·pycharm
杜子腾dd6 小时前
13. Pandas :使用 to_excel 方法写入 Excel文件
大数据·python·数据挖掘·excel·numpy·pandas
shix .6 小时前
爬虫一些基础知识的备忘录(需要自取)
c++·爬虫·python
网络风云8 小时前
Django 5实用指南(十四)项目部署与性能优化【完】
python·性能优化·django