Chapter 05

REST API 完整指南

Ollama 在本地启动一个 HTTP 服务,提供完整的 REST API,让任何语言的程序都能调用本地大模型。本章系统讲解所有 API 端点,从流式生成到向量嵌入,附完整的 curl 与 Python 示例。

本地服务架构

Ollama 安装后会在后台运行一个 HTTP 服务,默认监听 127.0.0.1:11434(只允许本机访问)。所有 CLI 命令底层都是调用这个 API。

Ollama API 路由总览(端口 11434) POST /api/generate ← 文本生成(单轮,支持流式) POST /api/chat ← 多轮对话(支持流式) POST /api/embeddings ← 生成向量嵌入 GET /api/tags ← 列出已安装模型 POST /api/show ← 查看模型详情 POST /api/pull ← 下载模型(支持进度流) POST /api/push ← 上传模型到库 POST /api/copy ← 复制模型 DELETE /api/delete ← 删除模型 POST /api/create ← 从 Modelfile 创建模型 GET /api/ps ← 查看当前运行中的模型 POST /api/blobs/:digest ← 检查/创建 blob 文件 GET / ← 健康检查(返回 "Ollama is running")

/api/generate — 文本生成

最基础的生成接口,适合单轮 Prompt 场景(不维护对话历史):

# 基础请求(非流式,等待完整响应)
curl http://localhost:11434/api/generate \
  -d '{
    "model": "llama3.2",
    "prompt": "用一句话解释什么是机器学习",
    "stream": false
  }'

# 响应示例:
# {
#   "model": "llama3.2",
#   "created_at": "2025-04-09T08:00:00Z",
#   "response": "机器学习是让计算机通过数据自动学习规律...",
#   "done": true,
#   "context": [1, 2, 3, ...],  ← 编码后的对话上下文
#   "total_duration": 1234567890,
#   "eval_count": 42,
#   "eval_duration": 1000000000
# }

# 流式请求(实时输出,每个 token 一条 JSON)
curl http://localhost:11434/api/generate \
  -d '{
    "model": "llama3.2",
    "prompt": "写一首关于代码的短诗",
    "stream": true
  }'
# 每行一个 JSON:{"model":"llama3.2","response":"代","done":false}
#              {"model":"llama3.2","response":"码","done":false}
#              {"model":"llama3.2","response":"","done":true,...}

# 携带生成参数
curl http://localhost:11434/api/generate \
  -d '{
    "model": "qwen2.5:7b",
    "prompt": "用 Python 实现二分查找",
    "stream": false,
    "options": {
      "temperature": 0.2,
      "num_ctx": 4096,
      "top_p": 0.9
    }
  }'

# 携带系统提示词
curl http://localhost:11434/api/generate \
  -d '{
    "model": "llama3.2",
    "system": "你是一个简洁的助手,回答不超过50字",
    "prompt": "什么是 Docker",
    "stream": false
  }'

/api/chat — 多轮对话

/api/chat 支持传入完整的对话历史,适合需要上下文的多轮交互场景:

# 多轮对话请求结构
curl http://localhost:11434/api/chat \
  -d '{
    "model": "llama3.2",
    "messages": [
      {
        "role": "system",
        "content": "你是一个 Python 专家助手"
      },
      {
        "role": "user",
        "content": "什么是列表推导式?"
      },
      {
        "role": "assistant",
        "content": "列表推导式是 Python 中创建列表的简洁语法..."
      },
      {
        "role": "user",
        "content": "给一个实际的例子"
      }
    ],
    "stream": false
  }'

# 响应结构:
# {
#   "model": "llama3.2",
#   "message": {
#     "role": "assistant",
#     "content": "好的,以下是一个实际例子..."
#   },
#   "done": true
# }

下面用 Python 实现一个维护完整对话历史的多轮对话函数:

import requests
import json

def chat_with_ollama(
    model: str = "llama3.2",
    system: str = "你是一个有帮助的助手",
    base_url: str = "http://localhost:11434"
):
    """
    维护对话历史的多轮对话函数。
    按 Ctrl+C 或输入 /quit 退出。
    """
    messages = [
        {"role": "system", "content": system}
    ]

    print(f"\n[{model}] 对话已启动,输入 /quit 退出\n")

    while True:
        user_input = input("你: ").strip()
        if not user_input:
            continue
        if user_input == "/quit":
            print("再见!")
            break
        if user_input == "/clear":
            messages = [messages[0]]  # 保留 system,清除历史
            print("[对话历史已清除]")
            continue

        messages.append({"role": "user", "content": user_input})

        # 流式请求
        response = requests.post(
            f"{base_url}/api/chat",
            json={
                "model": model,
                "messages": messages,
                "stream": True
            },
            stream=True
        )

        print("AI: ", end="", flush=True)
        full_response = ""

        for line in response.iter_lines():
            if line:
                chunk = json.loads(line)
                if not chunk.get("done"):
                    token = chunk["message"]["content"]
                    print(token, end="", flush=True)
                    full_response += token

        print()  # 换行
        # 将 AI 回复追加到历史(维护上下文)
        messages.append({"role": "assistant", "content": full_response})

