-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbundle8.min.js
More file actions
249 lines (215 loc) · 7.87 KB
/
bundle8.min.js
File metadata and controls
249 lines (215 loc) · 7.87 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
(() => {
// Debug logging
const debug = {
log: function(...args) {
console.log('[ChatWidget]', ...args);
},
error: function(...args) {
console.error('[ChatWidget]', ...args);
}
};
class ChatClient {
constructor(baseURL, apiKey) {
this.baseURL = baseURL;
this.apiKey = apiKey;
this.callbacks = {
onMessage: null,
onStatusChange: null
};
debug.log('ChatClient initialized with baseURL:', baseURL);
}
setCallbacks(callbacks) {
this.callbacks = { ...this.callbacks, ...callbacks };
}
async connect() {
debug.log('Attempting to connect...');
try {
const response = await this.testConnection();
debug.log('Connection successful:', response);
if (this.callbacks.onStatusChange) {
this.callbacks.onStatusChange('CONNECTED');
}
return true;
} catch (error) {
debug.error('Connection failed:', error);
if (this.callbacks.onStatusChange) {
this.callbacks.onStatusChange('DISCONNECTED');
}
return false;
}
}
async testConnection() {
debug.log('Testing connection...');
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('apikey', this.apiKey);
const response = await fetch(`${this.baseURL}/health`, {
method: 'GET',
headers: headers
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}
async sendMessage(message) {
debug.log('Sending message:', message);
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('apikey', this.apiKey);
try {
const response = await fetch(`${this.baseURL}/chat/completions`, {
method: 'POST',
headers: headers,
body: JSON.stringify({
messages: [{
role: 'user',
content: message
}]
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
debug.log('Received response:', data);
if (this.callbacks.onMessage) {
this.callbacks.onMessage(data);
}
return data;
} catch (error) {
debug.error('Error sending message:', error);
throw error;
}
}
}
class ChatWidget {
constructor(containerId, baseURL, apiKey) {
debug.log('Initializing ChatWidget...');
this.containerId = containerId;
this.client = new ChatClient(baseURL, apiKey);
this.messages = [];
this.status = 'DISCONNECTED';
// Set up client callbacks
this.client.setCallbacks({
onMessage: (response) => this.handleMessage(response),
onStatusChange: (status) => this.handleStatusChange(status)
});
this.initialize();
}
initialize() {
debug.log('Creating chat container...');
// Create container if it doesn't exist
this.container = document.getElementById(this.containerId);
if (!this.container) {
debug.log('Container not found, creating new one...');
this.container = document.createElement('div');
this.container.id = this.containerId;
document.body.appendChild(this.container);
}
this.createChatUI();
this.client.connect();
}
createChatUI() {
debug.log('Creating chat UI...');
const chatHtml = `
<div class="chat-widget" style="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;">
<div style="display: flex; justify-content: space-between; align-items: center; padding: 15px; border-bottom: 1px solid #eee;">
<div style="display: flex; align-items: center; gap: 8px;">
<div class="status-indicator" style="width: 8px; height: 8px; border-radius: 50%; background: #ccc;"></div>
<span style="font-weight: bold;">Chat</span>
</div>
<button class="close-button" style="background: none; border: none; font-size: 18px; cursor: pointer; padding: 5px;">×</button>
</div>
<div class="messages" style="height: 300px; overflow-y: auto; padding: 15px;"></div>
<div style="padding: 15px; border-top: 1px solid #eee;">
<div style="display: flex; gap: 10px;">
<input type="text" class="message-input" placeholder="Type your message..."
style="flex: 1; padding: 8px; border: 1px solid #ddd; border-radius: 4px; outline: none;">
<button class="send-button"
style="padding: 8px 15px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">
Send
</button>
</div>
</div>
</div>
`;
this.container.innerHTML = chatHtml;
this.setupEventListeners();
}
setupEventListeners() {
debug.log('Setting up event listeners...');
const widget = this.container.querySelector('.chat-widget');
const input = widget.querySelector('.message-input');
const sendButton = widget.querySelector('.send-button');
const closeButton = widget.querySelector('.close-button');
sendButton.addEventListener('click', () => this.sendMessage());
closeButton.addEventListener('click', () => this.close());
input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
this.sendMessage();
}
});
}
handleStatusChange(status) {
debug.log('Status changed:', status);
this.status = status;
const statusIndicator = this.container.querySelector('.status-indicator');
if (statusIndicator) {
const colors = {
CONNECTED: '#28a745',
CONNECTING: '#ffc107',
DISCONNECTED: '#dc3545'
};
statusIndicator.style.background = colors[status] || '#ccc';
}
}
handleMessage(response) {
debug.log('Handling message:', response);
if (response.choices && response.choices[0]) {
this.addMessage('assistant', response.choices[0].message.content);
}
}
addMessage(role, content) {
debug.log('Adding message:', { role, content });
const messagesContainer = this.container.querySelector('.messages');
const messageElement = document.createElement('div');
messageElement.style.cssText = `
margin-bottom: 10px;
padding: 8px;
border-radius: 4px;
max-width: 80%;
word-break: break-word;
${role === 'user'
? 'margin-left: auto; background: #007bff; color: white;'
: 'margin-right: auto; background: #f1f1f1;'}
`;
messageElement.textContent = content;
messagesContainer.appendChild(messageElement);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
async sendMessage() {
const input = this.container.querySelector('.message-input');
const message = input.value.trim();
if (!message) return;
debug.log('Sending message:', message);
input.value = '';
this.addMessage('user', message);
try {
await this.client.sendMessage(message);
} catch (error) {
debug.error('Failed to send message:', error);
this.addMessage('assistant', 'Sorry, there was an error sending your message.');
}
}
close() {
debug.log('Closing widget...');
if (this.container) {
this.container.remove();
}
}
}
// Make ChatWidget available globally
window.ChatWidget = ChatWidget;
debug.log('ChatWidget loaded and ready to use');
})();