스트리밍은 전체 응답이 완성될 때까지 기다리지 않고, 모델이 답변을 생성하는 대로 바로 보내 줍니다. 앱은 채팅 화면에서 글자를 타이핑하듯 도착하는 대로 단어를 보여 줄 수 있습니다. 긴 답변도 전체가 끝날 때까지 기다리지 않고 바로 화면에 표시하기 시작할 수 있습니다.
동작 방식
일반 API 호출은 모델이 생성을 마친 뒤 JSON 객체 하나를 반환합니다. 스트리밍 호출은 HTTP 연결을 열어 둔 채 server-sent events(SSE)로 작은 이벤트를 연속해서 보냅니다. 각 이벤트는 data: 로 시작하는 줄과 그 뒤의 JSON 청크로 이루어지며, 마지막은 data: [DONE] 줄로 끝납니다. 각 청크에는 지금까지의 전체 텍스트가 아니라 답변의 작은 조각("delta")만 들어 있으므로, 코드에서 조각을 버퍼에 이어 붙여야 합니다.
OpenAI 호환 API에서 스트리밍을 켜려면 요청 본문에 "stream": true를 설정하세요.
Python (OpenAI SDK)
from openai import OpenAI
client = OpenAI(base_url="https://aidiscount.ai/v1", api_key=os.environ["AIDISCOUNT_API_KEY"])
stream = client.chat.completions.create(
model="gpt-6-luna",
messages=[{"role": "user", "content": "Write a short poem about rivers."}],
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
print(delta, end="", flush=True)
Python (SDK 없이 SSE 직접 처리)
import json, os, requests
with requests.post(
"https://aidiscount.ai/v1/chat/completions",
headers={"Authorization": f"Bearer {os.environ['AIDISCOUNT_API_KEY']}"},
json={"model": "gpt-6-luna", "stream": True,
"messages": [{"role": "user", "content": "Write a short poem about rivers."}]},
stream=True, timeout=120,
) as r:
r.raise_for_status()
for line in r.iter_lines():
if not line or not line.startswith(b"data: "):
continue
payload = line[len(b"data: "):]
if payload == b"[DONE]":
break
delta = json.loads(payload)["choices"][0]["delta"].get("content")
if delta:
print(delta, end="", flush=True)
Node.js (OpenAI SDK)
import OpenAI from "openai";
const client = new OpenAI({ baseURL: "https://aidiscount.ai/v1", apiKey: process.env.AIDISCOUNT_API_KEY });
const stream = await client.chat.completions.create({
model: "gpt-6-luna",
messages: [{ role: "user", content: "Write a short poem about rivers." }],
stream: true,
});
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta?.content;
if (delta) process.stdout.write(delta);
}
Node.js (SDK 없이 fetch 사용)
const res = await fetch("https://aidiscount.ai/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.AIDISCOUNT_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gpt-6-luna",
stream: true,
messages: [{ role: "user", content: "Write a short poem about rivers." }],
}),
});
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
const lines = buf.split("\n");
buf = lines.pop();
for (const line of lines) {
if (!line.startsWith("data: ")) continue;
const data = line.slice(6);
if (data === "[DONE]") continue;
const delta = JSON.parse(data).choices[0]?.delta?.content;
if (delta) process.stdout.write(delta);
}
}
Anthropic Messages 형식
이벤트 구조가 다릅니다. 각 SSE 이벤트에는 이름이 붙은 event: 줄이 있고, 텍스트는 content_block_delta 이벤트로 도착합니다.
import anthropic
client = anthropic.Anthropic(base_url="https://aidiscount.ai", api_key=os.environ["AIDISCOUNT_API_KEY"])
with client.messages.stream(
model="claude-opus-4-8",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a short poem about rivers."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
연결이 끊겼을 때
스트리밍 요청은 텍스트가 일부 표시된 뒤 도중에 실패할 수 있습니다. 연결이 끊기기 전에 생성된 토큰은 보통 그대로 과금되므로, 짧은 간격으로 계속 재시도하지 마세요. UI에서는 오류를 잡아 이미 도착한 텍스트를 유지하고, 처음부터 조용히 다시 시작하는 대신 재시도 버튼을 보여 주세요. 재시도할 때는 같은 요청을 다시 보내면 됩니다. 새 요청은 새 스트림으로 시작됩니다.
프록시나 로드 밸런서 뒤에서는 연결이 버퍼링되거나 일찍 닫히지 않도록 해야 합니다. Nginx는 스트리밍하는 경로에 proxy_buffering off;가 필요하고, 클라이언트 타임아웃은 느린 모델이 생성을 마칠 수 있을 만큼 길어야 합니다. (스트리밍 응답은 유휴 연결이 아니라 활성 트래픽으로 취급되므로, 대부분의 클라이언트는 별도의 타임아웃 처리가 필요하지 않습니다.)
도구 호출과 스트리밍
모델이 도구 호출을 스트리밍하면 함수 이름과 인수도 여러 청크로 나뉘어 조각조각 도착합니다. tool_calls delta를 index별로 버퍼에 모으고, 스트림이 끝날 때까지 arguments 문자열을 이어 붙인 다음 JSON으로 파싱하세요. 대부분의 SDK는 이 버퍼링을 자동으로 처리합니다.