Bạn có bao giờ sử dụng ChatGPT và thấy câu trả lời xuất hiện từng chữ một thay vì đợi toàn bộ? Đó chính là Streaming Response — kỹ thuật giúp ứng dụng AI trở nên mượt mà và chuyên nghiệp hơn bao giờ hết.

Trong bài viết này, mình sẽ hướng dẫn bạn từng bước cách implement SSE (Server-Sent Events) để nhận phản hồi stream từ API, với code minh hoạ đầy đủ cho cả backend lẫn frontend. Tất cả đều sử dụng HolySheep AI — nền tảng API AI với chi phí thấp hơn 85% so với OpenAI chính thức, hỗ trợ WeChat/Alipay và độ trễ dưới 50ms.

Streaming Là Gì? Tại Sao Nó Quan Trọng?

Trước khi code, hãy hiểu đơn giản:

Streaming giúp:

HolySheep AI — Lựa Chọn Tối Ưu Cho Streaming

Mình đã thử nhiều nhà cung cấp và chọn HolySheep AI vì những lý do thực tế:

Phần 1: Backend — Server Streaming Với Node.js

Đầu tiên, mình sẽ tạo một server đơn giản bằng Node.js để nhận request từ frontend và gọi API streaming.

Bước 1: Cài Đặt Project

mkdir streaming-demo
cd streaming-demo
npm init -y
npm install express openai cors

Bước 2: Tạo Server Streaming

Tạo file server.js với nội dung:

const express = require('express');
const OpenAI = require('openai');
const cors = require('cors');
const app = express();

app.use(cors());
app.use(express.json());

// Khởi tạo OpenAI client với HolySheep API
const client = new OpenAI({
  apiKey: 'YOUR_HOLYSHEEP_API_KEY', // Thay bằng API key của bạn
  baseURL: 'https://api.holysheep.ai/v1' // URL API của HolySheep
});

// Endpoint streaming
app.post('/api/chat', async (req, res) => {
  const { message } = req.body;

  try {
    // Cấu hình stream response
    const stream = await client.chat.completions.create({
      model: 'gpt-4.1', // Model: gpt-4.1, claude-sonnet-4.5, deepseek-v3.2
      messages: [
        { role: 'system', content: 'Bạn là trợ lý AI thân thiện. Trả lời bằng tiếng Việt.' },
        { role: 'user', content: message }
      ],
      stream: true // BẬT STREAMING
    });

    // Thiết lập header cho SSE
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    res.flushHeaders();

    // Xử lý từng chunk khi nhận được
    for await (const chunk of stream) {
      const content = chunk.choices[0]?.delta?.content || '';
      if (content) {
        // Gửi dữ liệu tới client theo định dạng SSE
        res.write(data: ${JSON.stringify({ content })}\n\n);
      }
    }

    // Kết thúc stream
    res.write('data: [DONE]\n\n');
    res.end();

  } catch (error) {
    console.error('Stream error:', error);
    res.status(500).json({ error: 'Stream failed' });
  }
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(Server chạy tại http://localhost:${PORT});
  console.log('Sử dụng HolySheep API: https://api.holysheep.ai/v1');
});

Bước 3: Chạy Server

node server.js

Kết quả:

Server chạy tại http://localhost:3000
Sử dụng HolySheep API: https://api.holysheep.ai/v1

Phần 2: Frontend — Nhận Stream Bằng JavaScript

Bây giờ mình sẽ tạo giao diện web đơn giản để gửi message và hiển thị phản hồi streaming theo thời gian thực.

Tạo File index.html

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Streaming Chat Demo</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
        #chat { border: 1px solid #ccc; height: 400px; overflow-y: auto; padding: 15px; margin-bottom: 10px; }
        #input { width: 100%; padding: 10px; box-sizing: border-box; }
        .user { color: #2196F3; }
        .ai { color: #4CAF50; white-space: pre-wrap; }
        .loading { color: #999; font-style: italic; }
    </style>
</head>
<body>
    <h1>Demo Streaming Chat với HolySheep AI</h1>
    <div id="chat"></div>
    <input type="text" id="input" placeholder="Nhập câu hỏi..." />
    <button onclick="sendMessage()">Gửi</button>

    <script>
        const chatDiv = document.getElementById('chat');
        const input = document.getElementById('input');

        async function sendMessage() {
            const message = input.value.trim();
            if (!message) return;

            // Hiển thị tin nhắn user
            chatDiv.innerHTML += <div class="user">👤 Bạn: ${message}</div>;
            input.value = '';

            // Tạo container cho phản hồi AI
            const aiDiv = document.createElement('div');
            aiDiv.className = 'ai';
            aiDiv.innerHTML = '🤖 AI: ';
            chatDiv.appendChild(aiDiv);

            // Gọi API streaming
            try {
                const response = await fetch('http://localhost:3000/api/chat', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ message })
                });

                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');

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

                            try {
                                const parsed = JSON.parse(data);
                                if (parsed.content) {
                                    aiDiv.innerHTML += parsed.content;
                                    // Scroll xuống cuối
                                    chatDiv.scrollTop = chatDiv.scrollHeight;
                                }
                            } catch (e) {}
                        }
                    }
                }
            } catch (error) {
                aiDiv.innerHTML += '❌ Lỗi: ' + error.message;
            }

            chatDiv.scrollTop = chatDiv.scrollHeight;
        }

        // Gửi khi nhấn Enter
        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') sendMessage();
        });
    </script>
</body>
</html>

Phương Pháp 2: Sử Dụng EventSource (Chỉ cho GET)

Nếu bạn muốn sử dụng EventSource (phương pháp native của trình duyệt), cần đổi sang endpoint GET với query parameter:

