BazaarLinkBazaarLink
로그인
문서API 레퍼런스SDK 레퍼런스에이전트 사용법AI 스킬
목차

스트리밍

스트리밍

설정 stream: true 하여 Server-Sent Events(SSE) 스트림을 받으세요. 각 이벤트에는 응답 청크가 포함됩니다.

from openai import OpenAI

client = OpenAI(
    base_url="https://api.bazaarlink.ai/v1",
    api_key="sk-bl-YOUR_API_KEY",
)

stream = client.chat.completions.create(
    model="anthropic/claude-sonnet-4.6",
    messages=[{"role": "user", "content": "Count to 10 slowly."}],
    stream=True,
)

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

SSE 형식

data: {"id":"85e6f35c71a31f19-SJC","choices":[{"delta":{"content":"Hello"},"index":0}]}

data: {"id":"85e6f35c71a31f19-SJC","choices":[{"delta":{"content":" world"},"index":0}]}

data: {"id":"85e6f35c71a31f19-SJC","choices":[{"delta":{},"finish_reason":"stop","index":0}],"usage":{"prompt_tokens":10,"completion_tokens":4,"total_tokens":14}}

data: [DONE]
스트리밍에서의 사용량
스트리밍 시, 사용량 데이터는 [DONE] 메시지 이전의 마지막 청크에서 빈 delta와 finish_reason: "stop"을 가진 choices 배열과 함께 반환됩니다.

Keep-alive 및 마지막 청크

스트림에는 SSE 주석 줄과 알 수 없는 또는 ping keep-alive 이벤트가 포함될 수 있습니다. 이를 무시하고 data 프레임을 파싱하세요. 마지막 data 프레임에는 data: [DONE] 전에 usage가 포함될 수 있습니다.

: keepalive          <- SSE comment line — ignore, do NOT JSON.parse

data: {"id":"85e6f35c71a31f19-SJC","choices":[{"delta":{"content":"Hi"},"index":0}]}

data: {"id":"85e6f35c71a31f19-SJC","choices":[{"delta":{},"finish_reason":"stop","index":0}],"usage":{...}}

data: [DONE]

스트림 취소

클라이언트 연결을 종료하면 스트리밍 요청을 취소할 수 있습니다 — 예: AbortController.abort() 호출 또는 stream 객체 종료. BazaarLink는 취소 신호를 받는 즉시 이후 청크 전달을 중단하고 공급자로 나가는 요청을 취소합니다.

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.bazaarlink.ai/v1",
  apiKey: "sk-bl-YOUR_API_KEY",
});

const controller = new AbortController();

const stream = await client.chat.completions.create(
  {
    model: "anthropic/claude-sonnet-4.6",
    messages: [{ role: "user", content: "Write a long story." }],
    stream: true,
  },
  { signal: controller.signal }
);

for await (const chunk of stream) {
  const content = chunk.choices[0]?.delta?.content;
  if (content) process.stdout.write(content);
}

// e.g. on a "Stop" button click:
controller.abort();
중단된 스트림은 과금되지 않습니다
마지막 usage 청크가 도착하기 전에 스트림이 끝나면 — 클라이언트 측 취소를 포함해서 — 해당 요청의 신뢰할 수 있는 토큰 수 근거가 없으므로 BazaarLink는 예약된 금액 전액을 환불합니다. 취소 전에 클라이언트로 이미 전달된 내용에 대해서는 과금되지 않습니다.
공급자 측 즉시 중단은 보장되지 않습니다
연결을 종료하면 BazaarLink는 즉시 이후 토큰 전달과 과금을 중단하지만, 업스트림 공급자가 연결이 끊기는 순간 자사 서버에서 생성을 멈추는지 여부는 해당 공급자에 따라 다릅니다 — 일부는 연결 종료 후에도 잠시 계속 계산할 수 있습니다.

스트림 도중 오류

오류 프레임에는 choices 필드가 없음
스트리밍이 이미 시작된 후 실패가 발생하면(예: 업스트림 연결 끊김), 일반적인 {choices:[...]} 대신 {error:{message,type,code}} 형태의 SSE 데이터 프레임을 받게 됩니다 — 헤더는 이미 전송되었으므로 HTTP 상태 변경은 없습니다. choices[0].delta를 읽기 전에 error 키가 있는지 확인하세요. 이미 스트리밍된 토큰에 대해서만 과금됩니다(부분 과금 적용).
data: {"id":"85e6f35c71a31f19-SJC","choices":[{"delta":{"content":"The capital of "},"index":0}]}

data: {"error":{"message":"The request could not be completed.","type":"upstream_error","code":502}}

data: [DONE]
Support
Hi! How can we help you?
Send a message and we'll get back to you soon.
스트리밍 | BazaarLink