# 运行
if __name__ == "__main__":
    chat_with_ollama(model="qwen2.5:7b", system="你是一个 Python 专家")

/api/embeddings — 向量嵌入

向量嵌入是 RAG 系统的基础,将文本转换为高维向量表示:

# 首先拉取嵌入专用模型
ollama pull nomic-embed-text    # 推荐,270MB,768维
ollama pull mxbai-embed-large   # 更高质量,670MB,1024维

# 生成单条文本的向量嵌入
curl http://localhost:11434/api/embeddings \
  -d '{
    "model": "nomic-embed-text",
    "prompt": "Python 是一门高级编程语言"
  }'

# 响应:
# {
#   "embedding": [0.0123, -0.0456, 0.0789, ...]  ← 768维浮点数组
# }
import requests
import numpy as np

def get_embedding(text: str, model: str = "nomic-embed-text") -> list[float]:
    """将文本转换为向量嵌入。"""
    response = requests.post(
        "http://localhost:11434/api/embeddings",
        json={"model": model, "prompt": text}
    )
    return response.json()["embedding"]

def cosine_similarity(v1: list, v2: list) -> float:
    """计算两个向量的余弦相似度(-1 到 1,越接近 1 越相似)。"""
    a, b = np.array(v1), np.array(v2)
    return float(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)))

# 语义相似度对比示例
texts = [
    "Python 是一门高级编程语言",
    "Python 非常适合数据科学",     # 语义相近
    "今天天气很好,阳光明媚",       # 语义不同
]

base_embedding = get_embedding(texts[0])
for text in texts[1:]:
    emb = get_embedding(text)
    sim = cosine_similarity(base_embedding, emb)
    print(f"相似度 {sim:.4f}: {text}")

# 输出示例:
# 相似度 0.8934: Python 非常适合数据科学
# 相似度 0.1245: 今天天气很好,阳光明媚

管理类 API 接口

# 查看已安装模型列表
curl http://localhost:11434/api/tags

# 查看模型详情
curl http://localhost:11434/api/show \
  -d '{"name": "llama3.2"}'

# 通过 API 下载模型(显示进度)
curl http://localhost:11434/api/pull \
  -d '{"name": "phi4:mini", "stream": true}'

# 删除模型
curl -X DELETE http://localhost:11434/api/delete \
  -d '{"name": "mistral:7b"}'

# 查看当前运行中(已加载到内存)的模型
curl http://localhost:11434/api/ps

# 响应示例:
# {"models": [{"name":"qwen2.5:7b","model":"qwen2.5:7b",
#   "size":5137000000,"digest":"sha256:...","expires_at":"..."}]}

# 健康检查
curl http://localhost:11434/
# 返回:Ollama is running
OpenAI API 格式兼容 Ollama 提供了兼容 OpenAI 格式的端点,位于 /v1/ 路径:POST /v1/chat/completionsPOST /v1/embeddingsGET /v1/models。这意味着任何使用 OpenAI SDK 的代码,只需修改 base_url="http://localhost:11434/v1"api_key="ollama"(任意值)即可无缝切换到本地模型,无需修改其他代码。
# 使用 OpenAI Python SDK 调用 Ollama(零改动切换)
from openai import OpenAI

# 只需修改 base_url,其余代码与调用 ChatGPT 完全相同
client = OpenAI(
    base_url="http://localhost:11434/v1",
    api_key="ollama"  # 随意填写,本地不校验
)

response = client.chat.completions.create(
    model="qwen2.5:7b",
    messages=[{"role": "user", "content": "你好!"}]
)
print(response.choices[0].message.content)
本章小结 Ollama REST API 核心端点:/api/generate 单轮生成,/api/chat 多轮对话,/api/embeddings 向量嵌入,/api/tags 模型列表。所有端点均支持 JSON 请求体,生成类接口支持 stream: true 流式输出。此外,/v1/ 路径提供 OpenAI API 格式兼容,现有 ChatGPT 代码只需改 base_url 即可使用本地模型。下一章学习 Python 官方库的深度集成。