DeepInfra 스트리밍 — 토큰 단위로 응답 받기
DeepInfra 스트리밍 — 토큰 단위로 응답 받기
긴 답변을 통째로 기다리기보다, 생성되는 토큰을 실시간으로 받아보고 싶을 때가 있어요. DeepInfra는 OpenAI와 같은 SSE(Server-Sent Events) 프로토콜로 스트리밍 응답을 지원해요. 요청에 stream: true만 넣으면 되는 구조예요.
예시
Python에서 이렇게 스트림을 열어요. 생성되는 조각마다 delta.content를 이어 붙이면 자연스러운 타이핑 효과가 만들어져요.
from openai import OpenAI
openai = OpenAI(
api_key="$DEEPINFRA_TOKEN",
base_url="https://api.deepinfra.com/v1/openai",
)
stream = openai.chat.completions.create(
model="deepseek-ai/DeepSeek-V4-Flash-0731",
messages=[{"role": "user", "content": "Hello"}],
stream=True,
)
for event in stream:
if event.choices[0].finish_reason:
print(event.choices[0].finish_reason,
event.usage['prompt_tokens'],
event.usage['completion_tokens'])
else:
print(event.choices[0].delta.content, end="", flush=True)
JavaScript도 비슷해요. for await 루프로 청크를 순회해요.
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: "$DEEPINFRA_TOKEN",
baseURL: "https://api.deepinfra.com/v1/openai",
});
const completion = await openai.chat.completions.create({
messages: [{ role: "user", content: "Hello" }],
model: "deepseek-ai/DeepSeek-V4-Flash-0731",
stream: true,
});
for await (const chunk of completion) {
if (chunk.choices[0].finish_reason) {
console.log(chunk.choices[0].finish_reason,
chunk.usage.prompt_tokens,
chunk.usage.completion_tokens);
} else {
process.stdout.write(chunk.choices[0].delta.content);
}
}
curl로 요청 자체만 확인한다면 이렇게 해요.
curl "https://api.deepinfra.com/v1/openai/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $DEEPINFRA_TOKEN" \
-d '{
"model": "deepseek-ai/DeepSeek-V4-Flash-0731",
"stream": true,
"messages": [
{
"role": "user",
"content": "Hello!"
}
]
}'
SSE 형식
스트리밍되는 각 청크는 JSON 객체를 담은 data: 줄이에요.
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","choices":[{"delta":{"content":"Hello"},"finish_reason":null}]}
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":5}}
data: [DONE]
[DONE] 바로 직전의 마지막 청크에 usage 정보가 들어와요.
알아둘 점
- 스트리밍은 지원되는 모든 모델에서 동작해요
- usage 통계는 마지막 청크에서 확인할 수 있어요(
finish_reason이 설정된 청크) completion_tokens·prompt_tokens수치는 비스트리밍과 동일해요
더 알아보기
- Chat Completions — 스트리밍의 근거가 되는 채팅 완성 API
- DeepInfra 문서 전체 인덱스