REST 与 OpenAI 兼容 API
Ollama 装好后,本机默认提供两套 HTTP:
API 不严格按版本号演进,但承诺尽量向后兼容;弃用会写在 Release Notes。
原生:生成 /api/generate
官方示例:
curl http://localhost:11434/api/generate -d '{"model": "gemma4", "prompt": "Why is the sky blue?"}'
一次拿完整结果(关闭流式):
curl http://localhost:11434/api/generate -d '{
"model": "gemma4",
"prompt": "Why is the sky blue?",
"stream": false
}'
常用字段:system、options(如 temperature、num_ctx)、keep_alive(0 表示用完即卸)。默认流式返回 NDJSON,每行一个 JSON,最后一行 done: true。
Windows PowerShell(官方 Windows 页用 Invoke-WebRequest;下面等价且更好解析):
Invoke-RestMethod -Method Post -Uri "http://localhost:11434/api/generate" `
-ContentType "application/json" `
-Body '{"model":"gemma4","prompt":"Why is the sky blue?","stream":false}'
若坚持 curl,请用 curl.exe,避免 curl 被解析成 Invoke-WebRequest。
原生:对话 /api/chat
多轮要把历史放进 messages:
curl http://localhost:11434/api/chat -d "{
\"model\": \"gemma4\",
\"messages\": [
{\"role\": \"system\", \"content\": \"用简洁中文回答。\"},
{\"role\": \"user\", \"content\": \"天空为什么是蓝的?\"}
],
\"stream\": false
}"
PowerShell 用单引号包 JSON 更省转义:
Invoke-RestMethod -Method Post -Uri "http://localhost:11434/api/chat" `
-ContentType "application/json" `
-Body '{"model":"gemma4","stream":false,"messages":[{"role":"user","content":"Why is the sky blue?"}]}'
成功时 message.content 是助手文本。视觉模型可在消息里带 images(Base64),见官方 generate / chat。
原生:嵌入 /api/embed
curl http://localhost:11434/api/embed -d '{
"model": "embeddinggemma",
"input": "Why is the sky blue?"
}'
input 可以是字符串或字符串数组。先 ollama pull 嵌入模型,细节见 Embeddings。
管理类端点(常用)
OpenAI 兼容:/v1/chat/completions
现有 OpenAI SDK 只需改 base URL。官方文档基址为 http://localhost:11434/v1/,api_key 必填但本机可忽略,习惯填 ollama。
curl -X POST http://localhost:11434/v1/chat/completions \
-H "Content-Type: application/json" \
-d "{\"model\":\"gemma4\",\"messages\":[{\"role\":\"user\",\"content\":\"Say this is a test\"}]}"
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1/", api_key="ollama")
print(client.chat.completions.create(
model="gemma4",
messages=[{"role": "user", "content": "Say this is a test"}],
).choices[0].message.content)
兼容层还支持 /v1/completions、/v1/embeddings、/v1/models,以及较新的 /v1/responses(需足够新的 Ollama)。已支持流式、JSON mode、视觉(Base64)、tools、思考力度等;不支持 logprobs、远程图片 URL、tool_choice 等字段,完整勾选表见 OpenAI compatibility。
OpenAI 请求没有原生的 num_ctx。要改上下文:写 Modelfile 设 PARAMETER num_ctx,再 ollama create 出新名字。
云端 API
Cloud 有两种用法:
- 本机已 signin:
ollama run gemma4:cloud 或对本机 11434 指定 :cloud 模型,由本机服务转发。
- 直连云:
https://ollama.com/api,设置 OLLAMA_API_KEY,请求头 Authorization: Bearer ...。
curl https://ollama.com/api/chat \
-H "Authorization: Bearer $OLLAMA_API_KEY" \
-d '{"model":"gemma4","messages":[{"role":"user","content":"Why is the sky blue?"}],"stream":false}'
列出云上可见模型:curl https://ollama.com/api/tags(认证要求以当前文档为准)。
安全备忘
- 默认只监听本机。绑定
0.0.0.0 前先做网络隔离或反向代理鉴权。
- 兼容层的
api_key 不是本机访问控制;不要把它当成防火墙。
- 云 Key 只放环境变量,不要写进仓库。
下一步