Streaming

Nhận response theo từng token bằng Server-Sent Events (SSE).

POST https://bizgpt.vn/wp-json/bizcity/v1/llm/chat/stream

Streaming cho phép bạn nhận câu trả lời ngay khi model đang generate, thay vì chờ hoàn tất. Điều này giúp trải nghiệm chat mượt mà và nhanh hơn.

Cách sử dụng

Có 2 cách bật streaming:

  1. Gửi request tới endpoint /chat/stream
  2. Hoặc gửi tới /chat với "stream": true trong body

Ví dụ: curl

bash
curl -X POST https://bizgpt.vn/wp-json/bizcity/v1/llm/chat/stream \
  -H "Authorization: Bearer biz-YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o",
    "messages": [
      { "role": "user", "content": "Viết bài thơ ngắn về Hà Nội" }
    ]
  }'

SSE Response Format

Server gửi các event dạng text, mỗi event cách nhau bằng dòng trống:

text
data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}

data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hà"},"finish_reason":null}]}

data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":" Nội"},"finish_reason":null}]}

data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: [DONE]
ℹ️ Ghi chú Mỗi chunk chứa delta thay vì message. Bạn cần nối (concatenate) các delta.content lại để có message hoàn chỉnh. Stream kết thúc khi nhận data: [DONE].

Python (OpenAI SDK)

python
from openai import OpenAI

client = OpenAI(
    base_url="https://bizgpt.vn/wp-json/bizcity/v1/llm",
    api_key="biz-YOUR_API_KEY",
)

stream = client.chat.completions.create(
    model="openai/gpt-4o",
    messages=[{"role": "user", "content": "Hello!"}],
    stream=True,
)

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

JavaScript (Fetch API)

javascript
const response = await fetch("https://bizgpt.vn/wp-json/bizcity/v1/llm/chat/stream", {
  method: "POST",
  headers: {
    "Authorization": "Bearer biz-YOUR_API_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "openai/gpt-4o",
    messages: [{ role: "user", content: "Hello!" }],
  }),
});

const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;

  const text = decoder.decode(value);
  for (const line of text.split("\n")) {
    if (!line.startsWith("data: ")) continue;
    const data = line.slice(6);
    if (data === "[DONE]") break;
    const chunk = JSON.parse(data);
    const content = chunk.choices?.[0]?.delta?.content;
    if (content) process.stdout.write(content);
  }
}