5分钟上手node-llama-cpp:本地AI模型部署的终极教程

【免费下载链接】node-llama-cpp Run AI models locally on your machine with node.js bindings for llama.cpp. Force a JSON schema on the model output on the generation level 【免费下载链接】node-llama-cpp 项目地址: https://gitcode.com/gh_mirrors/no/node-llama-cpp

node-llama-cpp是一个强大的Node.js绑定库,让你能够在本地机器上运行AI模型,通过llama.cpp实现高效部署。它支持强制模型输出符合JSON模式,为开发者提供了灵活且强大的本地AI解决方案。

node-llama-cpp项目logo node-llama-cpp项目logo:可爱的羊驼形象象征着LLaMA模型,背景的星空效果代表着AI的无限可能

为什么选择node-llama-cpp? 🚀

在AI模型部署变得越来越复杂的今天,node-llama-cpp提供了一种简单而强大的方式来在本地运行AI模型。无论是开发聊天机器人、文本生成工具还是需要AI支持的应用程序,node-llama-cpp都能满足你的需求。它自动检测并利用你硬件上可用的最佳计算层,无需手动配置即可获得最佳性能。

快速安装:两种方式任你选 ⚡

方式一:创建新项目(推荐新手)

如果你刚开始使用node-llama-cpp,最快速的入门方式是使用项目脚手架工具:

npm create node-llama-cpp@latest

这个命令会引导你完成项目创建过程,包括输入项目名称、选择模板和推荐模型。首次运行模型的用户,建议选择"Node + TypeScript"模板,它提供了完整的类型支持和最佳实践。

方式二:添加到现有项目

如果你已经有一个Node.js项目,只需运行以下命令即可将node-llama-cpp添加到项目中:

npm install node-llama-cpp

node-llama-cpp为macOS、Linux和Windows提供了预构建的二进制文件,无需额外编译。如果你的平台没有可用的二进制文件,它会自动下载llama.cpp源代码并使用cmake从源码构建。

获取模型文件:开始你的AI之旅 📦

要运行AI模型,你需要一个GGUF格式的模型文件。我们推荐从Hugging Face获取模型,特别是Michael Radermacher提供的模型。对于初学者,建议选择参数较少的模型(如7B/8B参数)来确保一切正常运行。

使用node-llama-cpp的内置模型下载器可以快速获取模型:

npx --no node-llama-cpp pull --dir ./models <model-file-url>

如果你不确定该选择哪个模型,可以运行聊天命令查看推荐模型列表:

npx --no node-llama-cpp chat

验证模型:确保一切正常工作 ✅

下载模型后,使用聊天命令验证模型是否正常工作:

npx --no node-llama-cpp chat <path-to-a-model-file-on-your-computer>

尝试输入"Hi there",看看模型如何响应。如果响应看起来不正常,可以尝试使用不同的聊天包装器:

npx --no node-llama-cpp chat --wrapper general <path-to-a-model-file-on-your-computer>

你还可以使用单个命令下载模型并立即提示它:

npx --no node-llama-cpp chat --prompt 'Hi there' <model-url>

基本用法:构建你的第一个聊天机器人 🤖

以下是一个简单的聊天机器人示例,展示了如何使用node-llama-cpp:

import {fileURLToPath} from "url";
import path from "path";
import {getLlama, LlamaChatSession} from "node-llama-cpp";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const llama = await getLlama();
const model = await llama.loadModel({
    modelPath: path.join(__dirname, "models", "Meta-Llama-3-8B-Instruct.Q4_K_M.gguf")
});
const context = await model.createContext();
const session = new LlamaChatSession({
    contextSequence: context.getSequence()
});

const q1 = "Hi there, how are you?";
console.log("User: " + q1);

const a1 = await session.prompt(q1);
console.log("AI: " + a1);

const q2 = "Summarize what you said";
console.log("User: " + q2);

const a2 = await session.prompt(q2);
console.log("AI: " + a2);

高级功能:JSON模式和函数调用 🚀

node-llama-cpp提供了强大的高级功能,让你能够更好地控制模型输出。

JSON模式强制

你可以强制模型根据JSON模式生成输出,这在需要结构化响应时非常有用:

const grammar = await llama.createGrammarForJsonSchema({
    type: "object",
    properties: {
        positiveWordsInUserMessage: {
            type: "array",
            items: { type: "string" }
        },
        userMessagePositivityScoreFromOneToTen: {
            enum: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        },
        nameOfUser: {
            oneOf: [{ type: "null" }, { type: "string" }]
        }
    }
});

const prompt = "Hi there! I'm John. Nice to meet you!";
const res = await session.prompt(prompt, { grammar });
const parsedRes = grammar.parse(res);

函数调用

node-llama-cpp支持函数调用,让模型能够在生成过程中检索信息或执行操作:

const functions = {
    getFruitPrice: defineChatSessionFunction({
        description: "Get the price of a fruit",
        params: {
            type: "object",
            properties: {
                name: { type: "string" }
            }
        },
        async handler(params) {
            // 实现获取水果价格的逻辑
        }
    })
};

const q1 = "Is an apple more expensive than a banana?";
const a1 = await session.prompt(q1, { functions });

GPU加速:释放硬件潜力 💻

node-llama-cpp会自动检测并使用你硬件上可用的最佳计算层:

  • Metal:在配备Apple Silicon的Mac上默认启用
  • CUDA:检测到支持时默认使用
  • Vulkan:检测到支持时默认使用

要检查你的硬件支持情况,运行:

npx --no node-llama-cpp inspect gpu

下一步:探索更多可能性 🌟

现在你已经掌握了node-llama-cpp的基础知识,可以通过阅读官方文档探索更多高级主题:

无论你是想构建聊天机器人、文本生成工具还是其他AI应用,node-llama-cpp都能为你提供强大而灵活的本地AI部署解决方案。立即开始你的本地AI之旅吧!

【免费下载链接】node-llama-cpp Run AI models locally on your machine with node.js bindings for llama.cpp. Force a JSON schema on the model output on the generation level 【免费下载链接】node-llama-cpp 项目地址: https://gitcode.com/gh_mirrors/no/node-llama-cpp

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