目錄

用 JavaScript / Node.js 串接 Ollama

安裝

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日