【AI Agent系列】【阿里AgentScope框架】6. 可视化:AgentScope的日志和WebUI模块使用介绍

作者 : admin 本文共4502个字,预计阅读时间需要12分钟 发布时间: 2024-06-16 共1人阅读

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


阿里的AgentScope框架比其它多智能体开发框架友好的一点就是,它可以让你的程序运行过程可视化,让你能可视化地记录和查看到程序运行的详细过程及日志,便于排查问题和调试。

类似 LangChain 的 LangSmith 和 Langfuse平台,只不过现在还不成熟。

文章目录

  • 0. 日志模块
  • 1. WebUI可视化
    • 1.1 使用方法
    • 1.2 实现原理
      • 1.2.1 实现框架
      • 1.2.2 展示项目的原理
      • 1.2.3 展示详细日志的原理
    • 1.3 从一些坑看其实现原理
    • 1.4 实时对话框UI

0. 日志模块

参考官方文档:https://modelscope.github.io/agentscope/zh_CN/tutorial/105-logging.html#logging-zh

(1)日志模块的引入

from loguru import logger

(2)日志模块的等级

LOG_LEVEL = Literal[
    "CHAT",
    "TRACE",
    "DEBUG",
    "INFO",
    "SUCCESS",
    "WARNING",
    "ERROR",
    "CRITICAL",
]

(3)日志记录的设置

通过 init 函数来设置日志开启的等级

agentscope.init(..., logger_level="INFO")

(4)一般日志记录(系统日志)

通过 info、warning、error等函数来记录系统日志。

# Log general information useful for understanding the flow of the application.
logger.info("The dialogue agent has started successfully.")

# Log a warning message indicating a potential issue that isn't immediately problematic.
logger.warning("The agent is running slower than expected.")

# Log an error message when something has gone wrong.
logger.error("The agent encountered an unexpected error while processing a request.")

(5)对话消息记录

AgentScope额外提供chat接口来记录对话消息,用来追踪智能体之间的对话。

# Log a simple string message.
logger.chat("Hello World!")

# Log a `msg` representing dialogue with a speaker and content.
logger.chat({"name": "User", "content": "Hello, how are you?"})
logger.chat({"name": "Agent", "content": "I'm fine, thank you!"})

1. WebUI可视化

WebUI用来将上述记录的日志进行可视化。

1.1 使用方法

只需要下面几行代码,运行即可:

注意只需要下面几行代码,不要插入到其它代码里,新开一个文件,单独运行下面几行。

import agentscope

agentscope.web.init(
    path_save="D:\GitHub\LEARN_LLM\runs"
)

运行后:

【AI Agent系列】【阿里AgentScope框架】6. 可视化:AgentScope的日志和WebUI模块使用介绍插图

浏览器打开 127.0.0.1:5000,可以看到如下界面:

【AI Agent系列】【阿里AgentScope框架】6. 可视化:AgentScope的日志和WebUI模块使用介绍插图(1)
点击进入某一个具体的ID后,会看到详细的日志记录:

【AI Agent系列】【阿里AgentScope框架】6. 可视化:AgentScope的日志和WebUI模块使用介绍插图(2)

1.2 实现原理

1.2.1 实现框架

WebUI模块部分源码如下:

from flask import Flask, jsonify, render_template, Response
from flask_cors import CORS
from flask_socketio import SocketIO

app = Flask(__name__)
socketio = SocketIO(app)
CORS(app)  # This will enable CORS for all routes

可以看到其实现原理是使用Flask框架,将前端与后端链接起来获取数据展示数据。

1.2.2 展示项目的原理

看下其加载数据的源码:

@app.route("/getProjects", methods=["GET"])
def get_projects() -> Response:
    """Get all the projects in the runs directory."""
    cfgs = []
    for run_dir in os.listdir(PATH_SAVE):
        print(run_dir)
        path_cfg = os.path.join(PATH_SAVE, run_dir, ".config")
        if os.path.exists(path_cfg):
            with open(path_cfg, "r", encoding="utf-8") as file:
                cfg = json.load(file)
                cfg["dir"] = run_dir
                cfgs.append(cfg)

    # Filter the same projects
    project_names = list({_["project"] for _ in cfgs})

    return jsonify(
        {
            "names": project_names,
            "runs": cfgs,
        },
    )

这个接口用来获取并展示所有运行过的项目。其实现原理是加载日志路径里面的文件(这个日志路径有坑,后面细说)。

1.2.3 展示详细日志的原理

