Ollama Chat 端点

2026-10-29 19:01 更新

POST /api/chat 是多轮对话的标准入口。相比 /api/generate 的单段提示词,它接收 messages 数组,能表达完整的角色与历史,也是唯一支持工具调用的端点。

版本基线 v0.40.12,官方 docs.ollama.com/api/chat。

一、最小调用

curl http://localhost:11434/api/chat -d '{
  "model": "gemma4",
  "messages": [
    { "role": "user", "content": "why is the sky blue?" }
  ]
}'

返回:

{
  "model": "gemma4",
  "created_at": "2025-10-17T23:14:07.414671Z",
  "message": {
    "role": "assistant",
    "content": "Hello! How can I help you today?"
  },
  "done": true,
  "done_reason": "stop",
  "total_duration": 174560334,
  "load_duration": 101397084,
  "prompt_eval_count": 11,
  "prompt_eval_duration": 13074791,
  "eval_count": 18,
  "eval_duration": 52479709
}

答案在 message.content——注意不是 response,这是和 generate 端点的关键差别。

二、请求字段

字段 类型 必填 说明
model string 是 模型名
messages object[] 是 对话历史,每条含 role 和 content
tools object[] 可供模型调用的函数工具
format enum | object json 或 JSON schema
options object 运行时参数
stream boolean 默认 true
think boolean | string 思考控制,取值见 /api/show
keep_alive string | number 模型驻留时长
logprobs boolean 返回对数概率
top_logprobs integer 每个位置返回的候选数

messages 的结构

[
  {"role": "system",    "content": "你是一名严谨的技术助手"},
  {"role": "user",      "content": "什么是 KV 缓存?"},
  {"role": "assistant", "content": "KV 缓存是……"},
  {"role": "user",      "content": "那它占多少显存?"}
]

三个角色:system(系统提示,通常放第一条)、user、assistant(历史回复)。

多轮对话必须自己维护这个数组——每次请求把完整历史带上,服务端不保存会话状态。这也是 prompt_eval_cached_count 会有值的原因:历史前缀被缓存复用了。

三、工具调用(最实用的能力)

先定义工具:

{
  "model": "qwen3",
  "messages": [{"role": "user", "content": "北京今天天气怎么样?"}],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "获取指定城市的当前天气",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {"type": "string", "description": "城市名"}
          },
          "required": ["city"]
        }
      }
    }
  ]
}

模型不会直接回答,而是返回一个工具调用:

{
  "message": {
    "role": "assistant",
    "content": "",
    "tool_calls": [
      {
        "function": {
          "name": "get_weather",
          "arguments": { "city": "北京" }
        }
      }
    ]
  },
  "done": true,
  "done_reason": "stop"
}

接着把你的执行结果作为 tool 角色消息追加进去,再请求一次:

{
  "model": "qwen3",
  "messages": [
    {"role": "user", "content": "北京今天天气怎么样?"},
    {"role": "assistant", "content": "", "tool_calls": [ /* 上一步返回的 */ ]},
    {"role": "tool", "content": "{\"temp\": 18, \"condition\": \"晴\"}"}
  ],
  "tools": [ /* 同一份工具定义 */ ]
}

模型会基于工具结果生成最终答案。

三个容易出错的点:

  1. tools 每次请求都要带,不是只在第一次带
  2. tool_calls 的 arguments 可能是对象也可能需要序列化,取决于客户端库版本,处理前先打印确认
  3. tool 消息要和 tool_calls 一一对应,数量或顺序错了模型会混乱

完整的工具调用机制见 3.8 Ollama 工具调用。

四、响应字段

字段 说明
model 使用的模型
created_at ISO 8601 时间戳
message 回复对象,含 role、content、可能的 tool_calls 和 thinking
done 是否结束
done_reason 停止原因
total_duration / load_duration 耗时(纳秒)
prompt_eval_count / prompt_eval_cached_count 输入 token 数 / 缓存命中数
prompt_eval_duration / eval_count / eval_duration 其余耗时与输出 token
logprobs 开启时的概率信息

五、流式对话

默认流式,每个 chunk 的 message.content 是增量:

import json, requests

history = [{"role": "user", "content": "讲个短笑话"}]

with requests.post("http://localhost:11434/api/chat", json={
    "model": "gemma4",
    "messages": history,
}, stream=True) as r:
    parts = []
    for line in r.iter_lines():
        if not line:
            continue
        c = json.loads(line)
        if "error" in c:
            raise RuntimeError(c["error"])
        parts.append(c["message"]["content"])
        print(c["message"]["content"], end="", flush=True)
        if c.get("done"):
            break

## 把回复追加进历史,下一轮带上
history.append({"role": "assistant", "content": "".join(parts)})

注意最后一行——流式响应结束后要自己把 assistant 回复塞进历史,否则下一轮模型不知道它说过什么。

六、generate 还是 chat

场景 端点
单次生成、文本补全、结构化抽取 /api/generate
多轮对话 /api/chat
工具调用 / 代理 /api/chat
需要 system 但只有一轮 两者都行,chat 更清晰

常见问题

现象 原因 处理
取不到答案 读了 response 而非 message.content 改字段名
模型「忘了」上一轮 没把历史放进 messages 自己维护并传完整历史
工具调用没触发 模型不支持 tools /api/show 查 capabilities 是否含 tools
工具结果被忽略 tool 消息没对上 tool_calls 检查数量与顺序
返回一堆行 默认流式 加 "stream": false

动手试

## ① 单轮
curl -s http://localhost:11434/api/chat -d '{
  "model": "gemma4",
  "messages": [{"role":"user","content":"hi"}],
  "stream": false
}' | python -m json.tool

## ② 查模型支持哪些能力(含 tools)
curl -s http://localhost:11434/api/show -d '{"model":"qwen3"}' | python -c "
import sys,json;print(json.load(sys.stdin).get('capabilities'))"

第二条返回里有 tools,这个模型才能做工具调用。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号