diff --git a/docs/ollama-api-docs-20260518.html b/docs/ollama-api-docs-20260518.html new file mode 100644 index 0000000..d87cad9 --- /dev/null +++ b/docs/ollama-api-docs-20260518.html @@ -0,0 +1,1876 @@ + + + + + + Ollama API 完整接口文档 | 20260518 + + + + + + + + +
+ + +
+

Ollama API 完整接口文档

+

基于官方文档 docs.ollama.com 全面解析。覆盖所有 HTTP API 端点,每个接口均提供 JavaScript SDKHTTP Fetch 两种调用方式的详细示例代码。

+
+ 支持模型: gpt-oss · Gemma 3 · DeepSeek-R1 · Qwen3 等 + 文档日期: 2026-05-18 + 本地: http://localhost:11434 · 云端: https://ollama.com/api +
+
+ +
+ + +
+

📋 接口总览

+

Ollama 提供 RESTful HTTP API,默认监听在 http://localhost:11434。所有请求与响应均使用 JSON 格式。流式响应使用 NDJSON(newline-delimited JSON)。云端模型可通过 https://ollama.com/api 访问相同的 API。

+ + + + + + + + + + + + + + + + + + + +
方法接口路径描述
POST/api/generate生成文本响应(补全模式)
POST/api/chat对话模式生成消息
POST/api/embed生成文本向量嵌入
GET/api/tags列出所有本地模型
POST/api/show查看模型详细信息
POST/api/create创建自定义模型
POST/api/copy复制模型
DELETE/api/delete删除模型
POST/api/pull从仓库拉取模型
POST/api/push推送模型到仓库
GET/api/ps列出正在运行的模型
GET/api/version获取 Ollama 版本
+
+ + +
+

⚡ 快速开始

+

在开始之前,确保 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 等接口。

+ + + + + + + + + + + + + +
参数名类型描述
seedinteger随机种子,用于可复现的输出
temperaturefloat控制随机性,值越高越随机(默认约 0.8)
top_kinteger限制下一个 token 从概率最高的 K 个中选取
top_pfloat核采样的累积概率阈值
min_pfloattoken 选择的最低概率阈值
stopstring | string[]停止序列,遇到时终止生成
num_ctxinteger上下文窗口大小(token 数)
num_predictinteger最大生成 token 数
+
+ +
+ + +
+

POST /api/generate

+

生成文本响应(补全模式)。支持流式/非流式、结构化输出、图像输入、Thinking 模式、logprobs 等功能。适用于 gpt-oss、Gemma 3、DeepSeek-R1、Qwen3 等模型。