用来获取和展示详细日志的源码如下,根据传进来的日志路径,读取文件内容,返回并展示:

@app.route("/run/")
def run_detail(run_dir: str) -> str:
    """Render the run detail page."""
    path_run = os.path.join(PATH_SAVE, run_dir)

    # Find the logging and chat file by suffix
    path_log = os.path.join(path_run, "logging.log")
    path_dialog = os.path.join(path_run, "logging.chat")

    if os.path.exists(path_log):
        with open(path_log, "r", encoding="utf-8") as file:
            logging_content = ["".join(file.readlines())]
    else:
        logging_content = None

    if os.path.exists(path_dialog):
        with open(path_dialog, "r", encoding="utf-8") as file:
            dialog_content = file.readlines()
        dialog_content = [json.loads(_) for _ in dialog_content]
    else:
        dialog_content = []

    path_cfg = os.path.join(PATH_SAVE, run_dir, ".config")
    if os.path.exists(path_cfg):
        with open(path_cfg, "r", encoding="utf-8") as file:
            cfg = json.load(file)
    else:
        cfg = {
            "project": "-",
            "name": "-",
            "id": "-",
            "timestamp": "-",
        }

    logging_and_dialog = {
        "config": cfg,
        "logging": logging_content,
        "dialog": dialog_content,
    }

    return render_template("run.html", runInfo=logging_and_dialog)

1.3 从一些坑看其实现原理

(1)这个WebUI不是实时显示程序运行结果的,它只是一个运行日志查看平台。

(2)如果运行了程序,而在WebUI中却没有看到你的这次运行,那么,请检查你WebUI的设置路径:

【AI Agent系列】【阿里AgentScope框架】6. 可视化:AgentScope的日志和WebUI模块使用介绍插图(3)
官方文档中只说了这里填”YOUR SAVE PATH”,但是很坑的是,这里的SAVE PATH,指的是已经保存过的日志的路径。

在我们真正的程序中,刚开始都要进行init

agentscope.init(model_configs=[openai_cfg_dict], logger_level="INFO")

而这个保存路径就隐藏在这个函数里,我之前并没有注意到(下面代码中的save_dir):

def init(
    model_configs: Optional[Union[dict, str, list]] = None,
    project: Optional[str] = None,
    name: Optional[str] = None,
    save_dir: str = _DEFAULT_DIR,
    save_log: bool = True,
    save_code: bool = True,
    save_api_invoke: bool = True,
    logger_level: LOG_LEVEL = _DEFAULT_LOG_LEVEL,
    agent_configs: Optional[Union[str, list, dict]] = None,
) -> Sequence[AgentBase]:

代码中的save_dir,默认是 _DEFAULT_DIR = "./runs",也就是工程目录下的./runs文件夹下。这才是真正的日志记录的位置。WebUI init 时的 path_save 路径,必须与这里的路径相同,否则它是加载不到这些日志的。

1.4 实时对话框UI

上面的WebUI是用来看日志的,非实时,也不能编辑。

AgentScope还提供另一种UI界面,实时对话。使用命令 as_studio 要运行的py即可:

as_studio .\agentscope\start_0\start_agentscope.py

注意:运行的py文件一定要以main函数开始,要存在main函数

运行后的效果:

【AI Agent系列】【阿里AgentScope框架】6. 可视化:AgentScope的日志和WebUI模块使用介绍插图(4)
浏览器打开这个网址:

【AI Agent系列】【阿里AgentScope框架】6. 可视化:AgentScope的日志和WebUI模块使用介绍插图(5)
就可以在输入框直接对话了。后台程序同时会进行日志输出:

【AI Agent系列】【阿里AgentScope框架】6. 可视化:AgentScope的日志和WebUI模块使用介绍插图(6)

如果运行报错 NoneType:

【AI Agent系列】【阿里AgentScope框架】6. 可视化:AgentScope的日志和WebUI模块使用介绍插图(7)
则很可能是你的环境不全,需要安装 gradio 和 modelscope_studio

pip install -U gradio -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install -U modelscope_studio -i https://pypi.tuna.tsinghua.edu.cn/simple

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


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

本站文章一览:

【AI Agent系列】【阿里AgentScope框架】6. 可视化:AgentScope的日志和WebUI模块使用介绍插图(8)

本站无任何商业行为
个人在线分享 » 【AI Agent系列】【阿里AgentScope框架】6. 可视化:AgentScope的日志和WebUI模块使用介绍
E-->