WSL中使用Mermaid离线生成LangGraph流程图

在WSL(Ubuntu/Debian)环境下,Mermaid离线生成PNG常卡在Chrome Headless下载、依赖缺失、版本兼容等问题上。本文提供极简配置流程,10分钟搞定环境,支持一键自动化生成。

一、核心痛点

  1. Chrome Headless下载报错ECONNRESET
  2. 系统共享库缺失(如libnspr4.so);
  3. mmdc与Chrome版本不兼容;
  4. 自动化生成时路径不匹配、误判结果。

二、环境准备(3步搞定)

  1. WSL发行版:Ubuntu 20.04/22.04;

  2. Node.js(LTS版)+ npm,配置淘宝镜像:

    bash 复制代码
    npm config set registry https://registry.npmmirror.com/
  3. Python 3.8+,安装IPython:

    bash 复制代码
    pip install ipython

三、核心配置:Chrome Headless(关键步骤)

1. 配置网络代理(如果网络不通报ECONNRESET错)

Windows启动代理工具(如端口7897),WSL终端执行:

bash 复制代码
export HTTP_PROXY=http://127.0.0.1:7897
export HTTPS_PROXY=http://127.0.0.1:7897

2. 一键下载Chrome Headless

bash 复制代码
npx puppeteer browsers install chrome-headless-shell
  • 自动缓存到/home/用户名/.cache/puppeteer/

3. 补全系统依赖

bash 复制代码
sudo apt update && sudo apt install -y libnspr4 libnss3 libatk1.0-0 libgtk-3-0

4. 验证Chrome有效性

bash 复制代码
# 查找Chrome路径
find /home/用户名/.cache/puppeteer/ -name "chrome-headless-shell" -type f
# 验证版本(替换为查找结果)
/你的Chrome路径 --headless=new --version
  • 输出Chrome xxx.xx.xxxx.xxx即为成功

四、安装配置mmdc(2步)

1. 安装新版mmdc(兼容Chrome)

bash 复制代码
npm install -g @mermaid-js/mermaid-cli

2. 配置环境变量(永久生效)

bash 复制代码
vim ~/.bashrc
# 末尾添加(替换为你的Chrome路径)
export PUPPETEER_EXECUTABLE_PATH=/home/用户名/.cache/puppeteer/.../chrome-headless-shell
# 生效配置
source ~/.bashrc

3. 快速验证

bash 复制代码
# 新建测试文件
echo "```mermaid
flowchart LR
A[开始] --> B[执行] --> C[结束]
```" > test.md
# 生成PNG
mmdc -i test.md -o test.png -w 2000 -H 1000
  • 目录出现test.png(或test-1.png)即成功

五、Python自动化:LangGraph流程图一键生成

1. 前置准备

bash 复制代码
pip install langgraph

2. 自动化函数(直接复制使用)

python 复制代码
import os
import re
import subprocess
from IPython.display import Image, display

def display_langgraph_flow(agent):
    """从LangGraph Agent提取Mermaid,离线生成PNG并显示"""
    try:
        # 1. 固定路径,提取Mermaid文本
        script_dir = os.path.dirname(os.path.abspath(__file__))
        mermaid_text = agent.get_graph(xray=True).draw_mermaid()
        mermaid_file = os.path.join(script_dir, "langgraph_flow.md")
        
        # 2. 保存带代码块的Markdown(mmdc必需)
        with open(mermaid_file, "w", encoding="utf-8") as f:
            f.write(f"```mermaid\n{mermaid_text}\n```")
        
        # 3. 调用mmdc生成PNG
        png_base = os.path.join(script_dir, "langgraph_flow")
        result = subprocess.run(
            f"mmdc -i {mermaid_file} -o {png_base}.png -w 2000 -H 1000",
            shell=True, capture_output=True, text=True
        )
        
        # 4. 解析实际生成的PNG文件(兼容-1后缀)
        actual_png = None
        match = re.search(r'✅\s*(.+?\.png)', result.stdout, re.IGNORECASE)
        if match:
            actual_png = os.path.join(script_dir, match.group(1).strip())
        else:
            for file in os.listdir(script_dir):
                if file.startswith("langgraph_flow") and file.endswith(".png"):
                    actual_png = os.path.join(script_dir, file)
                    break
        
        # 5. 验证并显示
        if not actual_png or not os.path.exists(actual_png):
            raise Exception("未找到生成的PNG文件")
        print(f"✅ 流程图生成:{actual_png}")
        display(Image(actual_png))
        
    except Exception as e:
        print(f"❌ 错误:{str(e)}")

3. 使用方法

python 复制代码
# 传入LangGraph Agent对象调用
display_langgraph_flow(your_langgraph_agent)

六、避坑速查

  1. 下载报错ECONNRESET:检查代理或切换手机热点;
  2. 库缺失:执行apt install -y libnspr4 libgtk-3-0
  3. 后缀-1问题:函数自动兼容,无需手动处理;
  4. 找不到mmdc:用which mmdc获取绝对路径,替换函数中命令。

总结

核心流程:代理下载Chrome → 补依赖 → 配置mmdc → 自动化生成。配置完成后,可离线生成任意Mermaid图表,LangGraph流程图无需重复配置。

相关推荐
zzZ··*15 小时前
自动登录上海大学校园
python·网络协议·selenium
weisian15115 小时前
进阶篇-4-数学篇-3--深度解析AI中的向量概念:从生活到代码,一文吃透核心逻辑
人工智能·python·生活·向量
写代码的【黑咖啡】15 小时前
Python中的Msgpack:高效二进制序列化库
开发语言·python
MistaCloud15 小时前
Pytorch进阶训练技巧(二)之梯度层面的优化策略
人工智能·pytorch·python·深度学习
AIFQuant15 小时前
2026 全球股市实时行情数据 API 对比指南
python·websocket·金融·数据分析·restful
爱吃肉的鹏15 小时前
使用Flask在本地调用树莓派摄像头
人工智能·后端·python·flask·树莓派
Elastic 中国社区官方博客15 小时前
Elasticsearch:监控 LLM 推理和 Agent Builder 使用 OpenRouter
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
2501_9445264215 小时前
Flutter for OpenHarmony 万能游戏库App实战 - 主题切换实现
android·开发语言·javascript·python·flutter·游戏·django
深蓝电商API15 小时前
Selenium处理iframe嵌套页面实战
爬虫·python·selenium
一晌小贪欢15 小时前
Python 健壮性进阶:精通 TCP/IP 网络编程与 requirements.txt 的最佳实践
开发语言·网络·python·网络协议·tcp/ip·python基础·python小白