# סטרימינג

> קבלת טוקנים בזמן שהם נוצרים, עם server-sent events, בכל פורמטי ה-API.


מגדירים `stream: true`. התגובה היא `text/event-stream`. האירועים נשלחים אחד אחרי השני, בלי אגירה.

```bash test
curl -N https://api.notholy.com/v1/chat/completions \
  -H "Authorization: Bearer $NOTHOLY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "notholy-specter", "stream": true, "stream_options": {"include_usage": true}, "messages": [{"role": "user", "content": "Define XSS."}]}'
```

```python test
import os
from openai import OpenAI

client = OpenAI(base_url="https://api.notholy.com/v1", api_key=os.environ["NOTHOLY_API_KEY"])

stream = client.chat.completions.create(
    model="notholy-specter",
    stream=True,
    stream_options={"include_usage": True},
    messages=[{"role": "user", "content": "Define CSRF."}],
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")
    if chunk.usage:
        print("\n", chunk.usage.total_tokens, "tokens")
```

```js test
import OpenAI from 'openai';

const client = new OpenAI({ baseURL: 'https://api.notholy.com/v1', apiKey: process.env.NOTHOLY_API_KEY });

const stream = await client.chat.completions.create({
  model: 'notholy-specter',
  stream: true,
  messages: [{ role: 'user', content: 'Define RCE.' }],
});
for await (const chunk of stream) process.stdout.write(chunk.choices[0]?.delta?.content ?? '');
console.log();
```

## מה מקבלים

- Chat completions ו-text completions מסתיימים באירוע `data: [DONE]`. המקטע שלפניו תמיד מכיל את `usage`, עם `include_usage` או בלעדיו.
- Responses מסתיים באירוע `response.completed` (או `response.incomplete` כשמגיעים למגבלת הפלט). Messages מסתיים באירוע `message_delta` ואחריו `message_stop`. אף אחד מהם לא שולח `[DONE]`.
- בהפסקות ארוכות נשלחות הערות keep-alive (בפורמטים של OpenAI) או אירועי `ping` (ב-Messages).
- אם הסטרים נקטע, משלמים רק על הטוקנים שנוצרו לפני הניתוק.
- שגיאות שמתגלות לפני שהסטרים מתחיל (מפתח, קרדיטים, מגבלות) חוזרות כשגיאת JSON רגילה עם סטטוס ה-HTTP שלהן. כשל אחרי שהסטרים התחיל מגיע כאירוע שגיאה באותו פורמט: `data: {"error": ...}`, `response.failed` או אירוע `error`.

## הבא

- [שגיאות](/he/guides/errors)
