准备工作
在开始安装 node-llama-cpp 之前,先确认本地环境是否就绪。这个库依赖 Node.js 运行时,建议直接使用最新的 LTS 版本。
- Node.js 环境(推荐最新 LTS)
- npm 包管理器
- Git 版本控制工具
快速安装
node-llama-cpp 提供了预构建的二进制文件,覆盖 macOS、Linux 和 Windows 系统,所以日常使用直接通过 npm 就能搞定。
npm install node-llama-cpp
这条命令会自动检测当前系统并下载对应的二进制包。如果当前系统没有现成的预编译文件,它也会尝试自动拉取 llama.cpp 源码进行本地构建,不过这个过程可能需要一些时间。
Windows 系统详细指南
依赖安装
如果在 Windows 上需要源码构建,得准备好 C++ 构建工具。WinGet 是 Win10/11 自带的包管理工具,可以直接一键安装所需组件:
winget install --id Microsoft.VisualStudio.2022.BuildTools --force --override "--add Microsoft.VisualStudio.Component.VC.CMake.Project Microsoft.VisualStudio.Component.VC.CoreBuildTools Microsoft.VisualStudio.Component.VC.Tools.x86.x64 Microsoft.VisualStudio.Component.VC.ATL Microsoft.VisualStudio.Component.VC.ATLMFC Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset Microsoft.VisualStudio.Component.VC.Llvm.Clang Microsoft.VisualStudio.Component.VC.Redist.14.Latest Microsoft.Component.VC.Runtime.UCRTSDK Microsoft.VisualStudio.Component.Windows10SDK Microsoft.VisualStudio.Component.Windows10SDK.20348"
当然,也可以手动去官网下载 Visual C++ Build Tools,记得勾选以下关键项:
- C++ CMake 工具
- C++ Clang 编译器
- Windows 10 SDK
- Windows Universal CRT SDK
ARM64 架构补充
如果你用的是 Windows on Arm 设备,构建指令里还得加上 ARM64 相关的组件,比如 Microsoft.VisualStudio.Component.VC.Tools.ARM64 等,确保编译器支持目标架构。
Linux 系统详细指南
依赖安装
Linux 下主要缺的是编译器和构建工具链。Debian/Ubuntu 系可以用 apt 直接拉取:
sudo apt-get update
sudo apt-get install build-essential cmake git libstdc++6 libgomp1
其中 libgomp1 是为了支持 OpenMP 并行计算,别漏掉。
源码构建
如果预编译包不满足需求,可以手动触发构建流程:
npx node-llama-cpp source download
npx node-llama-cpp source build
Mac 系统详细指南
Xcode 命令行工具
macOS 用户第一步通常是安装 Xcode 的命令行工具,这是编译的基础:
xcode-select --install
Homebrew 依赖
接着用 Homebrew 补全其他依赖:
brew install cmake git
源码构建
构建命令同 Linux 一样:
npx node-llama-cpp source download
npx node-llama-cpp source build
模型自动下载配置
为了让项目初始化后自动拉取模型文件,建议在 package.json 里配置 postinstall 脚本。具体写法可以参考官方文档中的 CLI 使用说明部分。
常见问题排查
构建失败
遇到构建报错时,先检查构建工具链是否完整。不同平台的依赖差异较大,如果不确定缺什么,查阅官方构建文档通常能找到线索。
Windows 权限问题
在 Windows 上如果遇到权限错误,尽量避免直接用管理员账户运行 npm install,普通用户权限往往更稳妥。
Electron 应用构建
打包 Electron 应用时,若出现 EPERM: operation not permitted 错误,可能是符号链接创建受限。此时需要在开发者模式下运行,或者调整相关权限设置。
总结
现在你应该已经掌握了在三大主流操作系统上部署 node-llama-cpp 的方法。无论是快速体验还是深度集成,这套流程都能帮你把本地 AI 推理跑起来。后续遇到具体问题,查阅项目文档或提交 Issue 都是不错的解决途径。
