Ollama: REST API入门

REST API 是 Ollama 的万能接口——任何语言、任何框架,HTTP 一调即通。

⚠️ 注意:Ollama REST API无内置认证机制,任何能访问服务端口的人均可自由调用模型、查看已安装模型列表。在生产环境中,必须通过反向代理(如Nginx/Caddy)添加API Key认证,否则你的AI服务将面临被滥用、数据泄露和资源耗尽的风险。

📋 前置知识:需要先掌握以下内容

1. 你将学到


2. 一个 SaaS 创业者的真实故事

(1) 痛点:手动回复效率低下

Alice 创办了 GlobalShop 电商平台,客服团队 50 名客服每天处理 2,000+ 工单。平均每个工单耗时 8 分钟,客户等待时间超过 30 分钟。她需要用 API 将 LLM 集成到客服系统,实现自动回复草稿。

(2) 解法:REST API 一键生成回复

用 curl 调用 Ollama API,3 秒生成客服回复草稿,客服只需审核确认:

BASH
curl http://localhost:11434/api/chat -d '{
  "model": "qwen2.5",
  "messages": [{"role": "user", "content": "Refund for order #12345"}]
}'

⚠️ 警告: Ollama API 无内置认证机制,任何人能访问端口即可调用。生产环境必须通过反向代理(Nginx/Caddy)添加 API Key 认证,详见 Lesson 20 安全加固。

💡 提示: 流式 API(stream: true)适合聊天界面实时打字效果,非流式(stream: false)适合批处理和 API 后端集成。API 集成推荐非流式更简单。

ℹ️ 信息: Ollama 默认监听 http://127.0.0.1:11434,仅本机可访问。如需局域网访问需设置 OLLAMA_HOST 环境变量,但务必注意安全风险。

3. API 端点全解

(1) 两大核心端点对比

维度
用途 单轮文本生成 多轮对话
输入 + 数组
上下文 单次请求 支持对话历史
API 映射
适用场景 生成、补全、翻译 客服、助手、多轮推理
100%
sequenceDiagram
    participant C as Client
    participant O as Ollama Server
    C->>O: POST /api/chat {messages, model, stream}
    O-->>C: NDJSON {message, done: false}
    O-->>C: NDJSON {message, done: false}
    O-->>C: NDJSON {message, done: true, stats}

(2) 通用请求参数

参数 类型 默认值 说明
string 必填 模型名称
bool true 是否流式输出
object 推理参数(见下节)
string 输出格式:
string 模型驻留时间

▶ 示例 1: 单轮生成请求

BASH
# Non-streaming generate request
curl http://localhost:11434/api/generate -d '{
  "model": "llama3.2",
  "prompt": "Write a haiku about coding",
  "stream": false
}'

# Response (abbreviated)
# {
#   "model": "llama3.2",
#   "response": "Lines of logic flow,\nBug hides in the deep syntax—\nSemicolon found.",
#   "done": true,
#   "total_duration": 2500000000,
#   "eval_count": 18
# }

输出:

TEXT 📖 仅展示
{"status":"ok","data":{}}

▶ 示例 2: 多轮对话请求

BASH
# Chat with message history
curl http://localhost:11434/api/chat -d '{
  "model": "qwen2.5",
  "messages": [
    {"role": "system", "content": "You are a helpful customer service agent."},
    {"role": "user", "content": "I want to return my order #12345"},
    {"role": "assistant", "content": "I can help with that. May I ask the reason for the return?"},
    {"role": "user", "content": "The product arrived damaged"}
  ],
  "stream": false
}'

输出:

TEXT 📖 仅展示
{"status":"ok","data":{}}

4. 流式响应解析

💡 提示:流式(stream: true)和非流式(stream: false)各有适用场景:流式适合聊天界面的实时打字效果,用户无需等待完整响应即可看到内容;非流式适合批处理和API后端集成,直接获取完整JSON响应更便于程序解析。API集成推荐先用非流式验证逻辑,再切换流式优化体验。

(1) NDJSON 格式详解

