File size: 9,066 Bytes
d326834
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RAG Chat Demo</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background: #f5f5f5;
            padding: 20px;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        .panel {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            padding: 20px;
            display: flex;
            flex-direction: column;
        }
        h2 {
            color: #333;
            margin-bottom: 15px;
            font-size: 18px;
            border-bottom: 2px solid #007bff;
            padding-bottom: 10px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            color: #555;
            font-weight: 500;
            font-size: 14px;
        }
        input[type="text"], textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-family: inherit;
            font-size: 14px;
            resize: none;
        }
        input[type="text"]:focus, textarea:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
        }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 500;
            font-size: 14px;
            transition: background 0.2s;
        }
        button:hover { background: #0056b3; }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .output {
            flex: 1;
            background: #f9f9f9;
            border: 1px solid #eee;
            border-radius: 4px;
            padding: 15px;
            overflow-y: auto;
            max-height: 400px;
            font-size: 14px;
            line-height: 1.6;
            color: #333;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        .status {
            font-size: 12px;
            color: #666;
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid #eee;
        }
        .status.success { color: #28a745; }
        .status.error { color: #dc3545; }
        @media (max-width: 900px) {
            .container { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
<div class="container">
    <!-- Panel 1: Non-streaming (JSON) -->
    <div class="panel">
        <h2>📤 Non-Streaming (JSON)</h2>
        <div class="form-group">
            <label>Session ID:</label>
            <input type="text" id="sessionNonStream" value="user_session_1" />
        </div>
        <div class="form-group">
            <label>Message:</label>
            <input type="text" id="messageNonStream" placeholder="Nhập câu hỏi..." />
        </div>
        <button onclick="sendNonStream()">Gửi (JSON Response)</button>
        <div class="output" id="outputNonStream">Đợi phản hồi...</div>
        <div class="status" id="statusNonStream"></div>
    </div>

    <!-- Panel 2: Streaming (SSE) -->
    <div class="panel">
        <h2>📨 Streaming (SSE)</h2>
        <div class="form-group">
            <label>Session ID:</label>
            <input type="text" id="sessionStream" value="user_session_1" />
        </div>
        <div class="form-group">
            <label>Message:</label>
            <input type="text" id="messageStream" placeholder="Nhập câu hỏi..." />
        </div>
        <button onclick="sendStream()" id="btnStream">Gửi (Streaming)</button>
        <div class="output" id="outputStream">Đợi phản hồi...</div>
        <div class="status" id="statusStream"></div>
    </div>
</div>

<script>
const API_BASE = "http://localhost:8000";

// Non-streaming: POST /chat (JSON response)
async function sendNonStream() {
    const sessionId = document.getElementById('sessionNonStream').value.trim();
    const message = document.getElementById('messageNonStream').value.trim();
    
    if (!message) {
        setStatus('statusNonStream', 'Nhập tin nhắn', 'error');
        return;
    }
    
    const outputDiv = document.getElementById('outputNonStream');
    const statusDiv = document.getElementById('statusNonStream');
    outputDiv.textContent = 'Đang xử lý...';
    statusDiv.textContent = '';
    
    try {
        const response = await fetch(`${API_BASE}/chat`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ session_id: sessionId, message })
        });
        
        if (!response.ok) {
            const err = await response.json();
            throw new Error(err.detail || 'Lỗi server');
        }
        
        const data = await response.json();
        outputDiv.textContent = data.response || 'Không có phản hồi';
        setStatus('statusNonStream', '✅ Hoàn thành', 'success');
    } catch (err) {
        outputDiv.textContent = `❌ Lỗi: ${err.message}`;
        setStatus('statusNonStream', `Lỗi: ${err.message}`, 'error');
    }
}

// Streaming: POST /chat/stream (SSE)
async function sendStream() {
    const sessionId = document.getElementById('sessionStream').value.trim();
    const message = document.getElementById('messageStream').value.trim();
    
    if (!message) {
        setStatus('statusStream', 'Nhập tin nhắn', 'error');
        return;
    }
    
    const outputDiv = document.getElementById('outputStream');
    const statusDiv = document.getElementById('statusStream');
    const btnStream = document.getElementById('btnStream');
    
    outputDiv.textContent = '';
    statusDiv.textContent = 'Đang kết nối...';
    btnStream.disabled = true;
    
    try {
        const response = await fetch(`${API_BASE}/chat/stream`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ session_id: sessionId, message })
        });
        
        if (!response.ok) {
            throw new Error(`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(); // Giữ lại dòng chưa hoàn chỉnh
            
            for (const line of lines) {
                if (line.startsWith('data: ')) {
                    try {
                        const jsonStr = line.substring(6);
                        const data = JSON.parse(jsonStr);
                        
                        if (data.done) {
                            setStatus('statusStream', '✅ Hoàn thành streaming', 'success');
                            btnStream.disabled = false;
                            break;
                        }
                        
                        if (data.delta) {
                            outputDiv.textContent += data.delta;
                            outputDiv.scrollTop = outputDiv.scrollHeight;
                        }
                        
                        if (data.error) {
                            throw new Error(data.error);
                        }
                    } catch (parseErr) {
                        console.warn('Parse error:', parseErr);
                    }
                }
            }
        }
        
        if (!outputDiv.textContent) {
            outputDiv.textContent = 'Không nhận được phản hồi';
        }
        btnStream.disabled = false;
    } catch (err) {
        outputDiv.textContent = `❌ Lỗi: ${err.message}`;
        setStatus('statusStream', `Lỗi: ${err.message}`, 'error');
        btnStream.disabled = false;
    }
}

function setStatus(elementId, message, type) {
    const el = document.getElementById(elementId);
    el.textContent = message;
    el.className = `status ${type}`;
}

// Gợi ý: Nhấn Enter để gửi
document.getElementById('messageNonStream').addEventListener('keypress', e => {
    if (e.key === 'Enter') sendNonStream();
});
document.getElementById('messageStream').addEventListener('keypress', e => {
    if (e.key === 'Enter') sendStream();
});
</script>
</body>
</html>