File size: 10,545 Bytes
3c5e53a
 
c827077
 
 
 
 
3c5e53a
 
 
 
 
c827077
 
3c5e53a
 
c827077
3c5e53a
c827077
3c5e53a
 
 
 
 
3a36de8
 
 
3c5e53a
3a36de8
 
 
 
 
 
 
 
 
3c5e53a
 
 
 
 
 
 
 
 
 
 
c827077
3a36de8
 
c827077
3c5e53a
c827077
3a36de8
 
 
 
 
 
 
 
 
 
 
 
 
c827077
3c5e53a
 
 
 
c827077
3c5e53a
 
 
c827077
3c5e53a
 
c827077
 
3c5e53a
c827077
3c5e53a
 
 
 
 
 
 
 
 
 
c827077
 
 
 
 
3c5e53a
 
 
 
 
 
 
 
 
c827077
 
 
 
3c5e53a
c827077
 
 
 
3c5e53a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a36de8
3c5e53a
 
3a36de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c5e53a
 
3a36de8
 
 
 
c827077
3c5e53a
 
 
c827077
 
 
 
 
3c5e53a
 
 
 
c827077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c5e53a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c827077
 
 
 
 
 
 
3c5e53a
c827077
 
 
 
 
 
3c5e53a
 
 
c827077
 
3c5e53a
 
 
 
c827077
 
 
 
 
 
3c5e53a
c827077
3c5e53a
 
 
 
 
c827077
 
 
 
 
 
3c5e53a
c827077
3c5e53a
 
 
 
 
c827077
3c5e53a
c827077
 
 
3c5e53a
c827077
 
3c5e53a
 
 
 
c827077
 
 
 
 
 
3c5e53a
c827077
3c5e53a
 
 
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
class AIChat extends HTMLElement {
  connectedCallback() {
    this.messages = [];
    this.model = '';
    this.apiKey = '';
    this.isTyping = false;
this.attachShadow({ mode: 'open' });
    this.shadowRoot.innerHTML = `
      <style>
        .chat-container {
          background: white;
          border-radius: 0.5rem;
          box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
          height: 500px;
          display: flex;
          flex-direction: column;
          border: 1px solid #e5e7eb;
        }
.chat-header {
          padding: 1rem;
          border-bottom: 1px solid #e5e7eb;
          font-weight: 600;
          display: flex;
          align-items: center;
          background: #f9fafb;
          border-top-left-radius: 0.5rem;
          border-top-right-radius: 0.5rem;
        }
        .chat-header select {
          background: white;
          border: 1px solid #e5e7eb;
          border-radius: 0.375rem;
          padding: 0.25rem 0.5rem;
          font-size: 0.875rem;
          margin-left: 0.5rem;
        }
.chat-messages {
          flex: 1;
          overflow-y: auto;
          padding: 1rem;
          display: flex;
          flex-direction: column;
          gap: 0.75rem;
        }
        .message {
          max-width: 80%;
          padding: 0.75rem 1rem;
          border-radius: 1rem;
          line-height: 1.5;
          word-wrap: break-word;
          white-space: pre-wrap;
          box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
        }
.message pre {
          background: rgba(0,0,0,0.05);
          padding: 0.5rem;
          border-radius: 0.25rem;
          overflow-x: auto;
          margin: 0.5rem 0;
        }
        .message code {
          font-family: monospace;
          background: rgba(0,0,0,0.05);
          padding: 0.2rem 0.4rem;
          border-radius: 0.2rem;
          font-size: 0.9em;
        }
        .user-message {
          align-self: flex-end;
          background: #4f46e5;
          color: white;
          border-bottom-right-radius: 0.25rem;
          margin-left: 20%;
        }
        .ai-message {
          align-self: flex-start;
          background: #f9fafb;
          color: #111827;
          border-bottom-left-radius: 0.25rem;
          margin-right: 20%;
          border: 1px solid #e5e7eb;
        }
.chat-input {
          display: flex;
          padding: 1rem;
          border-top: 1px solid #e5e7eb;
        }
        .chat-input input {
          flex: 1;
          padding: 0.75rem 1rem;
          border: 1px solid #e5e7eb;
          border-radius: 0.375rem;
          outline: none;
          transition: border-color 0.2s;
        }
        .chat-input input:focus {
          border-color: #4f46e5;
          box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }
        .chat-input button {
          margin-left: 0.5rem;
          padding: 0.75rem 1.5rem;
          background: #4f46e5;
          color: white;
          border: none;
          border-radius: 0.375rem;
          cursor: pointer;
          transition: background 0.2s, transform 0.1s;
        }
        .chat-input button:hover {
          background: #4338ca;
        }
        .chat-input button:active {
          transform: scale(0.98);
        }
.typing-indicator {
          display: flex;
          padding: 0.5rem;
          align-items: center;
          color: #6b7280;
          font-size: 0.875rem;
        }
        .typing-dots {
          display: flex;
          margin-left: 0.5rem;
        }
        .typing-dot {
          width: 0.5rem;
          height: 0.5rem;
          background: #9ca3af;
          border-radius: 50%;
          margin: 0 0.125rem;
          animation: typingAnimation 1.4s infinite ease-in-out;
        }
        .typing-dot:nth-child(1) { animation-delay: 0s; }
        .typing-dot:nth-child(2) { animation-delay: 0.2s; }
        .typing-dot:nth-child(3) { animation-delay: 0.4s; }
        @keyframes typingAnimation {
          0%, 60%, 100% { transform: translateY(0); }
          30% { transform: translateY(-0.25rem); }
        }
      </style>
      <div class="chat-container">
        <div class="chat-header">
          <i data-feather="message-square" class="mr-2"></i>
          <span>AI Chat Assistant</span>
        </div>
        <div class="chat-messages" id="chat-messages"></div>
        <div class="chat-input">
          <input type="text" id="chat-input" placeholder="Type your message...">
          <button id="send-btn">
            <i data-feather="send"></i>
          </button>
        </div>
      </div>
    `;

    this.messages = [];
    this.model = '';
    this.apiKey = '';
    this.isTyping = false;

    this.shadowRoot.getElementById('send-btn').addEventListener('click', () => this.sendMessage());
    this.shadowRoot.getElementById('chat-input').addEventListener('keypress', (e) => {
      if (e.key === 'Enter') this.sendMessage();
    });
  }
  setModel(model, apiKey, modelList = []) {
    this.model = model;
    this.apiKey = apiKey;
    this.modelList = modelList;
    
    // Add model selector to chat header
    const header = this.shadowRoot.querySelector('.chat-header');
    if (modelList.length > 0) {
      const select = document.createElement('select');
      select.className = 'ml-4 px-2 py-1 border rounded text-sm';
      modelList.forEach(m => {
        const option = document.createElement('option');
        option.value = m.value;
        option.textContent = m.name;
        if (m.value === model) option.selected = true;
        select.appendChild(option);
      });
      
      select.addEventListener('change', (e) => {
        this.model = e.target.value;
        this.addMessage('ai', `Switched to ${e.target.selectedOptions[0].text}. How can I help you now?`);
      });
      
      header.appendChild(select);
    }
    
    this.addMessage('ai', `You are now chatting with ${this.getModelName(model)}. How can I help you with your server?`);
  }

