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流程图无需重复配置。

相关推荐
默_笙4 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003964 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫4 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技4 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读4 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
感谢地心引力4 天前
我用 Doubao-Seed-2.1-pro 做了一个深度融入 AI 功能的本地知识库软件
ai·开源·seed·markdown·豆包
只睡四小时4 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
阿昌喜欢吃黄桃4 天前
提示词工程:User Prompt 与 System Prompt
ai·prompt·提示词·提示词工程
AI产品测评官4 天前
海内外AI招聘工具分赛道横向对比:五大品类的技术路线与选型参考
人工智能·ai·求职招聘
奇思妙想聪明勤奋的小羊4 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型