Chuyển đến nội dung chính

Tổng quan

Streaming cho phép bạn nhận các phản hồi từng phần khi chúng được tạo ra, mang lại trải nghiệm người dùng tốt hơn cho các ứng dụng chat.

Bật Streaming

Thiết lập stream: true trong request của bạn:
curl https://api.lemondata.cc/v1/chat/completions \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [{"role": "user", "content": "Write a short poem"}],
    "stream": true
  }'

Định dạng Phản hồi Stream

Mỗi chunk trong stream tuân theo định dạng sau:
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1234567890,"model":"gpt-4o","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1234567890,"model":"gpt-4o","choices":[{"index":0,"delta":{"content":" world"},"finish_reason":null}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1234567890,"model":"gpt-4o","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: [DONE]

Xử lý Kết thúc Stream

Stream kết thúc với:
  • finish_reason: "stop" - Hoàn thành bình thường
  • finish_reason: "length" - Chạm giới hạn max_tokens
  • finish_reason: "tool_calls" - Model muốn gọi một tool
  • data: [DONE] - Tin nhắn cuối cùng

Thu thập Phản hồi Đầy đủ

Để thu thập phản hồi đầy đủ trong khi streaming:
full_response = ""

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

print(f"\n\nFull response: {full_response}")

Streaming Bất đồng bộ (Async)

Đối với các ứng dụng bất đồng bộ:
import asyncio
from openai import AsyncOpenAI

async def main():
    client = AsyncOpenAI(
        api_key="sk-your-api-key",
        base_url="https://api.lemondata.cc/v1"
    )

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

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

asyncio.run(main())

Ví dụ Ứng dụng Web

Đối với một giao diện chat web:
async function streamChat(message) {
  const response = await fetch('https://api.lemondata.cc/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer sk-your-api-key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'gpt-4o',
      messages: [{ role: 'user', content: message }],
      stream: true
    })
  });

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

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

    const chunk = decoder.decode(value);
    const lines = chunk.split('\n').filter(line => line.startsWith('data: '));

    for (const line of lines) {
      const data = line.slice(6);
      if (data === '[DONE]') return;

      const parsed = JSON.parse(data);
      const content = parsed.choices[0]?.delta?.content;
      if (content) {
        // Thêm vào giao diện người dùng của bạn
        document.getElementById('output').textContent += content;
      }
    }
  }
}