介绍
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.");
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。