ในปัจจุบัน AI API อย่าง HolySheep AI สามารถตอบกลับมาแบบทีละส่วน แทนที่จะรอจนเสร็จทั้งหมด วิธีนี้เรียกว่า Streaming และเทคโนโลยีหลักที่ใช้คือ Server-Sent Events หรือ SSE

SSE คืออะไร ทำไมต้องเรียนรู้

SSE ย่อมาจาก Server-Sent Events เป็นวิธีที่เซิร์ฟเวอร์ส่งข้อมูลมาหาฝั่งลูกค้าทีละส่วน โดยไม่ต้องรอจนเสร็จทั้งหมด ต่างจากวิธีปกติที่ต้องรอ Loading นานๆ เหมาะมากสำหรับงาน AI Chat ที่ต้องการเห็นตัวอักษรพิมพ์ขึ้นทีละตัว

ข้อดีของการใช้ HolySheep AI ผ่าน SSE:

การตั้งค่าเริ่มต้นสำหรับผู้เริ่มต้น

ก่อนจะเริ่มเขียนโค้ด ให้เตรียมสิ่งต่อไปนี้:

โค้ดพื้นฐานสำหรับรับข้อมูล Streaming ด้วย JavaScript

นี่คือตัวอย่างโค้ดง่ายๆ สำหรับรับข้อมูลจาก API แบบ Stream

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <title>SSE Stream Demo - HolySheep AI</title>
    <style>
        body { font-family: sans-serif; padding: 20px; }
        #output { 
            border: 1px solid #ccc; 
            padding: 15px; 
            min-height: 200px;
            background: #f9f9f9;
        }
        .loading { color: #666; }
        .error { color: red; }
    </style>
</head>
<body>
    <h1>ทดสอบ SSE Stream กับ HolySheep AI</h1>
    
    <textarea id="prompt" rows="3" cols="50" 
        placeholder="พิมพ์คำถามของคุณที่นี่...">
สงครามโลกครั้งที่สองสิ้นสุดเมื่อใด
    </textarea>
    <br><br>
    <button onclick="sendMessage()">ส่งคำถาม</button>
    <button onclick="closeConnection()">หยุดรับข้อมูล</button>
    
    <h3>คำตอบ:</h3>
    <div id="output"></div>
    
    <script>
        let eventSource = null;
        let fullResponse = '';
        
        function sendMessage() {
            const prompt = document.getElementById('prompt').value;
            const output = document.getElementById('output');
            
            // ล้างข้อความเก่า
            output.innerHTML = '';
            output.innerHTML = '<span class="loading">กำลังโหลด...</span>';
            fullResponse = '';
            
            // ปิดการเชื่อมต่อเดิมถ้ามี
            closeConnection();
            
            // ตรวจสอบว่าเบราว์เซอร์รองรับ SSE หรือไม่
            if (!window.EventSource) {
                output.innerHTML = '<span class="error">เบราว์เซอร์นี้ไม่รองรับ SSE</span>';
                return;
            }
            
            // สร้างการเชื่อมต่อ SSE
            eventSource = new EventSource(
                'https://api.holysheep.ai/v1/chat/completions' +
                '?stream=true'
            );
            
            // ตั้งค่า EventSource ด้วยวิธี POST
            // หมายเหตุ: EventSource รองรับเฉพาะ GET 
            // ดังนั้นต้องใช้ fetch แทน
        }
        
        function closeConnection() {
            if (eventSource) {
                eventSource.close();
                eventSource = null;
            }
        }
    </script>
</body>
</html>

วิธีที่ถูกต้อง: ใช้ Fetch API สำหรับ Streaming

เนื่องจาก EventSource รองรับเฉพาะการร้องขอแบบ GET แต่ API ส่วนใหญ่ต้องการ POSTพร้อมข้อมูล เราจึงต้องใช้ Fetch API แทน

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <title>SSE Streaming ด้วย Fetch API - HolySheep AI</title>
    <style>
        body { font-family: sans-serif; padding: 20px; max-width: 800px; margin: auto; }
        #prompt { width: 100%; padding: 10px; margin-bottom: 10px; }
        #output { 
            border: 2px solid #4CAF50; 
            padding: 20px; 
            min-height: 300px;
            background: #f1f8e9;
            border-radius: 8px;
            white-space: pre-wrap;
            line-height: 1.6;
        }
        .loading { color: #ff9800; }
        .complete { color: #4CAF50; }
        button { 
            padding: 10px 20px; 
            margin: 5px;
            cursor: pointer;
            background: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
        }
        button:hover { background: #45a049; }
        .stop-btn { background: #f44336; }
        .stop-btn:hover { background: #da190b; }
    </style>
</head>
<body>
    <h1>รับข้อมูล Streaming จาก HolySheep AI</h1>
    <p>API: https://api.holysheep.ai/v1/chat/completions | ราคา: DeepSeek V3.2 $0.42/MTok</p>
    
    <textarea id="prompt" rows="4" placeholder="พิมพ์คำถามของคุณ...">
อธิบายประโยชน์ของการเขียนโปรแกรมเป็นภาษา Python
    </textarea>
    <br>
    <button onclick="startStream()">เริ่มรับข้อมูล Stream</button>
    <button class="stop-btn" onclick="stopStream()">หยุดรับ</button>
    
    <h3>คำตอบจาก AI:</h3>
    <div id="output"></div>
    
    <script>
        let abortController = null;
        let reader = null;
        
        async function startStream() {
            const prompt = document.getElementById('prompt').value;
            const output = document.getElementById('output');
            
            if (!prompt.trim()) {
                alert('กรุณาพิมพ์คำถาม');
                return;
            }
            
            // สร้าง AbortController สำหรับยกเลิกการเชื่อมต่อ
            abortController = new AbortController();
            
            // แสดงสถานะกำลังโหลด
            output.innerHTML = '<span class="loading">กำลังเชื่อมต่อกับ HolySheep AI...</span>';
            
            try {
                const response = await fetch('https://api.holysheep.ai/v1/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer YOUR_HOLYSHEEP_API_KEY'
                    },
                    body: JSON.stringify({
                        model: 'deepseek-chat',
                        messages: [
                            { role: 'user', content: prompt }
                        ],
                        stream: true
                    }),
                    signal: abortController.signal
                });
                
                // ตรวจสอบว่าได้รับข้อมูลสำเร็จหรือไม่
                if (!response.ok) {
                    const error = await response.json();
                    output.innerHTML = <span class="error">เกิดข้อผิดพลาด: ${error.error?.message || response.statusText}</span>;
                    return;
                }
                
                // ล้างสถานะกำลังโหลด
                output.innerHTML = '';
                
                // อ่านข้อมูลแบบ Stream
                reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';
                
                while (true) {
                    const { done, value } = await reader.read();
                    
                    if (done) break;
                    
                    // แปลงข้อมูลเป็น text
                    buffer += decoder.decode(value, { stream: true });
                    
                    // แยกวิเคราะห์ข้อมูล SSE
                    const lines = buffer.split('\n');
                    buffer = lines.pop() || '';
                    
                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            const data = line.slice(6);
                            
                            // ข้ามข้อมูล [DONE]
                            if (data === '[DONE]') continue;
                            
                            try {
                                const json =