跳过至正文
流式传输允许您在模型生成文本时同步进行渲染。 REST API 默认启用流式传输,但 SDK 默认禁用。 如需在 SDK 中启用流式传输,请将 stream 参数设置为 True

流式传输核心概念

  1. 聊天:流式传输助手的部分消息。每个数据块(chunk)都包含 content,以便您在消息到达时即时渲染。
  2. 思考:具备思考能力的模型在每个数据块中除了常规内容外,还会发送一个 thinking 字段。通过检测流式数据块中的此字段,可以在最终答案呈现前显示或隐藏推理过程。
  3. 工具调用:监测每个数据块中的流式 tool_calls,执行请求的工具,并将工具输出添加回对话中。

处理流式数据块

必须累加这些部分字段以维持对话历史。这对于工具调用尤为重要,因为思考过程、模型的工具调用指令以及执行后的工具结果都必须在下一次请求中传回给模型。
from ollama import chat

stream = chat(
  model='qwen3',
  messages=[{'role': 'user', 'content': 'What is 17 × 23?'}],
  stream=True,
)

in_thinking = False
content = ''
thinking = ''
for chunk in stream:
  if chunk.message.thinking:
    if not in_thinking:
      in_thinking = True
      print('Thinking:\n', end='', flush=True)
    print(chunk.message.thinking, end='', flush=True)
    # accumulate the partial thinking 
    thinking += chunk.message.thinking
  elif chunk.message.content:
    if in_thinking:
      in_thinking = False
      print('\n\nAnswer:\n', end='', flush=True)
    print(chunk.message.content, end='', flush=True)
    # accumulate the partial content
    content += chunk.message.content

  # append the accumulated fields to the messages for the next request
  new_messages = [{ role: 'assistant', thinking: thinking, content: content }]