스트리밍 응답 (Streaming Responses)

스트리밍 응답 (Streaming Responses)

모델이 답을 길게 만들어낼 때 통째로 기다리느라 화면이 멈춰 보이는 걸 경험해 보셨죠. Cerebras API는 메시지를 청크 단위로 나눠 보내서, 모델이 생성하는 대로 점진적으로 화면에 표시하는 스트리밍을 지원해요.

출처: Cerebras Inference - Streaming Responses

스트리밍 켜기

Cerebras API는 스트리밍 응답을 지원해요. 메시지를 청크로 나눠 보내고, 모델이 생성하는 대로 점진적으로 표시해요. 이 기능을 켜려면 chat.completions.create 메서드 안에서 stream 파라미터를 True로 설정하면 돼요. 이러면 API가 메시지의 청크를 담은 이터러블(iterable)을 반환하고, 순회하며 청크를 꺼내 쓰면 돼요.

Python에서는 이렇게 작성해요.

stream = client.chat.completions.create(
    messages=[
        {
            "role": "user",
            "content": "Why is fast inference important?",
        }
    ],
    model="qwen-3.8-27b",
    stream=True,
)

for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="")

TypeScript에서도 동일하게 chat.completions.create 메서드의 stream 속성을 true로 설정하면 되고, 스트림을 순회하며 chunk.choices[0]?.delta?.content 를 읽어 화면에 이어 붙이면 돼요.

const stream = await client.chat.completions.create({
  messages: [{ role: 'user', content: 'Why is fast inference important?' }],
  model: 'qwen-3.8-27b',
  stream: true,
});
for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content || '');
}

스트리밍으로 얻는 것

스트리밍을 쓰면 첫 토큰이 도착하는 대로 바로 렌더링하기 시작하므로 체감 지연이 확 줄어요. 길고 복합적인 답변일수록, 사용자가 결과를 기다리며 빈 화면을 보는 시간이 그만큼 짧아지는 거죠. 모델명은 실제 사용하는 모델 ID로 바꿔서 호출하면 돼요.

더 알아보기