  getModelName(modelValue) {
    const model = this.modelList.find(m => m.value === modelValue);
    return model ? model.name : modelValue;
  }
  addMessage(sender, text) {
    const messagesContainer = this.shadowRoot.getElementById('chat-messages');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${sender}-message`;
    
    // Format message with markdown-like support
    const formattedText = this.formatMessage(text);
    messageDiv.innerHTML = formattedText;
    
    messagesContainer.appendChild(messageDiv);
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
  }

  formatMessage(text) {
    // Simple markdown formatting
    let formatted = text
      .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') // bold
      .replace(/\*(.*?)\*/g, '<em>$1</em>') // italic
      .replace(/`([^`]+)`/g, '<code>$1</code>') // inline code
      .replace(/```([^`]+)```/gs, '<pre>$1</pre>') // code blocks
      .replace(/\n/g, '<br>'); // line breaks

    // Convert URLs to links
    formatted = formatted.replace(
      /(https?:\/\/[^\s]+)/g, 
      '<a href="$1" target="_blank" rel="noopener noreferrer" class="text-indigo-600 hover:underline">$1</a>'
    );

    return formatted;
  }
showTypingIndicator() {
    const messagesContainer = this.shadowRoot.getElementById('chat-messages');
    const typingDiv = document.createElement('div');
    typingDiv.className = 'typing-indicator';
    typingDiv.id = 'typing-indicator';
    typingDiv.innerHTML = `
      <span>AI is typing</span>
      <div class="typing-dots">
        <div class="typing-dot"></div>
        <div class="typing-dot"></div>
        <div class="typing-dot"></div>
      </div>
    `;
    messagesContainer.appendChild(typingDiv);
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
  }

  hideTypingIndicator() {
    const typingIndicator = this.shadowRoot.getElementById('typing-indicator');
    if (typingIndicator) {
      typingIndicator.remove();
    }
  }
  async sendMessage() {
    // Add loading state to send button
    const sendBtn = this.shadowRoot.getElementById('send-btn');
    const originalBtnHTML = sendBtn.innerHTML;
    sendBtn.innerHTML = '<i data-feather="loader" class="animate-spin"></i>';
    sendBtn.disabled = true;
    feather.replace();
const input = this.shadowRoot.getElementById('chat-input');
    const message = input.value.trim();
    if (!message) return;
    
    if (!this.model || !this.apiKey) {
      this.addMessage('ai', 'Please configure your AI settings first (API key and model)');
      return;
    }

    input.value = '';
    this.addMessage('user', message);
    input.focus(); // Keep focus on input after sending
this.showTypingIndicator();
    this.isTyping = true;

    try {
      // Simulate API call to HuggingFace
      // Add message history context
      const context = this.messages
        .slice(-4) // Last 2 exchanges (4 messages)
        .map(msg => `${msg.sender === 'user' ? 'User' : 'Assistant'}: ${msg.text}`)
        .join('\n');

      const response = await fetch(`https://api-inference.huggingface.co/models/${this.model}`, {
method: 'POST',
        headers: {
          'Authorization': `Bearer ${this.apiKey}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          inputs: `Previous conversation:\n${context}\n\nUser: ${message}\nAssistant:`,
          parameters: {
            max_new_tokens: 250,
            temperature: 0.7,
            repetition_penalty: 1.2
          }
        })
});

      const data = await response.json();
      this.hideTypingIndicator();
      this.isTyping = false;
      if (data.error) {
        this.addMessage('ai', `Error: ${data.error}. Please check your API key and model selection.`);
      } else {
        let reply = data[0]?.generated_text || "I'm sorry, I couldn't generate a response.";
        // Clean up the response if it includes our prompt
        reply = reply.replace(/.*Assistant:/s, '').trim();
        this.addMessage('ai', reply);
        // Store message in history
        this.messages.push({sender: 'ai', text: reply});
      }
    } catch (error) {
      this.hideTypingIndicator();
      this.isTyping = false;
      this.addMessage('ai', `Connection error: ${error.message}. Please check your internet connection.`);
    } finally {
      // Restore send button
      sendBtn.innerHTML = originalBtnHTML;
      sendBtn.disabled = false;
      feather.replace();
    }
}
}

customElements.define('ai-chat', AIChat);