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

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


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

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

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"
)

运行后:

在这里插入图片描述

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

在这里插入图片描述
点击进入某一个具体的ID后,会看到详细的日志记录:

在这里插入图片描述

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/<run_dir>")
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的设置路径:

在这里插入图片描述
官方文档中只说了这里填"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函数

运行后的效果:

在这里插入图片描述
浏览器打开这个网址:

在这里插入图片描述
就可以在输入框直接对话了。后台程序同时会进行日志输出:

在这里插入图片描述

如果运行报错 NoneType:

在这里插入图片描述
则很可能是你的环境不全,需要安装 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 一起交流💬,一起进步💪。
  • 微信公众号也可搜同学小张 🙏

本站文章一览:

在这里插入图片描述

  • 11
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

同学小张

如果觉得有帮助,欢迎给我鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值