欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 艺术 > 使用 OpenAI 的 Node.js 通过 Ollama 在本地运行 DeepSeek R1

使用 OpenAI 的 Node.js 通过 Ollama 在本地运行 DeepSeek R1

2025/3/17 22:26:30 来源:https://blog.csdn.net/hefeng_aspnet/article/details/146070839  浏览:    关键词:使用 OpenAI 的 Node.js 通过 Ollama 在本地运行 DeepSeek R1

介绍

        DeepSeek R1是一款开源 LLM,可提供强大的生成式 AI 功能。如果您使用Ollama在本地运行它,您可能想知道如何将其与您的 Node.js 应用程序集成。本指南将向您展示如何设置和使用OpenAI SDK以及您本地运行的 DeepSeek R1 模型

步骤 1:使用 Ollama 在本地启动 DeepSeek R1

确保 Ollama 正在运行并且已下载 DeepSeek R1 模型。如果尚未安装,请执行以下操作:

ollama pull deepseek-r1:1.5b

然后,启动测试会话以验证其是否正常工作: 

ollama run deepseek-r1:1.5b

第 2 步:安装依赖项(Nodejs)

首先,确保您已安装 Node.js,然后安装 OpenAI SDK:

npm install openai

步骤 3:配置 OpenAI SDK 以使用 Ollama

const OpenAI = require("openai");

const openai = new OpenAI({
    baseURL: "http://localhost:11434/v1", // Pointing to Ollama's local API
    apiKey: "ollama", // Required by the OpenAI SDK, but Ollama doesn’t validate it
});

async function chatWithDeepSeek(prompt) {
    try {
        const response = await openai.chat.completions.create({
            model: "deepseek-r1:1.5b", // Ensure this model is running
            messages: [{ role: "user", content: prompt }],
        });

        console.log(response.choices[0].message.content);
    } catch (error) {
        console.error("Error:", error.message);
    }
}

// Test the function
chatWithDeepSeek("Hello, how are you?");

步骤 4:启用流式响应

为了提高性能并实时获得响应,请启用流式
 

传输函数的流式传输版本

async function chatWithDeepSeekStream(prompt) {
    try {
        const stream = await openai.chat.completions.create({
            model: "deepseek-r1:1.5b",
            messages: [{ role: "user", content: prompt }],
            stream: true, // Enable streaming
        });

        for await (const chunk of stream) {
            process.stdout.write(chunk.choices[0]?.delta?.content || "");
        }
        console.log("\n");
    } catch (error) {
        console.error("Error:", error.message);
    }
}

chatWithDeepSeekStream("Tell me a fun fact about space.");

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词