流式响应使用 NDJSON(Newline Delimited JSON),每行一个 JSON 对象:

TEXT 📖 仅展示
{"model":"llama3.2","message":{"role":"assistant","content":"I"},"done":false}
{"model":"llama3.2","message":{"role":"assistant","content":" can"},"done":false}
{"model":"llama3.2","message":{"role":"assistant","content":" help"},"done":false}
{"model":"llama3.2","message":{"role":"assistant","content":""},"done":true,"total_duration":1500000000}
字段 说明
本 chunk 的文本片段
是否为最后一个 chunk
总推理耗时(纳秒)
生成 token 数
输入 token 数

(2) 流式 vs 非流式对比

维度 流式(stream: true) 非流式(stream: false)
用户体验 实时逐字输出 等待完整响应
首字延迟 极低(~200ms) 等全部生成完
实现复杂度 需解析 NDJSON 直接读 JSON
适用场景 聊天界面、实时展示 批处理、API 后端

▶ 示例 3: 解析流式响应

BASH
# Streaming request with real-time output
curl http://localhost:11434/api/chat -d '{
  "model": "llama3.2",
  "messages": [{"role": "user", "content": "Hello!"}],
  "stream": true
}' | while read -r line; do
    # Extract content field from each NDJSON line
    echo "$line" | python3 -c "
import sys, json
data = json.load(sys.stdin)
if data.get('message', {}).get('content'):
    print(data['message']['content'], end='', flush=True)
"
done

输出:

TEXT 📖 仅展示
{"status":"ok","data":{}}

5. 推理参数调优

(1) 核心参数表

参数 类型 范围 默认值 作用
float 0-2 0.8 控制随机性,低值更确定
float 0-1 0.9 核采样,限制候选 token 范围
int 1-100 40 只从 top-K 候选中采样
int 128-131072 2048 上下文窗口大小
float 1-2 1.1 重复惩罚系数
int 任意 -1 随机种子(-1=随机)

(2) 参数调优场景对照

场景 temperature top_p 说明
代码生成 0.1-0.3 0.9 需要确定性和准确性
客服回复 0.3-0.5 0.9 稳定但允许适度变化
创意写作 0.7-1.0 0.95 需要多样性和创造力
数据分析 0.1-0.2 0.9 必须精确,不允许幻觉
⚠️ 警告: num_ctx 直接影响内存占用。8B 模型 num_ctx=8192 约需 6GB VRAM,num_ctx=32768 约需 12GB VRAM。按需设置,不要盲目调大。

▶ 示例 4: 参数调优对比

BASH
# Low temperature: deterministic output
curl http://localhost:11434/api/generate -d '{
  "model": "llama3.2",
  "prompt": "What is 2+2?",
  "stream": false,
  "options": {"temperature": 0.1}
}'
# Response: "2+2 equals 4."

# High temperature: creative output
curl http://localhost:11434/api/generate -d '{
  "model": "llama3.2",
  "prompt": "What is 2+2?",
  "stream": false,
  "options": {"temperature": 1.5}
}'
# Response: "In the realm of mathematics, 2+2 opens the door to 4..."

输出:

TEXT 📖 仅展示
{"status":"ok","data":{}}

▶ 示例 5: JSON 格式输出

BASH
# Force JSON output format
curl http://localhost:11434/api/chat -d '{
  "model": "llama3.2",
  "messages": [
    {"role": "system", "content": "You are a product catalog API. Return JSON only."},
    {"role": "user", "content": "List 3 laptops under $500"}
  ],
  "format": "json",
  "stream": false,
  "options": {"temperature": 0.3}
}'

# Response is valid JSON
# {"products":[{"name":"Acer Aspire 5","price":449,"spec":"8GB RAM, 256GB SSD"},...]}

输出:

TEXT 📖 仅展示
{"status":"ok","data":{}}

6. 综合示例:SupportBot 客服 API 原型

💡 提示: 生产环境调用 API 时,务必设置 keep_alive 参数(如 "keep_alive": "5m"),避免模型频繁加载/卸载导致响应延迟。

