目录

Ollama JavaScript / Node.js 教程:掌握对话、流式输出与 API 调用

安装

npm install ollama

基本对话

import ollama from "ollama";

const response = await ollama.chat({
  model: "qwen3:8b",
  messages: [
    { role: "system", content: "请用简体中文回答。" },
    { role: "user", content: "JavaScript 和 TypeScript 有什么不同?" },
  ],
});

console.log(response.message.content);

(使用 ES modules:文件名使用 .mjs,或在 package.json 中设置 "type": "module"。)

流式输出

import ollama from "ollama";

const stream = await ollama.chat({
  model: "qwen3:8b",
  messages: [{ role: "user", content: "写一首四行短诗" }],
  stream: true,
});

for await (const part of stream) {
  process.stdout.write(part.message.content);
}

中止生成

用户按下“停止”时:

const stream = await ollama.chat({ model: "qwen3:8b", messages, stream: true });

setTimeout(() => stream.abort(), 3000); // 3 秒后中止

try {
  for await (const part of stream) process.stdout.write(part.message.content);
} catch (err) {
  if (err.name === "AbortError") console.log("\n已停止");
}

连接到其他主机

import { Ollama } from "ollama";

const client = new Ollama({ host: "http://192.168.1.50:11434" });
const res = await client.chat({ model: "qwen3:8b", messages: [{ role: "user", content: "你好" }] });

在浏览器中使用

import ollama from "ollama/browser";

从网页直接调用本机的 Ollama 时,需要设置 OLLAMA_ORIGINS,允许网页来源访问,参见环境变量与设置。在正式产品中,通常由自己的后端转发请求,不让浏览器直接连接 Ollama。

不安装包:直接使用 fetch

const res = await fetch("http://localhost:11434/api/chat", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "qwen3:8b",
    messages: [{ role: "user", content: "你好" }],
    stream: false,
  }),
});
const data = await res.json();
console.log(data.message.content);

使用 fetch 处理流式输出

流式响应每行包含一个 JSON(NDJSON):

const res = await fetch("http://localhost:11434/api/chat", {
  method: "POST",
  body: JSON.stringify({ model: "qwen3:8b", messages: [{ role: "user", content: "从 1 数到 10" }] }),
});

const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";

while (true) {
  const { value, done } = await reader.read();
  if (done) break;
  buffer += decoder.decode(value, { stream: true });
  const lines = buffer.split("\n");
  buffer = lines.pop(); // 最后一行可能不完整,留到下次
  for (const line of lines) {
    if (!line.trim()) continue;
    const chunk = JSON.parse(line);
    process.stdout.write(chunk.message?.content ?? "");
  }
}

使用 OpenAI SDK

npm install openai
import OpenAI from "openai";

const openai = new OpenAI({ baseURL: "http://localhost:11434/v1", apiKey: "ollama" });

const completion = await openai.chat.completions.create({
  model: "qwen3:8b",
  messages: [{ role: "user", content: "你好" }],
});
console.log(completion.choices[0].message.content);

简单的 Express API

将 Ollama 封装成自己的 API,供前端调用:

import express from "express";
import ollama from "ollama";

const app = express();
app.use(express.json());

app.post("/api/ask", async (req, res) => {
  const { question } = req.body;
  res.setHeader("Content-Type", "text/plain; charset=utf-8");
  const stream = await ollama.chat({
    model: "qwen3:8b",
    messages: [
      { role: "system", content: "请用简体中文简洁回答。" },
      { role: "user", content: question },
    ],
    stream: true,
  });
  for await (const part of stream) res.write(part.message.content);
  res.end();
});

app.listen(3000, () => console.log("http://localhost:3000"));
curl -N -X POST http://localhost:3000/api/ask \
  -H "Content-Type: application/json" \
  -d '{"question":"什么是 API?"}'

更新于 2026年10月12日