> For the complete documentation index, see [llms.txt](https://runyourai.gitbook.io/userguide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://runyourai.gitbook.io/userguide/api/guide/stream.md).

# 스트리밍 응답 받기

스트리밍을 사용하면 AI의 응답이 완성될 때까지 기다리지 않고, 생성되는 즉시 글자 단위로 받아볼 수 있습니다. 채팅 서비스처럼 타이핑 효과를 구현하거나 긴 응답을 빠르게 표시하고 싶을 때 사용하세요.

***

### 스트리밍 응답 받기

요청에 `stream=True` (Python) 또는 `stream: true` (Node.js / JSON)를 추가하면 됩니다.

{% tabs %}
{% tab title="Python" %}

```python
stream = client.chat.completions.create(
    model="openai/gpt-5.2",
    messages=[{"role": "user", "content": "RunYour AI를 소개해줘."}],
    stream=True   # ← 스트리밍 활성화
)

for chunk in stream:
    token = chunk.choices[0].delta.content
    if token is not None:
        print(token, end="", flush=True)  # 글자가 생성될 때마다 출력
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const stream = await client.chat.completions.create({
  model: "openai/gpt-5.2",
  messages: [{ role: "user", content: "RunYour AI를 소개해줘." }],
  stream: true,   // ← 스트리밍 활성화
});

for await (const chunk of stream) {
  const token = chunk.choices?.[0]?.delta?.content;
  if (token) process.stdout.write(token);  // 글자가 생성될 때마다 출력
}
```

{% endtab %}

{% tab title="cURL" %}

```bash
curl https://api.runyour.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer runyour-v1-YOUR_API_KEY" \
  -d '{
    "model": "openai/gpt-5.2",
    "messages": [{ "role": "user", "content": "RunYour AI를 소개해줘." }],
    "stream": true
  }'
```

{% endtab %}
{% endtabs %}

응답은 텍스트가 생성되는 순서대로 `delta.content` 조각(청크)으로 전달됩니다.

***

### 스트리밍 응답 구조 이해하기

스트리밍 응답은 **Server-Sent Events(SSE)** 형식으로 전송됩니다. 각 줄은 아래와 같은 형태의 JSON 청크입니다.

```
data: {"id":"chatcmpl-123","object":"chat.completion.chunk","model":"openai/gpt-5.2","choices":[{"delta":{"content":"안녕"},"finish_reason":null}]}

data: {"id":"chatcmpl-123","object":"chat.completion.chunk","model":"openai/gpt-5.2","choices":[{"delta":{"content":"하세요!"},"finish_reason":null}]}

data: {"id":"chatcmpl-123","object":"chat.completion.chunk","model":"openai/gpt-5.2","choices":[{"delta":{},"finish_reason":"stop"}]}

data: [DONE]
```

* 각 청크의 `choices[0].delta.content`에 글자 조각이 담겨 있습니다.
* `finish_reason`이 `"stop"`으로 바뀌면 응답이 완료된 것입니다.
* 마지막에 `data: [DONE]` 신호가 전송되면 스트림이 종료됩니다.

***

### Responses API에서 스트리밍 받기

`/v1/responses` 엔드포인트도 스트리밍을 지원합니다. 단, **OpenAI 모델(`openai/...`)에서만** 사용 가능합니다.

{% tabs %}
{% tab title="Python" %}

```python
stream = client.responses.create(
    model="openai/gpt-5",
    input="1부터 3까지 짧게 세어줘.",
    stream=True,
)

for event in stream:
    print(event.type, event)  # OpenAI Responses 스트림 이벤트
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const stream = await client.responses.create({
  model: "openai/gpt-5",
  input: "1부터 3까지 짧게 세어줘.",
  stream: true,
});

for await (const event of stream) {
  console.log(event.type, event);  // OpenAI Responses 스트림 이벤트
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
Responses API 스트리밍은 `openai/...` 모델에서만 지원됩니다. Claude, Gemini, DeepSeek 등 다른 모델의 스트리밍은 위의 Chat Completions(`/v1/chat/completions`) 방식을 사용하세요.
{% endhint %}

***

### 스트리밍 사용 시 유의사항

* 스트림 연결을 클라이언트에서 중단하더라도 이미 생성된 토큰에 대해서는 비용이 청구됩니다.
* 스트리밍 응답은 완성 여부와 무관하게 생성된 토큰 수만큼 크레딧이 차감됩니다.
* 처음에는 비스트리밍(`stream: false`)으로 연동을 안정화한 뒤, 이후 스트리밍으로 전환하는 것을 권장합니다.
