Ollama 流式工具调用:cURL/Python 实现实时工具调用
难度:进阶 · 来源:Ollama Blog · 采集于:2026-11-05
你将学到什么
- 在 Ollama 的
/api/chat请求中同时开启stream与tools,让模型边输出内容边发起工具调用。 - 用 Python SDK 把普通 Python 函数作为工具传入,并逐块处理流式返回的文本与
tool_calls。 - 了解 Ollama 新工具解析器的思路,以及 MCP 场景下上下文窗口的调优建议。
前置条件
- 安装最新版 Ollama:原文给出下载页
https://ollama.com/download。 - 使用支持工具调用的模型,例如 Qwen 3、Devstral、Qwen2.5 / Qwen2.5-coder、Llama 3.1、Llama 4 等。
- Python 示例需安装最新版 Ollama Python 库:
pip install -U ollama
JavaScript 示例需安装:
npm i ollama
步骤
-
确认环境为最新版 Ollama 与最新 SDK。原文强调流式工具调用依赖新版本;Python 用
pip install -U ollama更新,JS 用npm i ollama更新。 -
选择支持工具调用的模型。示例使用
qwen3;原文还列出devstral、qwen2.5、qwen2.5-coder、llama3.1、llama4,并给出工具调用模型检索页。 -
用 cURL 调
/api/chat,请求体中设置"stream": true,并在tools数组里声明函数。原文天气示例声明get_current_weather,参数为location与format(celsius/fahrenheit)。返回是多个 JSON 块,可能先出现文本内容,再出现tool_calls。 -
用 Python SDK 把 Python 函数直接作为工具传入,并迭代流式响应。原文示例:
# Define the python function
def add_two_numbers(a: int, b: int) -> int:
"""
Add two numbers
Args:
a (set): The first number as an int
b (set): The second number as an int
Returns:
int: The sum of the two numbers
"""
return a + b
from ollama import chat, ChatResponse
messages = [{'role': 'user', 'content': 'what is three minus one?'}]
response: ChatResponse = chat(
model='qwen3',
messages=messages,
tools=[add_two_numbers], # Python SDK supports passing tools as functions
stream=True
)
for chunk in response:
# Print model content
print(chunk.message.content, end='', flush=True)
# Print the tool call
if chunk.message.tool_calls:
print(chunk.message.tool_calls)
运行时逐块读取:chunk.message.content 是文本增量,chunk.message.tool_calls 是工具调用。
-
JavaScript SDK 同样在
ollama.chat中传入tools与stream: true,用for await迭代 chunk。原文示例定义addTwoNumbers工具 schema,并分别打印工具调用与模型内容。 -
MCP 场景下,现在可以在使用 Ollama 与 MCP 时流式输出聊天内容和工具调用。原文经验性建议使用 32k 或更高上下文窗口可提升工具调用性能与结果,但内存占用会增加。原文示例:
curl -X POST "http://localhost:11434/api/chat" -d '{
"model": "llama3.2",
"messages": [
{
"role": "user",
"content": "why is the sky blue?"
}
],
"options": {
"num_ctx": 32000 # Update context window here
}
}'
常见坑/注意事项
- 必须使用最新版 Ollama 和最新 SDK;旧方式要等完整输出后再按 JSON 解析,无法边流式输出边判断工具调用。
- 不同模型的工具调用前缀/模板不同;新解析器会参考模型模板识别工具调用,并在模型无前缀输出 JSON 时回退解析。若 JSON 不符合该模型的工具调用格式,会作为普通内容返回。
- 原文提到模型有时会在结果回传后重复引用此前的工具调用;新解析器通过前缀匹配和状态管理提升可靠性。
- 增大上下文窗口会增加内存使用;32k 以上是原文的经验性建议,并非硬性保证。
原文链接:https://ollama.com/blog/streaming-tool
原文:Streaming responses with tool calling May 28, 2025 Ollama now supports streaming responses with tool calling. This enabl(本文为采集智能体整理的导读,版权归原作者,请阅读原文获取完整内容)
评论(1)