Skip to content

串流允許您在模型產生文字時即時渲染。

透過 REST API 時,串流預設為啟用;但在 SDK 中,串流預設為停用。

若要在 SDK 中啟用串流,請將 stream 參數設為 True

關鍵串流概念

  1. 聊天:串流傳輸部分助理訊息。每個區塊都包含 content,因此您可以在訊息到達時即時渲染。
  2. 思考:具備思考能力的模型會在每個區塊中與常規內容一起發出 thinking 欄位。在串流區塊中偵測此欄位,以便在最終答案到達之前顯示或隱藏推理軌跡。
  3. 工具呼叫:留意每個區塊中串流的 tool_calls,執行要求的工具,並將工具輸出附加回對話中。

處理串流區塊

注意

為了維護對話歷史記錄,必須累積部分欄位。這對於工具呼叫尤其重要,因為在下次請求中,必須將思考、模型的工具呼叫以及已執行的工具結果傳回給模型。

Python

```python
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)
    # 累積部分思考
    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)
    # 累積部分內容
    content += chunk.message.content

  # 將累積的欄位附加到訊息中,以供下次請求使用
  new_messages = [{ role: 'assistant', thinking: thinking, content: content }]
```

JavaScript

```javascript
import ollama from 'ollama'

async function main() {
  const stream = await ollama.chat({
    model: 'qwen3',
    messages: [{ role: 'user', content: 'What is 17 × 23?' }],
    stream: true,
  })

  let inThinking = false
  let content = ''
  let thinking = ''

  for await (const chunk of stream) {
    if (chunk.message.thinking) {
      if (!inThinking) {
        inThinking = true
        process.stdout.write('Thinking:\n')
      }
      process.stdout.write(chunk.message.thinking)
      // 累積部分思考
      thinking += chunk.message.thinking
    } else if (chunk.message.content) {
      if (inThinking) {
        inThinking = false
        process.stdout.write('\n\nAnswer:\n')
      }
      process.stdout.write(chunk.message.content)
      // 累積部分內容
      content += chunk.message.content
    }
  }

  // 將累積的欄位附加到訊息中,以供下次請求使用
  new_messages = [{ role: 'assistant', thinking: thinking, content: content }]
}

main().catch(console.error)
```