BASH
#!/bin/bash
# ============================================
# Comprehensive: SupportBot API prototype
# Multi-turn customer service via REST API
# ============================================

API="http://localhost:11434/api/chat"
MODEL="qwen2.5"

# Function: Send a chat message and extract response
chat() {
    local system_prompt="$1"
    local user_msg="$2"
    local temp="${3:-0.4}"

    curl -s "$API" -d "$(cat <<EOF
{
  "model": "$MODEL",
  "messages": [
    {"role": "system", "content": "$system_prompt"},
    {"role": "user", "content": "$user_msg"}
  ],
  "stream": false,
  "options": {"temperature": $temp, "num_ctx": 4096}
}
EOF
)" | python3 -c "import sys,json; print(json.load(sys.stdin)['message']['content'])"
}

# Customer service system prompt
SYSTEM="You are SupportBot, a customer service agent for an e-commerce store. Be polite, concise, and helpful. If you cannot answer, say 'Let me connect you with a human agent.'"

# Simulate customer interactions
echo "=== Query 1: Order Status ==="
chat "$SYSTEM" "Where is my order #88765? It has been 5 days."

echo ""
echo "=== Query 2: Return Request ==="
chat "$SYSTEM" "I received a damaged item. Order #12345. I want a refund."

echo ""
echo "=== Query 3: Product Question ==="
chat "$SYSTEM" "Does the wireless headphone support Bluetooth 5.3?"

echo ""
echo "=== Benchmark ==="
time chat "$SYSTEM" "Hello" > /dev/null
💻 输出:

TEXT 📖 仅展示
=== Query 1: Order Status ===
I'd be happy to check on your order #88765. Based on our tracking system, your order is currently in transit and expected to arrive within 2-3 business days. You can track it at track.example.com/88765.

=== Query 2: Return Request ===
I'm sorry to hear about the damaged item. For order #12345, I've initiated a return request. You'll receive a prepaid shipping label via email within 24 hours. Once we receive the item, a full refund will be processed within 3-5 business days.

=== Query 3: Product Question ===
Yes, our wireless headphones support Bluetooth 5.3 with a range of up to 15 meters. They also feature active noise cancellation and 30-hour battery life.

❓ 常见问题

Q 为什么 curl 请求报 connection refused?
A Ollama 服务未运行。执行 或确认 systemd 服务已启动:。
Q stream: true 和 stream: false 该选哪个?
A 前端聊天界面用 实现实时打字效果。后端批处理用 直接获取完整响应。API 集成推荐非流式更简单。
Q 如何限制输出长度?
A 设置 参数,如 限制最多生成 200 tokens。注意这是生成 token 数,不是字符数。
Q format: json 能保证输出一定是合法 JSON 吗?
A 大多数情况下可以,但不保证 100%。建议在应用层加 JSON 校验,解析失败时重试或降级为文本处理。
Q 多轮对话如何保持上下文?
A 客户端需自行维护 数组,每次请求将完整对话历史发送。Ollama 服务端不存储会话状态。
Q API 调用有并发限制吗?
A 默认一次只处理一个请求。设置 环境变量可增加并发数,但需更多 VRAM。详见 Lesson 19 性能调优。

📖 小节


📝 作业

  1. 基础题(难度⭐):用 curl 调用 生成一段产品描述,分别尝试 和 观察区别。
  2. 进阶题(难度⭐⭐):用 实现一个 3 轮对话,手动维护 messages 数组,每轮输出完整回复。
  3. 挑战题(难度⭐⭐⭐):编写一个 Shell 脚本,模拟 SupportBot 客服流程——接收问题、调用 API、以 JSON 格式返回分类结果(意图+回复),支持流式实时输出。
Web-Tutorial.com

Web-Tutorial 技术团队

由多位开发者共同维护的编程教程平台。每篇教程由对应领域的开发者编写和审核,确保内容准确可靠。如发现任何问题,欢迎向我们反馈。

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