// server.js - Thêm endpoint GET
app.get('/api/chat-stream', async (req, res) => {
  const message = req.query.message;

  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.flushHeaders();

  try {
    const stream = await client.chat.completions.create({
      model: 'gpt-4.1',
      messages: [{ role: 'user', content: message }],
      stream: true
    });

    for await (const chunk of stream) {
      const content = chunk.choices[0]?.delta?.content || '';
      if (content) {
        res.write(data: ${JSON.stringify({ content })}\n\n);
      }
    }
    res.end();
  } catch (error) {
    res.write(data: ${JSON.stringify({ error: error.message })}\n\n);
    res.end();
  }
});

// Frontend - Sử dụng EventSource
async function sendMessageEventSource(message) {
  chatDiv.innerHTML += <div class="user">👤 Bạn: ${message}</div>;
  
  const aiDiv = document.createElement('div');
  aiDiv.className = 'ai';
  aiDiv.innerHTML = '🤖 AI: ';
  chatDiv.appendChild(aiDiv);

  const encodedMessage = encodeURIComponent(message);
  const eventSource = new EventSource(http://localhost:3000/api/chat-stream?message=${encodedMessage});

  eventSource.onmessage = (event) => {
    const data = JSON.parse(event.data);
    if (data.content) {
      aiDiv.innerHTML += data.content;
      chatDiv.scrollTop = chatDiv.scrollHeight;
    }
  };

  eventSource.onerror = () => {
    aiDiv.innerHTML += '\n❌ Kết nối bị gián đoạn';
    eventSource.close();
  };
}

Phần 3: Python Backend — FastAPI Streaming

Nếu bạn thích Python hơn, đây là cách implement với FastAPI:

# requirements.txt

fastapi

uvicorn

openai

sse-starlette

from fastapi import FastAPI from fastapi.responses import StreamingResponse from openai import OpenAI import uvicorn app = FastAPI()

Khởi tạo client HolySheep

client = OpenAI( api_key="YOUR_HOLYSHEEP_API_KEY", base_url="https://api.holysheep.ai/v1" ) @app.post("/api/chat/stream") async def chat_stream(message: dict): async def event_generator(): stream = client.chat.completions.create( model="gpt-4.1", messages=[ {"role": "system", "content": "Bạn là trợ lý AI thân thiện. Trả lời bằng tiếng Việt."}, {"role": "user", "content": message.get("content", "")} ], stream=True ) for chunk in stream: content = chunk.choices[0].delta.content if content: yield f"data: {content}\n\n" yield "data: [DONE]\n\n" return StreamingResponse( event_generator(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive" } ) if __name__ == "__main__": print("🚀 FastAPI Server đang chạy tại http://localhost:8000") print("📡 Sử dụng HolySheep API: https://api.holysheep.ai/v1") uvicorn.run(app, host="0.0.0.0", port=8000)

Chạy server:

pip install fastapi uvicorn openai sse-starlette
python main.py

Hướng Dẫn Lấy API Key Từ HolySheep AI

Để sử dụng code trên, bạn cần có API key từ HolySheep AI. Các bước:

  1. Đăng ký tài khoản tại holysheep.ai/register
  2. Đăng nhập vào dashboard
  3. Tìm mục "API Keys" trong sidebar
  4. Nhấn "Create New Key" và đặt tên (ví dụ: "streaming-demo")
  5. Copy API key và dán vào code thay thế YOUR_HOLYSHEEP_API_KEY

Lưu ý: API key chỉ hiển thị MỘT lần duy nhất. Hãy lưu lại ngay!

Bảng Giá Tham Khảo — HolySheep AI 2026

ModelGiá/1M TokensUse Case
GPT-4.1$8.00Tác vụ phức tạp, coding
Claude Sonnet 4.5$15.00Phân tích sâu, viết lách
Gemini 2.5 Flash$2.50Tổng hợp, nhanh
DeepSeek V3.2$0.42Tiết kiệm chi phí

Với DeepSeek V3.2, chi phí chỉ khoảng $0.42/1 triệu tokens — rẻ hơn 95% so với GPT-4o chính thức!

Lỗi Thường Gặp Và Cách Khắc Phục

Lỗi 1: CORS Error — "Access-Control-Allow-Origin"

Mô tả: Trình duyệt chặn request từ frontend tới backend

Lỗi: Access to fetch at 'http://localhost:3000' from origin 'http://localhost:5500' 
has been blocked by CORS policy

Cách khắc phục:

// Thêm CORS middleware vào server.js
const cors = require('cors');

// Cấu hình CORS cho phép tất cả origin (development)
app.use(cors({
  origin: '*', // Production: thay bằng domain cụ thể
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type']
}));

// Hoặc cấu hình chi tiết hơn
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  if (req.method === 'OPTIONS') {
    return res.end();
  }
  next();
});

Lỗi 2: API Key Invalid Hoặc Hết Hạn

Mô tả: Server trả về lỗi authentication khi gọi API

Lỗi: 401 Unauthorized
{
  "error": {
    "message": "Invalid API key provided",
    "type": "invalid_request_error"
  }
}

Cách khắc phục:

// 1. Kiểm tra API key đã được set đúng chưa
// Đảm bảo KHÔNG có khoảng trắng thừa
const client = new OpenAI({
  apiKey: process.env.HOLYSHEEP_API_KEY, // Đọc từ environment variable
  baseURL: 'https://api.holysheep.ai/v1'
});

// 2. Thêm error handling chi tiết
try {
  const stream = await client.chat.completions.create({
    model: 'gpt-4.1',
    messages: [{ role: 'user', content: message }],
    stream: true
  });
} catch (error) {
  if (error.status === 401) {
    console.error('❌ API Key không hợp lệ. Vui lòng kiểm tra tại https://www.holysheep.ai/register');
  } else if (error.status === 429