-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbundle26.min.js
More file actions
480 lines (433 loc) · 13.7 KB
/
bundle26.min.js
File metadata and controls
480 lines (433 loc) · 13.7 KB
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
(() => {
// Import marked at the top of the bundle
const marked = require('marked');
// Configure marked for security and features
marked.setOptions({
gfm: true, // GitHub Flavored Markdown
breaks: true, // Convert \n to <br>
sanitize: false, // We'll sanitize HTML ourselves
silent: true // Don't throw errors on invalid markdown
});
// Simple HTML sanitizer
function sanitizeHtml(html) {
const div = document.createElement('div');
div.textContent = html;
return div.innerHTML;
}
// Replace the complex renderMarkdown function with this simple one
function renderMarkdown(text) {
// First sanitize the input
const sanitized = sanitizeHtml(text);
// Then parse markdown and return HTML
return marked(sanitized);
}
class ChatClient {
constructor(hostUrl, apiKey, flowId) {
this.hostUrl = hostUrl;
this.apiKey = apiKey;
this.flowId = flowId;
this.callbacks = {
onMessage: null,
onStatusChange: null
};
console.log('[ChatClient] Initialized with:', { hostUrl, flowId });
}
setCallbacks(callbacks) {
this.callbacks = { ...this.callbacks, ...callbacks };
}
async connect() {
console.log('[ChatClient] Connecting...');
try {
await this.testConnection();
if (this.callbacks.onStatusChange) {
this.callbacks.onStatusChange('CONNECTED');
}
return true;
} catch (error) {
console.error('[ChatClient] Connection failed:', error);
if (this.callbacks.onStatusChange) {
this.callbacks.onStatusChange('DISCONNECTED');
}
return false;
}
}
async testConnection() {
console.log('[ChatClient] Testing connection...');
const headers = this.getHeaders();
try {
const response = await fetch(`${this.hostUrl}/health`, {
method: 'GET',
headers: headers
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('[ChatClient] Health check error:', error);
throw error;
}
}
getHeaders() {
return {
'Content-Type': 'application/json',
'x-api-key': this.apiKey
};
}
async sendMessage(message) {
console.log('[ChatClient] Sending message:', message);
const headers = this.getHeaders();
try {
const response = await fetch(`${this.hostUrl}/api/v1/run/${this.flowId}`, {
method: 'POST',
headers: headers,
body: JSON.stringify({
input_type: "chat",
input_value: message,
output_type: "chat",
session_id: crypto.randomUUID()
})
});
if (!response.ok) {
const errorText = await response.text();
console.error('[ChatClient] Error response:', errorText);
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('[ChatClient] Received response:', data);
if (this.callbacks.onMessage) {
this.callbacks.onMessage(data);
}
return data;
} catch (error) {
console.error('[ChatClient] Error sending message:', error);
throw error;
}
}
}
class LangFlowChat extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.isTyping = false;
}
connectedCallback() {
console.log('[LangFlowChat] Connected to DOM');
const hostUrl = this.getAttribute('host_url');
const apiKey = this.getAttribute('api_key');
const flowId = this.getAttribute('flow_id');
const windowTitle = this.getAttribute('window_title') || 'Chat';
this.client = new ChatClient(hostUrl, apiKey, flowId);
this.messages = [];
this.status = 'DISCONNECTED';
this.client.setCallbacks({
onMessage: (response) => this.handleMessage(response),
onStatusChange: (status) => this.handleStatusChange(status)
});
this.createChatUI(windowTitle);
this.client.connect();
}
createChatUI(windowTitle) {
console.log('[LangFlowChat] Creating UI');
const style = `
.chat-widget {
position: fixed;
bottom: 20px;
right: 20px;
width: 350px;
background: white;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
font-family: Arial, sans-serif;
z-index: 1000;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px;
border-bottom: 1px solid #eee;
}
.status-container {
display: flex;
align-items: center;
gap: 8px;
}
.status-indicator {
width: 8px;
height: 8px;
border-radius: 50%;
background: #ccc;
}
.close-button {
background: none;
border: none;
font-size: 18px;
cursor: pointer;
padding: 5px;
}
.messages {
height: 300px;
overflow-y: auto;
padding: 15px;
}
.message-container {
display: flex;
gap: 12px;
margin-bottom: 15px;
align-items: flex-start;
}
.message {
padding: 12px;
border-radius: 12px;
max-width: 80%;
word-break: break-word;
line-height: 1.4;
}
.message.user {
margin-left: auto;
background: #007bff;
color: white;
border-bottom-right-radius: 4px;
}
.message.assistant {
margin-right: auto;
background: #f1f1f1;
color: #333;
border-bottom-left-radius: 4px;
}
.message a.chat-link {
color: inherit;
text-decoration: underline;
word-break: break-all;
}
.message img {
max-width: 100%;
border-radius: 4px;
margin: 5px 0;
}
.message code {
background: rgba(0,0,0,0.1);
padding: 2px 4px;
border-radius: 4px;
font-family: monospace;
font-size: 0.9em;
}
.message pre {
background: rgba(0,0,0,0.05);
padding: 10px;
border-radius: 4px;
overflow-x: auto;
}
.message pre code {
background: none;
padding: 0;
}
.avatar {
width: 32px;
height: 32px;
border-radius: 50%;
background: #eee;
flex-shrink: 0;
overflow: hidden;
}
.avatar img {
width: 100%;
height: 100%;
object-fit: cover;
}
.typing-indicator {
display: flex;
gap: 4px;
padding: 12px;
background: #f1f1f1;
border-radius: 12px;
border-bottom-left-radius: 4px;
margin-bottom: 15px;
width: fit-content;
}
.typing-dot {
width: 8px;
height: 8px;
background: #666;
border-radius: 50%;
opacity: 0.6;
animation: typing 1.4s infinite;
}
.typing-dot:nth-child(2) { animation-delay: 0.2s; }
.typing-dot:nth-child(3) { animation-delay: 0.4s; }
@keyframes typing {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-4px); }
}
.input-container {
padding: 15px;
border-top: 1px solid #eee;
display: flex;
gap: 10px;
}
.message-input {
flex: 1;
padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 20px;
outline: none;
font-size: 14px;
}
.message-input:focus {
border-color: #007bff;
}
.send-button {
padding: 8px 16px;
background: #007bff;
color: white;
border: none;
border-radius: 20px;
cursor: pointer;
font-size: 14px;
transition: background-color 0.2s;
}
.send-button:hover {
background: #0056b3;
}
`;
const html = `
<style>${style}</style>
<div class="chat-widget">
<div class="header">
<div class="status-container">
<div class="status-indicator"></div>
<span class="title">${windowTitle}</span>
</div>
<button class="close-button">×</button>
</div>
<div class="messages"></div>
<div class="input-container">
<input type="text" class="message-input" placeholder="Type your message...">
<button class="send-button">Send</button>
</div>
</div>
`;
this.shadowRoot.innerHTML = html;
this.setupEventListeners();
}
setupEventListeners() {
console.log('[LangFlowChat] Setting up event listeners');
const input = this.shadowRoot.querySelector('.message-input');
const sendButton = this.shadowRoot.querySelector('.send-button');
const closeButton = this.shadowRoot.querySelector('.close-button');
sendButton.addEventListener('click', () => this.sendMessage());
closeButton.addEventListener('click', () => this.close());
input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
this.sendMessage();
}
});
}
showTypingIndicator() {
if (this.isTyping) return;
this.isTyping = true;
const messagesContainer = this.shadowRoot.querySelector('.messages');
const typingContainer = document.createElement('div');
typingContainer.className = 'message-container typing-message';
typingContainer.innerHTML = `
<div class="avatar">
<img src="https://hebbkx1anhila5yf.public.blob.vercel-storage.com/879-cQrx9a2kw2d0VO4ZsOtv1rMMJpo912.png" alt="Assistant Avatar">
</div>
<div class="typing-indicator">
<div class="typing-dot"></div>
<div class="typing-dot"></div>
<div class="typing-dot"></div>
</div>
`;
messagesContainer.appendChild(typingContainer);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
hideTypingIndicator() {
if (!this.isTyping) return;
this.isTyping = false;
const typingMessage = this.shadowRoot.querySelector('.typing-message');
if (typingMessage) {
typingMessage.remove();
}
}
handleStatusChange(status) {
console.log('[LangFlowChat] Status changed:', status);
this.status = status;
const statusIndicator = this.shadowRoot.querySelector('.status-indicator');
if (statusIndicator) {
const colors = {
CONNECTED: '#28a745',
CONNECTING: '#ffc107',
DISCONNECTED: '#dc3545'
};
statusIndicator.style.background = colors[status] || '#ccc';
}
}
handleMessage(response) {
console.log('[LangFlowChat] Handling message:', response);
try {
const messageText = response.outputs[0].outputs[0].results.message.text;
if (messageText) {
this.hideTypingIndicator();
this.addMessage('assistant', messageText);
} else {
console.error('[LangFlowChat] Could not find message text in response');
this.hideTypingIndicator();
this.addMessage('assistant', 'Sorry, I could not process the response properly.');
}
} catch (error) {
console.error('[LangFlowChat] Error parsing message:', error);
this.hideTypingIndicator();
this.addMessage('assistant', 'Sorry, I could not process the response properly.');
}
}
addMessage(role, content) {
console.log('[LangFlowChat] Adding message:', { role, content });
const messagesContainer = this.shadowRoot.querySelector('.messages');
const messageContainer = document.createElement('div');
messageContainer.className = 'message-container';
let html = '';
if (role === 'assistant') {
html += `
<div class="avatar">
<img src="https://hebbkx1anhila5yf.public.blob.vercel-storage.com/879-cQrx9a2kw2d0VO4ZsOtv1rMMJpo912.png" alt="Assistant Avatar">
</div>
`;
}
const messageElement = document.createElement('div');
messageElement.className = `message ${role}`;
messageElement.innerHTML = renderMarkdown(content);
if (role === 'user') {
messageContainer.appendChild(messageElement);
} else {
messageContainer.innerHTML = html;
messageContainer.appendChild(messageElement);
}
messagesContainer.appendChild(messageContainer);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
async sendMessage() {
const input = this.shadowRoot.querySelector('.message-input');
const message = input.value.trim();
if (!message) return;
console.log('[LangFlowChat] Sending message:', message);
input.value = '';
this.addMessage('user', message);
this.showTypingIndicator();
try {
await this.client.sendMessage(message);
} catch (error) {
console.error('[LangFlowChat] Failed to send message:', error);
this.hideTypingIndicator();
this.addMessage('assistant', 'Sorry, there was an error sending your message.');
}
}
close() {
console.log('[LangFlowChat] Closing widget');
this.remove();
}
}
customElements.define('langflow-chat', LangFlowChat);
console.log('[Bundle] LangFlow Chat Widget loaded and registered');
})();