+ +
+ POST + http://localhost:11434/api/generate +
+ +
📥 请求参数
+ + + + + + + + + + + + + + + + + +
参数名类型必填描述
modelstring必填模型名称,如 "gemma3"
promptstring可选提示文本。省略时仅加载模型
suffixstring可选中间填充模式 (FIM) 中,出现在 prompt 后、response 前的文本
imagesstring[]可选Base64 编码的图像数组(多模态模型)
formatstring | object可选结构化输出格式,可传 "json" 或 JSON Schema 对象
systemstring可选系统提示词
streamboolean可选是否流式返回(默认 true)
thinkboolean | string可选启用 Thinking 模式。可传 true/false 或 "high"/"medium"/"low"
rawboolean可选跳过模板处理,返回模型原始输出
keep_alivestring | number可选模型保持加载时间,如 "5m"。传 0 立即卸载
optionsobject可选模型参数(见上方 Options 表格)
logprobsboolean可选是否返回 token 的对数概率
top_logprobsinteger可选每个位置返回的候选 token 数(需 logprobs=true)
+ +
📤 响应字段
+ + + + + + + + + + + + + + + + +
字段名类型描述
modelstring模型名称
created_atstringISO 8601 时间戳
responsestring模型生成的文本
thinkingstringThinking 模式下的思考输出
doneboolean是否生成完毕
done_reasonstring停止原因(如 "stop")
total_durationinteger总耗时(纳秒)
load_durationinteger模型加载耗时(纳秒)
prompt_eval_countinteger输入 token 数
prompt_eval_durationintegerPrompt 评估耗时(纳秒)
eval_countinteger输出 token 数
eval_durationinteger生成 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 +
+ +
📥 请求参数
+ + + + + + + + + + + + + + + + + + +
参数名类型必填描述
modelstring必填模型名称
messagesarray必填对话历史消息数组
messages[].rolestring必填角色: "system" | "user" | "assistant" | "tool"
messages[].contentstring必填消息文本
messages[].imagesstring[]可选Base64 编码的图像数组
messages[].tool_callsarray可选工具调用请求
toolsarray可选可用的函数工具列表
formatstring | object可选结构化输出格式
streamboolean可选是否流式返回(默认 true)
thinkboolean | string可选Thinking 模式
keep_alivestring | number可选模型保持加载时间
optionsobject可选模型参数
logprobsboolean可选是否返回对数概率
top_logprobsinteger可选每位置候选 token 数
+ +
📤 响应字段
+ + + + + + + + + + + + + + + + +
字段名类型描述
modelstring模型名称
created_atstringISO 8601 时间戳
messageobject包含 role, content, thinking, tool_calls 等
message.rolestring始终为 "assistant"
message.contentstring助手回复文本
message.thinkingstringThinking 模式的思考输出
message.tool_callsarray模型请求的工具调用
message.imagesstring[]Base64 编码的图像(部分模型支持)
doneboolean是否完成
done_reasonstring停止原因
total_durationinteger总耗时(纳秒)
eval_countinteger输出 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 +
+ +
📥 请求参数
+ + + + + + + + + + +
参数名类型必填描述
modelstring必填嵌入模型名称,如 "embeddinggemma"
inputstring | string[]必填待编码的文本或文本数组
truncateboolean可选是否截断超长输入(默认 true)
dimensionsinteger可选生成的嵌入维度数
keep_alivestring可选模型保持加载时间
optionsobject可选模型参数
+ +
📤 响应字段
+ + + + + + + + + +
字段名类型描述
modelstring使用的模型
embeddingsnumber[][]向量嵌入数组
total_durationinteger总耗时(纳秒)
load_durationinteger模型加载耗时(纳秒)
prompt_eval_countinteger输入 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
+}
+
+
+ +
+ + +
+

GET /api/tags

+

列出所有已下载到本地的模型及其详细信息(名称、大小、格式、量化级别等)。

+ +
+ GET + http://localhost:11434/api/tags +
+ +
📤 响应字段
+ + + + + + + + + + + + + +
字段名类型描述
models[]array模型列表
models[].namestring模型名称
models[].modelstring模型标识
models[].remote_modelstring上游模型名称(远程模型时)
models[].remote_hoststring上游 Ollama 主机 URL(远程模型时)
models[].modified_atstring最后修改时间
models[].sizeinteger磁盘大小(字节)
models[].digeststringSHA256 摘要
models[].detailsobject格式、家族、参数量、量化级别
+ +
💻 代码示例
+
+ + +
+
+
+
import Ollama from 'ollama';
+const ollama = new Ollama();
+
+// 列出所有本地模型
+const { models } = await ollama.list();
+
+console.log(`共 ${models.length} 个模型:\n`);
+for (const m of models) {
+  const sizeGB = (m.size / 1e9).toFixed(2);
+  console.log(`  ${m.name}  [${sizeGB} GB]  ${m.details.parameter_size}  ${m.details.quantization_level}`);
+}
+
+
+
// HTTP 列出模型
+const response = await fetch('http://localhost:11434/api/tags');
+const { models } = await response.json();
+
+for (const m of models) {
+  console.log(`${m.name} - ${(m.size / 1e9).toFixed(2)} GB`);
+}
+
+
+ +
📤 响应示例
+
+
{
+  "models": [
+    {
+      "name": "gemma3:latest",
+      "model": "gemma3:latest",
+      "modified_at": "2026-05-17T23:34:03.409490317+08:00",
+      "size": 3338801804,
+      "digest": "a2af6cc3eb7fa8be8504abaf9b04e88f17a119ec...",
+      "details": {
+        "format": "gguf",
+        "family": "gemma",
+        "families": ["gemma"],
+        "parameter_size": "4.3B",
+        "quantization_level": "Q4_K_M"
+      }
+    }
+  ]
+}
+
+
+ +
+ + +
+

