📋 接口总览
Ollama 提供 RESTful HTTP API,默认监听在 http://localhost:11434。所有请求与响应均使用 JSON 格式。流式响应使用 NDJSON(newline-delimited JSON)。云端模型可通过 https://ollama.com/api 访问相同的 API。
⚡ 快速开始
在开始之前,确保 Ollama 已安装并运行。安装 SDK 依赖后即可使用。
// 安装: npm install ollama
import Ollama from 'ollama';
// 默认连接本地 http://localhost:11434
const ollama = new Ollama();
// 也可以指定远程地址
const remoteOllama = new Ollama({ host: 'http://192.168.1.100:11434' });
// 使用云端模型 (ollama.com)
const cloudOllama = new Ollama({ host: 'https://ollama.com/api' });
// 无需安装任何依赖,使用原生 fetch 即可
const OLLAMA_BASE = 'http://localhost:11434';
// 所有请求都是 POST (除少数 GET 接口)
const response = await fetch(`${OLLAMA_BASE}/api/generate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'gemma3',
prompt: '你好,世界!',
}),
});
const data = await response.json();
console.log(data.response);
⚙️ 模型参数 (Options)
以下参数可在 options 字段中传入,控制生成行为。适用于 /api/generate 和 /api/chat 等接口。
| 参数名 | 类型 | 描述 |
| seed | integer | 随机种子,用于可复现的输出 |
| temperature | float | 控制随机性,值越高越随机(默认约 0.8) |
| top_k | integer | 限制下一个 token 从概率最高的 K 个中选取 |
| top_p | float | 核采样的累积概率阈值 |
| min_p | float | token 选择的最低概率阈值 |
| stop | string | string[] | 停止序列,遇到时终止生成 |
| num_ctx | integer | 上下文窗口大小(token 数) |
| num_predict | integer | 最大生成 token 数 |
POST /api/generate
生成文本响应(补全模式)。支持流式/非流式、结构化输出、图像输入、Thinking 模式、logprobs 等功能。适用于 gpt-oss、Gemma 3、DeepSeek-R1、Qwen3 等模型。
POST
http://localhost:11434/api/generate
📥 请求参数
| 参数名 | 类型 | 必填 | 描述 |
| model | string | 必填 | 模型名称,如 "gemma3" |
| prompt | string | 可选 | 提示文本。省略时仅加载模型 |
| suffix | string | 可选 | 中间填充模式 (FIM) 中,出现在 prompt 后、response 前的文本 |
| images | string[] | 可选 | Base64 编码的图像数组(多模态模型) |
| format | string | object | 可选 | 结构化输出格式,可传 "json" 或 JSON Schema 对象 |
| system | string | 可选 | 系统提示词 |
| stream | boolean | 可选 | 是否流式返回(默认 true) |
| think | boolean | string | 可选 | 启用 Thinking 模式。可传 true/false 或 "high"/"medium"/"low" |
| raw | boolean | 可选 | 跳过模板处理,返回模型原始输出 |
| keep_alive | string | number | 可选 | 模型保持加载时间,如 "5m"。传 0 立即卸载 |
| options | object | 可选 | 模型参数(见上方 Options 表格) |
| logprobs | boolean | 可选 | 是否返回 token 的对数概率 |
| top_logprobs | integer | 可选 | 每个位置返回的候选 token 数(需 logprobs=true) |
📤 响应字段
| 字段名 | 类型 | 描述 |
| model | string | 模型名称 |
| created_at | string | ISO 8601 时间戳 |
| response | string | 模型生成的文本 |
| thinking | string | Thinking 模式下的思考输出 |
| done | boolean | 是否生成完毕 |
| done_reason | string | 停止原因(如 "stop") |
| total_duration | integer | 总耗时(纳秒) |
| load_duration | integer | 模型加载耗时(纳秒) |
| prompt_eval_count | integer | 输入 token 数 |
| prompt_eval_duration | integer | Prompt 评估耗时(纳秒) |
| eval_count | integer | 输出 token 数 |
| eval_duration | integer | 生成 token 耗时(纳秒) |
💡 提示:流式模式下,每个 chunk 都是独立的 NDJSON 事件,response 字段为当前片段文本,最后一个 chunk 的 done 为 true 并包含统计信息。
💻 代码示例
import Ollama from 'ollama';
const ollama = new Ollama();
// 流式生成
const stream = await ollama.generate({
model: 'gemma3',
prompt: '用简单的语言解释量子计算',
stream: true,
options: {
temperature: 0.7,
num_predict: 512,
},
});
for await (const chunk of stream) {
process.stdout.write(chunk.response);
if (chunk.done) {
console.log(`\n\n[完成] 总耗时: ${(chunk.total_duration / 1e9).toFixed(2)}s`);
console.log(`[统计] 输入: ${chunk.prompt_eval_count} tokens, 输出: ${chunk.eval_count} tokens`);
}
}
// 流式生成(逐行读取 NDJSON)
const response = await fetch('http://localhost:11434/api/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'gemma3',
prompt: '用简单的语言解释量子计算',
stream: true,
options: { temperature: 0.7 },
}),
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = 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.response);
if (chunk.done) console.log('\n[流结束]');
}
}
import Ollama from 'ollama';
const ollama = new Ollama();
// 非流式 + 结构化 JSON 输出
const result = await ollama.generate({
model: 'gemma3',
prompt: '列出中国人口最多的5个城市,包含城市名和人口数',
stream: false,
format: {
type: 'object',
properties: {
cities: {
type: 'array',
items: {
type: 'object',
properties: {
name: { type: 'string' },
population: { type: 'integer' },
},
required: ['name', 'population'],
},
},
},
required: ['cities'],
},
});
const data = JSON.parse(result.response);
console.log('结构化结果:', JSON.stringify(data, null, 2));
// HTTP 非流式 + 结构化输出
const response = await fetch('http://localhost:11434/api/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'gemma3',
prompt: '列出中国人口最多的5个城市',
stream: false,
format: {
type: 'object',
properties: {
cities: {
type: 'array',
items: {
type: 'object',
properties: {
name: { type: 'string' },
population: { type: 'integer' },
},
required: ['name', 'population'],
},
},
},
required: ['cities'],
},
}),
});
const data = await response.json();
console.log(JSON.parse(data.response));
import Ollama from 'ollama';
import { readFileSync } from 'fs';
const ollama = new Ollama();
// 读取图片并转为 Base64
const imageBuffer = readFileSync('./photo.jpg');
const imageBase64 = imageBuffer.toString('base64');
// 多模态图像识别
const result = await ollama.generate({
model: 'gemma3',
prompt: '这张图片里有什么?请详细描述。',
images: [imageBase64],
stream: false,
});
console.log(result.response);
// HTTP 图像识别
// 将本地图片转为 Base64
const fs = require('fs');
const imageBuffer = fs.readFileSync('./photo.jpg');
const imageBase64 = imageBuffer.toString('base64');
const response = await fetch('http://localhost:11434/api/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'gemma3',
prompt: '这张图片里有什么?请详细描述。',
images: [imageBase64],
stream: false,
}),
});
const data = await response.json();
console.log(data.response);
📤 响应示例
{
"model": "gemma3",
"created_at": "2026-05-18T08:14:07.414671Z",
"response": "量子计算是一种利用量子力学原理进行计算的新型计算方式...",
"done": true,
"done_reason": "stop",
"total_duration": 174560334,
"load_duration": 101397084,
"prompt_eval_count": 11,
"prompt_eval_duration": 13074791,
"eval_count": 128,
"eval_duration": 52479709
}
POST /api/chat
对话模式生成消息。支持多轮对话、工具调用 (Tool Calling)、Thinking 模式、结构化输出、图像输入、logprobs。适用于 gpt-oss、Gemma 3、Qwen3 等模型。
POST
http://localhost:11434/api/chat
📥 请求参数
| 参数名 | 类型 | 必填 | 描述 |
| model | string | 必填 | 模型名称 |
| messages | array | 必填 | 对话历史消息数组 |
| messages[].role | string | 必填 | 角色: "system" | "user" | "assistant" | "tool" |
| messages[].content | string | 必填 | 消息文本 |
| messages[].images | string[] | 可选 | Base64 编码的图像数组 |
| messages[].tool_calls | array | 可选 | 工具调用请求 |
| tools | array | 可选 | 可用的函数工具列表 |
| format | string | object | 可选 | 结构化输出格式 |
| stream | boolean | 可选 | 是否流式返回(默认 true) |
| think | boolean | string | 可选 | Thinking 模式 |
| keep_alive | string | number | 可选 | 模型保持加载时间 |
| options | object | 可选 | 模型参数 |
| logprobs | boolean | 可选 | 是否返回对数概率 |
| top_logprobs | integer | 可选 | 每位置候选 token 数 |
📤 响应字段
| 字段名 | 类型 | 描述 |
| model | string | 模型名称 |
| created_at | string | ISO 8601 时间戳 |
| message | object | 包含 role, content, thinking, tool_calls 等 |
| message.role | string | 始终为 "assistant" |
| message.content | string | 助手回复文本 |
| message.thinking | string | Thinking 模式的思考输出 |
| message.tool_calls | array | 模型请求的工具调用 |
| message.images | string[] | Base64 编码的图像(部分模型支持) |
| done | boolean | 是否完成 |
| done_reason | string | 停止原因 |
| total_duration | integer | 总耗时(纳秒) |
| eval_count | integer | 输出 token 数 |
💻 代码示例
import Ollama from 'ollama';
const ollama = new Ollama();
// 多轮对话
const messages = [
{ role: 'system', content: '你是一个专业的编程助手,请用中文回答。' },
{ role: 'user', content: 'JavaScript 中 Promise 和 async/await 的区别是什么?' },
];
const response = await ollama.chat({
model: 'gemma3',
messages,
stream: true,
});
let fullReply = '';
for await (const chunk of response) {
const text = chunk.message.content;
fullReply += text;
process.stdout.write(text);
}
// 追加助手回复,继续对话
messages.push({ role: 'assistant', content: fullReply });
messages.push({ role: 'user', content: '能给一个 async/await 的代码示例吗?' });
// HTTP 多轮对话(非流式)
const response = await fetch('http://localhost:11434/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'gemma3',
stream: false,
messages: [
{ role: 'system', content: '你是一个专业的编程助手。' },
{ role: 'user', content: '解释 JavaScript 的事件循环机制' },
],
}),
});
const data = await response.json();
console.log(data.message.content);
console.log(`输出 ${data.eval_count} tokens,耗时 ${(data.eval_duration / 1e6).toFixed(0)}ms`);
import Ollama from 'ollama';
const ollama = new Ollama();
// 定义工具
const tools = [{
type: 'function',
function: {
name: 'get_weather',
description: '获取指定城市的当前天气信息',
parameters: {
type: 'object',
properties: {
city: {
type: 'string',
description: '城市名称,如 "北京"',
},
unit: {
type: 'string',
enum: ['celsius', 'fahrenheit'],
description: '温度单位',
},
},
required: ['city'],
},
},
}];
// 第一轮:模型可能请求调用工具
const response1 = await ollama.chat({
model: 'qwen3',
messages: [{ role: 'user', content: '北京今天天气怎么样?' }],
tools,
stream: false,
});
if (response1.message.tool_calls?.length) {
const toolCall = response1.message.tool_calls[0];
console.log(`模型调用: ${toolCall.function.name}`, toolCall.function.arguments);
// 模拟工具执行结果
const weatherResult = '晴天,温度 22°C,微风';
// 第二轮:将工具结果返回给模型
const response2 = await ollama.chat({
model: 'qwen3',
messages: [
{ role: 'user', content: '北京今天天气怎么样?' },
response1.message,
{
role: 'tool',
content: weatherResult,
},
],
stream: false,
});
console.log('最终回复:', response2.message.content);
}
// HTTP 工具调用
const response = await fetch('http://localhost:11434/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'qwen3',
messages: [
{ role: 'user', content: '巴黎今天天气如何?' },
],
stream: false,
tools: [{
type: 'function',
function: {
name: 'get_current_weather',
description: '获取指定地点的当前天气',
parameters: {
type: 'object',
properties: {
location: { type: 'string', description: '地点' },
format: { type: 'string', enum: ['celsius', 'fahrenheit'] },
},
required: ['location', 'format'],
},
},
}],
}),
});
const data = await response.json();
console.log('工具调用:', data.message.tool_calls);
import Ollama from 'ollama';
const ollama = new Ollama();
// Thinking 模式 - 让模型先思考再回答
const response = await ollama.chat({
model: 'gpt-oss',
messages: [
{ role: 'user', content: '如果一个房间里有3个人,每两个人握手一次,一共握了几次手?' },
],
think: 'low', // 可选: true/false/"high"/"medium"/"low"
stream: true,
});
let thinking = '';
let content = '';
for await (const chunk of response) {
if (chunk.message.thinking) {
thinking += chunk.message.thinking;
process.stderr.write(chunk.message.thinking); // 思考过程
}
if (chunk.message.content) {
content += chunk.message.content;
process.stdout.write(chunk.message.content); // 最终答案
}
}
// HTTP Thinking 模式(流式读取)
const response = await fetch('http://localhost:11434/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'gpt-oss',
messages: [
{ role: 'user', content: '如果一个房间里有3个人,每两个人握手一次,一共握了几次手?' },
],
think: 'low',
}),
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
console.log('=== 思考过程 ===');
while (true) {
const { done, value } = 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);
if (chunk.message?.thinking) {
process.stderr.write(chunk.message.thinking);
}
if (chunk.message?.content) {
process.stdout.write(chunk.message.content);
}
}
}
📤 响应示例
{
"model": "gemma3",
"created_at": "2026-05-18T08:14:07.414671Z",
"message": {
"role": "assistant",
"content": "Promise 和 async/await 的主要区别在于语法和错误处理方式..."
},
"done": true,
"done_reason": "stop",
"total_duration": 174560334,
"load_duration": 101397084,
"prompt_eval_count": 24,
"prompt_eval_duration": 13074791,
"eval_count": 156,
"eval_duration": 52479709
}
POST /api/embed
生成文本的向量嵌入。用于语义搜索、RAG 检索增强生成、文本相似度比较等场景。支持批量输入和自定义维度。
POST
http://localhost:11434/api/embed
📥 请求参数
| 参数名 | 类型 | 必填 | 描述 |
| model | string | 必填 | 嵌入模型名称,如 "embeddinggemma" |
| input | string | string[] | 必填 | 待编码的文本或文本数组 |
| truncate | boolean | 可选 | 是否截断超长输入(默认 true) |
| dimensions | integer | 可选 | 生成的嵌入维度数 |
| keep_alive | string | 可选 | 模型保持加载时间 |
| options | object | 可选 | 模型参数 |
📤 响应字段
| 字段名 | 类型 | 描述 |
| model | string | 使用的模型 |
| embeddings | number[][] | 向量嵌入数组 |
| total_duration | integer | 总耗时(纳秒) |
| load_duration | integer | 模型加载耗时(纳秒) |
| prompt_eval_count | integer | 输入 token 数 |
💻 代码示例
import Ollama from 'ollama';
const ollama = new Ollama();
// 单条文本嵌入
const single = await ollama.embed({
model: 'embeddinggemma',
input: 'Ollama 是一个本地运行大语言模型的工具',
});
console.log(`维度: ${single.embeddings[0].length}`);
// 批量文本嵌入
const batch = await ollama.embed({
model: 'embeddinggemma',
input: [
'JavaScript 是一种编程语言',
'Python 常用于数据科学',
'机器学习是 AI 的子领域',
],
dimensions: 256, // 自定义维度
});
console.log(`生成了 ${batch.embeddings.length} 个向量`);
// HTTP 批量嵌入
const response = await fetch('http://localhost:11434/api/embed', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'embeddinggemma',
input: [
'什么是机器学习?',
'深度学习与传统机器学习的区别',
'如何训练一个神经网络',
],
dimensions: 128,
}),
});
const data = await response.json();
console.log(`模型: ${data.model}`);
console.log(`向量数: ${data.embeddings.length}`);
console.log(`维度: ${data.embeddings[0].length}`);
console.log(`耗时: ${(data.total_duration / 1e6).toFixed(0)}ms`);
import Ollama from 'ollama';
const ollama = new Ollama();
// 实际用法: 语义搜索
function cosineSimilarity(a, b) {
const dot = a.reduce((s, v, i) => s + v * b[i], 0);
const magA = Math.sqrt(a.reduce((s, v) => s + v * v, 0));
const magB = Math.sqrt(b.reduce((s, v) => s + v * v, 0));
return dot / (magA * magB);
}
const docs = [
'Python 是一种通用编程语言',
'机器学习使用统计方法让计算机学习',
'React 是一个前端 JavaScript 框架',
];
// 生成文档嵌入
const docEmbeddings = await ollama.embed({ model: 'embeddinggemma', input: docs });
// 生成查询嵌入
const query = '什么是 AI';
const queryEmbed = await ollama.embed({ model: 'embeddinggemma', input: query });
// 计算相似度并排序
const results = docEmbeddings.embeddings
.map((emb, i) => ({
text: docs[i],
score: cosineSimilarity(queryEmbed.embeddings[0], emb),
}))
.sort((a, b) => b.score - a.score);
console.log('搜索结果:', results);
📤 响应示例
{
"model": "embeddinggemma",
"embeddings": [
[0.010071029, -0.0017594862, 0.05007221, 0.04692972, 0.054916814, ...]
],
"total_duration": 14143917,
"load_duration": 1019500,
"prompt_eval_count": 8
}
POST /api/show
查看指定模型的详细信息,包括参数设置、许可证、模板、模型能力、模型架构元数据等。
POST
http://localhost:11434/api/show
📥 请求参数
| 参数名 | 类型 | 必填 | 描述 |
| model | string | 必填 | 模型名称 |
| verbose | boolean | 可选 | 是否返回详细的 verbose 信息 |
📤 响应字段
| 字段名 | 类型 | 描述 |
| parameters | string | 模型参数设置文本 |
| license | string | 模型许可证 |
| modified_at | string | 最后修改时间 |
| details | object | 模型格式、家族、参数量等 |
| template | string | 提示模板 |
| capabilities | string[] | 支持的功能列表(如 "completion", "vision") |
| model_info | object | 详细的模型架构元数据 |
💻 代码示例
import Ollama from 'ollama';
const ollama = new Ollama();
// 查看模型信息
const info = await ollama.show({ model: 'gemma3', verbose: true });
console.log('能力:', info.capabilities); // ["completion", "vision"]
console.log('参数量:', info.details.parameter_size);
console.log('格式:', info.details.format);
console.log('上下文长度:', info.model_info?.['gemma3.context_length']);
// HTTP 查看模型详情
const response = await fetch('http://localhost:11434/api/show', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model: 'gemma3', verbose: true }),
});
const info = await response.json();
console.log('能力:', info.capabilities);
console.log('模型信息:', info.model_info);
POST /api/create
基于已有模型创建自定义模型。可以自定义系统提示词、模板、参数,也可以进行量化。
POST
http://localhost:11434/api/create
📥 请求参数
| 参数名 | 类型 | 必填 | 描述 |
| model | string | 必填 | 新模型的名称 |
| from | string | 可选 | 基础模型名称 |
| template | string | 可选 | 自定义提示模板 |
| system | string | 可选 | 嵌入模型的系统提示词 |
| license | string | string[] | 可选 | 许可证 |
| parameters | object | 可选 | 模型参数 |
| messages | array | 可选 | 用于模型的消息历史 |
| quantize | string | 可选 | 量化级别,如 "q4_K_M", "q8_0" |
| stream | boolean | 可选 | 是否流式返回创建进度(默认 true) |
💻 代码示例
import Ollama from 'ollama';
const ollama = new Ollama();
// 创建自定义模型
const stream = await ollama.create({
model: 'my-assistant',
from: 'gemma3',
system: '你是一个专业的中文编程助手。回答简洁明了,优先使用代码示例。',
stream: true,
});
for await (const chunk of stream) {
if (chunk.status) process.stdout.write(`状态: ${chunk.status}\n`);
}
// HTTP 创建模型
const response = await fetch('http://localhost:11434/api/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'emoji-bot',
from: 'gemma3',
system: '你只会用表情符号回答问题。',
stream: false,
}),
});
const result = await response.json();
console.log(result.status); // "success"
import Ollama from 'ollama';
const ollama = new Ollama();
// 创建量化版本模型(减少显存占用)
const stream = await ollama.create({
model: 'llama3:8b-q4',
from: 'llama3:8b-instruct-fp16',
quantize: 'q4_K_M', // 量化到 Q4_K_M 级别
stream: true,
});
for await (const chunk of stream) {
if (chunk.total && chunk.completed) {
const pct = ((chunk.completed / chunk.total) * 100).toFixed(1);
console.log(`量化进度: ${pct}%`);
}
}
POST /api/copy
复制一个已有模型到新名称。
POST
http://localhost:11434/api/copy
📥 请求参数
| 参数名 | 类型 | 必填 | 描述 |
| source | string | 必填 | 源模型名称 |
| destination | string | 必填 | 目标模型名称 |
💻 代码示例
import Ollama from 'ollama';
const ollama = new Ollama();
await ollama.copy({
source: 'gemma3',
destination: 'gemma3-backup',
});
console.log('复制完成');
await fetch('http://localhost:11434/api/copy', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
source: 'gemma3',
destination: 'gemma3-backup',
}),
});
console.log('复制完成'); // 成功返回 200
DELETE /api/delete
删除本地模型文件,释放磁盘空间。
DELETE
http://localhost:11434/api/delete
📥 请求参数
| 参数名 | 类型 | 必填 | 描述 |
| model | string | 必填 | 要删除的模型名称 |
⚠️ 警告:此操作不可恢复。模型文件将被永久删除。
💻 代码示例
import Ollama from 'ollama';
const ollama = new Ollama();
await ollama.delete({ model: 'gemma3-backup' });
console.log('模型已删除');
// HTTP 删除模型 (注意是 DELETE 方法)
await fetch('http://localhost:11434/api/delete', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model: 'gemma3-backup' }),
});
console.log('模型已删除');
POST /api/pull
从 Ollama 模型仓库下载模型到本地。支持流式进度显示。
POST
http://localhost:11434/api/pull
📥 请求参数
| 参数名 | 类型 | 必填 | 描述 |
| model | string | 必填 | 要下载的模型名称,如 "gemma3", "llama3:70b" |
| insecure | boolean | 可选 | 允许不安全连接下载 |
| stream | boolean | 可选 | 是否流式返回进度(默认 true) |
📤 响应字段
| 字段名 | 类型 | 描述 |
| status | string | 状态消息(如 "pulling manifest", "success") |
| digest | string | 当前层的内容摘要 |
| total | integer | 总字节数 |
| completed | integer | 已传输字节数 |
💻 代码示例
import Ollama from 'ollama';
const ollama = new Ollama();
// 下载模型并显示进度
const stream = await ollama.pull({ model: 'gemma3', stream: true });
for await (const chunk of stream) {
if (chunk.total && chunk.completed) {
const pct = ((chunk.completed / chunk.total) * 100).toFixed(1);
const doneMB = (chunk.completed / 1e6).toFixed(0);
const totalMB = (chunk.total / 1e6).toFixed(0);
process.stdout.write(`\r${chunk.status}: ${pct}% (${doneMB}/${totalMB} MB)`);
} else {
console.log(chunk.status);
}
}
console.log('\n下载完成!');
// HTTP 下载模型并跟踪进度
const response = await fetch('http://localhost:11434/api/pull', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model: 'gemma3' }),
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = 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 event = JSON.parse(line);
if (event.total) {
console.log(`${event.status}: ${((event.completed / event.total) * 100).toFixed(1)}%`);
}
}
}
POST /api/push
将本地自定义模型推送到 Ollama 模型仓库(需要先登录 ollama.com)。
POST
http://localhost:11434/api/push
📥 请求参数
| 参数名 | 类型 | 必填 | 描述 |
| model | string | 必填 | 要推送的模型名称(格式:username/model) |
| insecure | boolean | 可选 | 允许不安全连接 |
| stream | boolean | 可选 | 是否流式返回进度(默认 true) |
💻 代码示例
import Ollama from 'ollama';
const ollama = new Ollama();
// 推送模型到仓库
const stream = await ollama.push({
model: 'my-username/my-custom-model',
stream: true,
});
for await (const chunk of stream) {
if (chunk.total && chunk.completed) {
const pct = ((chunk.completed / chunk.total) * 100).toFixed(1);
process.stdout.write(`\r推送进度: ${pct}%`);
}
}
console.log('\n推送完成!');
// HTTP 推送模型
const response = await fetch('http://localhost:11434/api/push', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'my-username/my-model',
stream: false,
}),
});
const result = await response.json();
console.log(result.status); // "success"
GET /api/ps
列出当前正在内存中运行的模型。显示 VRAM 占用、上下文长度、过期时间等信息。
GET
http://localhost:11434/api/ps
📤 响应字段
| 字段名 | 类型 | 描述 |
| models[] | array | 正在运行的模型列表 |
| models[].name | string | 模型名称 |
| models[].size | integer | 模型大小(字节) |
| models[].digest | string | SHA256 摘要 |
| models[].details | object | 格式、家族等详细信息 |
| models[].expires_at | string | 模型自动卸载时间 |
| models[].size_vram | integer | VRAM 占用(字节) |
| models[].context_length | integer | 当前上下文长度 |
💻 代码示例
import Ollama from 'ollama';
const ollama = new Ollama();
// 列出正在运行的模型
const { models } = await ollama.ps();
if (models.length === 0) {
console.log('当前没有运行中的模型');
} else {
for (const m of models) {
console.log(`模型: ${m.name}`);
console.log(` VRAM: ${(m.size_vram / 1e9).toFixed(2)} GB`);
console.log(` 上下文: ${m.context_length} tokens`);
console.log(` 过期: ${m.expires_at}`);
}
}
// HTTP 列出运行中的模型
const response = await fetch('http://localhost:11434/api/ps');
const { models } = await response.json();
console.log(`运行中: ${models.length} 个模型`);
for (const m of models) {
console.log(` ${m.name} → VRAM: ${(m.size_vram / 1e9).toFixed(2)} GB`);
}
📤 响应示例
{
"models": [
{
"name": "gemma3:latest",
"model": "gemma3:latest",
"size": 6591830464,
"digest": "a2af6cc3eb7fa...",
"details": {
"parent_model": "",
"format": "gguf",
"family": "gemma3",
"families": ["gemma3"],
"parameter_size": "4.3B",
"quantization_level": "Q4_K_M"
},
"expires_at": "2026-05-18T16:47:07.93355+08:00",
"size_vram": 5333539264,
"context_length": 4096
}
]
}
GET /api/version
获取当前 Ollama 服务的版本号。
GET
http://localhost:11434/api/version
📤 响应字段
| 字段名 | 类型 | 描述 |
| version | string | Ollama 版本号 |
💻 代码示例
import Ollama from 'ollama';
const ollama = new Ollama();
// 获取版本
const { version } = await ollama.version();
console.log(`Ollama 版本: ${version}`); // 如 "0.12.6"
// HTTP 获取版本
const response = await fetch('http://localhost:11434/api/version');
const { version } = await response.json();
console.log(`Ollama 版本: ${version}`);
📤 响应示例