Lần đầu tiên tôi cần implement SSE (Server-Sent Events) streaming với authentication cho một dự án chatbot AI, tôi đã tốn gần 2 tuần để debug các lỗi CORS, token expiration và connection timeout. Sau khi chuyển sang HolySheep AI, toàn bộ quá trình chỉ mất 2 ngày — và độ trễ giảm từ 800ms xuống còn dưới 50ms. Bài viết này sẽ hướng dẫn bạn implement SSE streaming với authentication một cách hoàn chỉnh, kèm theo những kinh nghiệm thực chiến mà tôi đã đúc kết được.
Tổng Quan về SSE Streaming với Authentication
Server-Sent Events (SSE) là công nghệ cho phép server push data đến client theo thời gian thực qua HTTP connection. Khi kết hợp với authentication, bạn cần đảm bảo:
- Token được truyền an toàn qua header hoặc query parameter
- Connection được duy trì ổn định qua proxy/load balancer
- Reconnection logic được xử lý đúng cách khi connection bị drop
- Rate limiting không block legitimate requests
HolySheep Relay — Tại Sao Đáng Để Thử
Trước khi đi vào code, tôi muốn chia sẻ tại sao HolySheep AI trở thành lựa chọn của tôi:
| Tiêu chí | OpenAI Direct | HolySheep Relay |
|---|---|---|
| Độ trễ trung bình | 400-800ms | <50ms |
| Tỷ giá | $1 = $1 | ¥1 = $1 (tiết kiệm 85%+) |
| Thanh toán | Chỉ thẻ quốc tế | WeChat, Alipay, Visa |
| Tín dụng miễn phí | $5 | Có, khi đăng ký |
| Stream compatibility | 原生 SSE | Tương thích 100% |
Code Implementation — 3 Cách Triển Khai
Cách 1: JavaScript Client (Browser)
Đây là cách phổ biến nhất khi bạn cần implement streaming từ frontend:
// SSE Client với Authentication
// Base URL: https://api.holysheep.ai/v1
class HolySheepSSEClient {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.holysheep.ai/v1';
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 5;
this.reconnectDelay = 1000;
}
async streamChat(model, messages, onChunk, onError, onComplete) {
const controller = new AbortController();
try {
const response = await fetch(${this.baseUrl}/chat/completions, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': Bearer ${this.apiKey},
'Accept': 'text/event-stream'
},
body: JSON.stringify({
model: model,
messages: messages,
stream: true,
stream_options: { include_usage: true }
}),
signal: controller.signal
});
if (!response.ok) {
const error = await response.json().catch(() => ({}));
throw new Error(error.error?.message || HTTP ${response.status});
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') {
onComplete?.();
return;
}
try {
const parsed = JSON.parse(data);
onChunk?.(parsed);
} catch (e) {
// Skip invalid JSON chunks
}
}
}
}
onComplete?.();
} catch (error) {
if (error.name === 'AbortError') {
console.log('Stream aborted by user');
} else {
this.handleError(error, onError);
}
}
}
handleError(error, callback) {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++;
console.log(Reconnecting... Attempt ${this.reconnectAttempts});
setTimeout(() => {
this.streamChat(/* retry logic */);
}, this.reconnectDelay * this.reconnectAttempts);
}
callback?.(error);
}
}
// Sử dụng
const client = new HolySheepSSEClient('YOUR_HOLYSHEEP_API_KEY');
await client.streamChat(
'gpt-4.1',
[{ role: 'user', content: 'Explain SSE streaming' }],
(chunk) => {
const content = chunk.choices?.[0]?.delta?.content || '';
process.stdout.write(content);
},
(error) => console.error('Error:', error),
() => console.log('\n\nStream complete!')
);
Cách 2: Python Implementation (FastAPI Backend)
Khi bạn cần implement SSE streaming ở backend để xử lý logic phức tạp hơn:
# Python SSE Streaming với HolySheep Relay
Install: pip install httpx sse-starlette
import httpx
import asyncio
from typing import AsyncGenerator, List, Dict, Any
from starlette.responses import StreamingResponse
from starlette.requests import Request
from fastapi import FastAPI, HTTPException, Header
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
CORS middleware cho frontend
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1"
class HolySheepStreamer:
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = HOLYSHEEP_BASE_URL
async def stream