POST /api/show

+

查看指定模型的详细信息,包括参数设置、许可证、模板、模型能力、模型架构元数据等。

+ +
+ POST + http://localhost:11434/api/show +
+ +
📥 请求参数
+ + + + + + +
参数名类型必填描述
modelstring必填模型名称
verboseboolean可选是否返回详细的 verbose 信息
+ +
📤 响应字段
+ + + + + + + + + + + +
字段名类型描述
parametersstring模型参数设置文本
licensestring模型许可证
modified_atstring最后修改时间
detailsobject模型格式、家族、参数量等
templatestring提示模板
capabilitiesstring[]支持的功能列表(如 "completion", "vision")
model_infoobject详细的模型架构元数据
+ +
💻 代码示例
+
+ + +
+
+
+
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 +
+ +
📥 请求参数
+ + + + + + + + + + + + + +
参数名类型必填描述
modelstring必填新模型的名称
fromstring可选基础模型名称
templatestring可选自定义提示模板
systemstring可选嵌入模型的系统提示词
licensestring | string[]可选许可证
parametersobject可选模型参数
messagesarray可选用于模型的消息历史
quantizestring可选量化级别,如 "q4_K_M", "q8_0"
streamboolean可选是否流式返回创建进度(默认 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 +
+ +
📥 请求参数
+ + + + + + +
参数名类型必填描述
sourcestring必填源模型名称
destinationstring必填目标模型名称
+ +
💻 代码示例
+
+ + +
+
+
+
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 +
+ +
📥 请求参数
+ + + + + +
参数名类型必填描述
modelstring必填要删除的模型名称
+ +
⚠️ 警告:此操作不可恢复。模型文件将被永久删除。
+ +
💻 代码示例
+
+ + +
+
+
+
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 +
+ +
📥 请求参数
+ + + + + + + +
参数名类型必填描述
modelstring必填要下载的模型名称,如 "gemma3", "llama3:70b"
insecureboolean可选允许不安全连接下载
streamboolean可选是否流式返回进度(默认 true)
+ +
📤 响应字段
+ + + + + + + + +
字段名类型描述
statusstring状态消息(如 "pulling manifest", "success")
digeststring当前层的内容摘要
totalinteger总字节数
completedinteger已传输字节数
+ +
💻 代码示例
+
+ + +
+
+
+
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 +
+ +
📥 请求参数
+ + + + + + + +
参数名类型必填描述
modelstring必填要推送的模型名称(格式:username/model)
insecureboolean可选允许不安全连接
streamboolean可选是否流式返回进度(默认 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[].namestring模型名称
models[].sizeinteger模型大小(字节)
models[].digeststringSHA256 摘要
models[].detailsobject格式、家族等详细信息
models[].expires_atstring模型自动卸载时间
models[].size_vramintegerVRAM 占用(字节)
models[].context_lengthinteger当前上下文长度
+ +
💻 代码示例
+
+ + +
+
+
+
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 +
+ +
📤 响应字段
+ + + + + +
字段名类型描述
versionstringOllama 版本号
+ +
💻 代码示例
+
+ + +
+
+
+
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}`);
+
+
+ +
📤 响应示例
+
+
{
+  "version": "0.12.6"
+}
+
+
+ + +
+

📄 本文档基于 docs.ollama.com 官方文档生成

+

支持模型: gpt-oss · Gemma 3 · DeepSeek-R1 · Qwen3 · 文档日期: 2026-05-18

+

JavaScript SDK: github.com/ollama/ollama-js · Python SDK: github.com/ollama/ollama-python

+
+
+
+ + + + +