Ollama API 调用教程:Python / 前端直连本地模型,兼容 OpenAI 接口

接本地模型就两条路:Ollama 原生 API 和 OpenAI 兼容接口。后者更重要,因为用了它,OpenAI SDK 写的代码改一行 base_url 就能连本地。

先确认接口通了:

BASH
curl http://localhost:11434/api/tags
curl http://localhost:11434/api/chat -d '{"model":"qwen2.5:7b","messages":[{"role":"user","content":"你好"}]}'

有返回就对了。


流式输出

"stream": true 就能看到模型一个字一个字蹦的效果:

BASH
curl -N http://localhost:11434/api/chat -d '{"model":"qwen2.5:7b","messages":[{"role":"user","content":"写首诗"}],"stream":true}'

非流式就是等生成完了才一次性返回,长回答要等。日常用推荐流式。


OpenAI 兼容接口(重点)

Ollama 从 0.1.14 开始兼容 /v1/chat/completions。Python 用 openai 库几乎不用改代码:

PYTHON
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:11434/v1",
    api_key="ollama",  # 随便填,本地不需要
)

response = client.chat.completions.create(
    model="qwen2.5:7b",
    messages=[
        {"role": "system", "content": "你是一个有帮助的助手"},
        {"role": "user", "content": "用 Python 写一个快速排序"}
    ],
)
print(response.choices[0].message.content)

流式版也差不多,加 stream=True,遍历 chunk 就行。

查可用模型:client.models.list()


前端直连

不想搞后端的话,前端 fetch 直接调(Ollama 得绑定 0.0.0.0):

JAVASCRIPT
async function ask(question) {
  const res = await fetch('http://localhost:11434/api/chat', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({
      model: 'qwen2.5:7b',
      messages: [{role: 'user', content: question}],
      stream: false
    })
  });
  const data = await res.json();
  return data.message.content;
}

流式输出稍微复杂点,得用 response.body.getReader() 逐块读 NDJSON。


多轮对话

关键一点:历史消息要一起传过去,不然模型没有记忆。

BASH
curl http://localhost:11434/api/chat -d '{
  "model": "qwen2.5:7b",
  "messages": [
    {"role": "user", "content": "我叫小明"},
    {"role": "assistant", "content": "你好小明!"},
    {"role": "user", "content": "我叫什么?"}
  ]
}'

远程访问

默认只监 127.0.0.1,改 0.0.0.0:

BASH
sudo systemctl edit ollama
[Service]
Environment="OLLAMA_HOST=0.0.0.0"
sudo systemctl daemon-reload && sudo systemctl restart ollama

但别裸开。暴露到公网等于任何人都能调你的模型。用 Nginx 反代加 basic auth,或者 iptables 限制来源 IP。

NGINX
server {
    listen 443 ssl;
    server_name ai.yourdomain.com;
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    location / {
        auth_basic "Ollama API";
        auth_basic_user_file /etc/nginx/.htpasswd;
        proxy_pass http://127.0.0.1:11434;
        proxy_buffering off;
        proxy_cache off;
    }
}

密码文件:htpasswd -c /etc/nginx/.htpasswd youruser


常见报错

“model not found” — 模型名写错了,ollama list 看一下准确的。注意 qwen2.5:7bqwen2.5:7b-instruct 是不同的。

“connection refused” — Ollama 没启动。systemctl start ollama

前端跨域报错 — 设环境变量 OLLAMA_ORIGINS=* 或者指定域名。

发表评论