Skip to content

스트리밍을 사용하면 모델이 텍스트를 생성하는 대로 렌더링할 수 있습니다.

스트리밍은 REST API를 통해 기본적으로 활성화되어 있지만, SDK에서는 기본적으로 비활성화되어 있습니다.

SDK에서 스트리밍을 활성화하려면 stream 매개변수를 True로 설정하세요.

주요 스트리밍 개념

  1. 채팅: 부분적인 어시스턴트 메시지를 스트리밍합니다. 각 청크에는 content가 포함되어 있어 메시지가 도착하는 대로 렌더링할 수 있습니다.
  2. 사고(Thinking): 사고 기능을 지원하는 모델은 각 청크의 일반 콘텐츠와 함께 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)
    # 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 }]
```

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)
      // accumulate the partial 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)
      // 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 }]
}

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