File size: 12,858 Bytes
863f653 1395cc4 2b4dda3 ad45554 7940110 ad45554 863f653 1395cc4 863f653 2b4dda3 863f653 2b4dda3 7940110 2b4dda3 7940110 2b4dda3 1395cc4 863f653 2b4dda3 863f653 7940110 863f653 2b4dda3 1395cc4 863f653 1395cc4 863f653 1395cc4 863f653 2b4dda3 1395cc4 2b4dda3 1395cc4 2b4dda3 7940110 2b4dda3 7940110 2b4dda3 1395cc4 7940110 863f653 2b4dda3 1395cc4 863f653 1395cc4 2b4dda3 1395cc4 2b4dda3 1395cc4 2b4dda3 1395cc4 2b4dda3 1395cc4 863f653 ad45554 863f653 2b4dda3 863f653 1395cc4 2b4dda3 1395cc4 2b4dda3 1395cc4 2b4dda3 1395cc4 863f653 2b4dda3 863f653 1395cc4 2b4dda3 1395cc4 863f653 2b4dda3 863f653 2b4dda3 863f653 1395cc4 2b4dda3 1395cc4 863f653 2b4dda3 1395cc4 2b4dda3 863f653 1395cc4 2b4dda3 1395cc4 863f653 1395cc4 2b4dda3 1395cc4 863f653 2b4dda3 863f653 ad45554 863f653 |
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 |
import React, { useState, useRef, useEffect } from 'react';
import { modelCompanies, allModels, findModelById } from './models/modelConfig';
import { HuggingFaceService } from './services/huggingfaceService';
import './App.css';
// Import Lucide icons
import { createIcons, Brain, Key, Sun, Moon, X, ChevronDown, Cpu, BrainCircuit, Atom, Check, Send, AlertCircle, Sparkles } from 'lucide-react';
function App() {
const [messages, setMessages] = useState([]);
const [inputValue, setInputValue] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [isDarkMode, setIsDarkMode] = useState(false);
const [showModelDropdown, setShowModelDropdown] = useState(false);
const [selectedModel, setSelectedModel] = useState('deepseek-v3.2-exp');
const [hfToken, setHfToken] = useState('');
const [showAuth, setShowAuth] = useState(true);
const [error, setError] = useState('');
const messagesEndRef = useRef(null);
const textareaRef = useRef(null);
const dropdownRef = useRef(null);
const currentMessageRef = useRef(null);
// Initialize Lucide icons
useEffect(() => {
createIcons({
icons: {
Brain,
Key,
Sun,
Moon,
X,
ChevronDown,
Cpu,
BrainCircuit,
Atom,
Check,
Send,
AlertCircle,
Sparkles
}
});
}, []);
// Check for stored token
useEffect(() => {
const storedToken = localStorage.getItem('hf_token');
if (storedToken) {
setHfToken(storedToken);
setShowAuth(false);
}
}, []);
// Scroll to bottom
useEffect(() => {
scrollToBottom();
}, [messages]);
// Close dropdown when clicking outside
useEffect(() => {
const handleClickOutside = (event) => {
if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
setShowModelDropdown(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
// Auto-resize textarea
useEffect(() => {
if (textareaRef.current) {
textareaRef.current.style.height = 'auto';
textareaRef.current.style.height = Math.min(textareaRef.current.scrollHeight, 200) + 'px';
}
}, [inputValue]);
// Toggle dark mode
useEffect(() => {
if (isDarkMode) {
document.body.classList.add('dark');
} else {
document.body.classList.remove('dark');
}
}, [isDarkMode]);
const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
};
const handleTokenSubmit = () => {
if (!hfToken.trim()) {
setError('Please enter your Hugging Face token');
return;
}
if (!hfToken.startsWith('hf_')) {
setError('Please enter a valid Hugging Face token');
return;
}
localStorage.setItem('hf_token', hfToken.trim());
setShowAuth(false);
setError('');
};
const handleClearToken = () => {
localStorage.removeItem('hf_token');
setHfToken('');
setShowAuth(true);
setMessages([]);
};
const handleSendMessage = async () => {
if (!inputValue.trim() || isLoading || !hfToken) return;
const userMessage = {
id: Date.now(),
content: inputValue.trim(),
role: 'user',
timestamp: new Date()
};
setMessages(prev => [...prev, userMessage]);
setInputValue('');
setIsLoading(true);
setError('');
// Create assistant message for streaming
const assistantMessageId = Date.now() + 1;
const assistantMessage = {
id: assistantMessageId,
content: '',
role: 'assistant',
timestamp: new Date()
};
setMessages(prev => [...prev, assistantMessage]);
currentMessageRef.current = assistantMessageId;
try {
const currentModelConfig = findModelById(selectedModel);
const hfService = new HuggingFaceService(hfToken);
const chatMessages = [
...messages.filter(msg => msg.role !== 'assistant' || msg.content),
userMessage
].map(msg => ({
role: msg.role,
content: msg.content
}));
await hfService.streamChatCompletion(
chatMessages,
currentModelConfig,
(chunk) => {
setMessages(prev => prev.map(msg =>
msg.id === assistantMessageId
? { ...msg, content: msg.content + (chunk || '') }
: msg
));
},
() => {
setIsLoading(false);
currentMessageRef.current = null;
},
(errorMsg) => {
setError(`Model error: ${errorMsg}`);
setIsLoading(false);
currentMessageRef.current = null;
setMessages(prev => prev.filter(msg => msg.id !== assistantMessageId));
}
);
} catch (err) {
console.error('Chat error:', err);
setError(`Failed to connect to AI model: ${err.message}`);
setIsLoading(false);
currentMessageRef.current = null;
setMessages(prev => prev.filter(msg => msg.id !== assistantMessageId));
}
};
const handleKeyPress = (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSendMessage();
}
};
const handleModelSelect = (modelId) => {
setSelectedModel(modelId);
setShowModelDropdown(false);
};
const currentModel = findModelById(selectedModel);
const groupedModels = modelCompanies;
// Auth Modal
if (showAuth) {
return (
<div className={`App ${isDarkMode ? 'dark' : ''}`}>
<div className="auth-modal">
<div className="auth-content">
<div className="logo" style={{ justifyContent: 'center', marginBottom: '24px' }}>
<i data-lucide="brain"></i>
<span style={{ fontSize: '28px' }}>SynapseAI</span>
</div>
<h2 className="auth-title">Welcome to SynapseAI</h2>
<p className="auth-description">
Enter your Hugging Face token to start chatting with AI models
</p>
{error && (
<div className="error-message">
<i data-lucide="alert-circle"></i>
{error}
</div>
)}
<div className="auth-input">
<input
type="password"
className="input"
placeholder="Enter your Hugging Face token (hf_...)"
value={hfToken}
onChange={(e) => setHfToken(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleTokenSubmit()}
/>
</div>
<div className="auth-actions">
<button className="btn primary" onClick={handleTokenSubmit}>
<i data-lucide="key"></i>
Start Chatting
</button>
</div>
<div className="token-info">
<h4>How to get your Hugging Face token:</h4>
<ol>
<li>Go to <a href="https://huggingface.co" target="_blank" rel="noopener noreferrer">huggingface.co</a></li>
<li>Sign in to your account</li>
<li>Go to Settings → Access Tokens</li>
<li>Create a new token with read permissions</li>
<li>Copy and paste it here</li>
</ol>
</div>
</div>
</div>
</div>
);
}
return (
<div className={`App ${isDarkMode ? 'dark' : ''}`}>
<div className="chat-container">
{/* Header */}
<header className="header">
<div className="logo">
<i data-lucide="brain"></i>
<span>SynapseAI</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
<div className="token-display">
<i data-lucide="key"></i>
<span className="token-text">Token: {hfToken.substring(0, 10)}...</span>
<div className="clear-token" onClick={handleClearToken} title="Clear token">
<i data-lucide="x"></i>
</div>
</div>
<button
className="btn ghost theme-toggle"
onClick={() => setIsDarkMode(!isDarkMode)}
>
<i data-lucide={isDarkMode ? "sun" : "moon"}></i>
</button>
</div>
</header>
{/* Chat Messages */}
<div className="chat-messages">
{messages.length === 0 && (
<div className="welcome-message">
<div className="card" style={{ maxWidth: '600px', margin: '0 auto' }}>
<i data-lucide="sparkles"></i>
<h2 style={{ marginBottom: '8px', fontSize: '24px', fontWeight: '600' }}>Welcome to SynapseAI</h2>
<p style={{ color: '#71717a', lineHeight: '1.5', marginBottom: '16px' }}>
Start a conversation with AI models. Select your preferred model below.
</p>
<p style={{ fontSize: '14px', color: '#a1a1aa' }}>
Current Model: <strong>{currentModel?.name}</strong> by {currentModel?.company}
</p>
</div>
</div>
)}
{messages.map((message) => (
<div key={message.id} className={`message ${message.role}`}>
<div className="message-content">
{message.content || (message.role === 'assistant' && isLoading && '...')}
</div>
</div>
))}
{isLoading && !currentMessageRef.current && (
<div className="message assistant">
<div className="typing-indicator">
<div className="typing-dot"></div>
<div className="typing-dot"></div>
<div className="typing-dot"></div>
</div>
</div>
)}
<div ref={messagesEndRef} />
</div>
{/* Error Display */}
{error && (
<div className="error-message">
<i data-lucide="alert-circle"></i>
{error}
</div>
)}
{/* Input Area */}
<div className="input-container">
<div className="chat-input-wrapper">
{/* Model Selector */}
<div className="dropdown" ref={dropdownRef}>
<button
className="btn model-selector"
onClick={() => setShowModelDropdown(!showModelDropdown)}
>
<i data-lucide={currentModel?.companyLogo || "cpu"}></i>
<span style={{ flex: 1, textAlign: 'left' }}>{currentModel?.name}</span>
<i data-lucide="chevron-down"></i>
</button>
{showModelDropdown && (
<div className="dropdown-content">
{groupedModels.map((company) => (
<div key={company.id} className="company-section">
<div className="company-header">
<i data-lucide={company.logo}></i>
{company.name}
</div>
{company.models.map((model) => (
<div
key={model.id}
className={`dropdown-item ${selectedModel === model.id ? 'active' : ''}`}
onClick={() => handleModelSelect(model.id)}
>
<div className="model-info">
<div className="model-name">{model.name}</div>
<div className="model-description">{model.description}</div>
</div>
<div className="model-check">
{selectedModel === model.id && <i data-lucide="check"></i>}
</div>
</div>
))}
</div>
))}
</div>
)}
</div>
{/* Chat Input */}
<textarea
ref={textareaRef}
className="input chat-input"
placeholder="Message SynapseAI..."
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
onKeyPress={handleKeyPress}
disabled={isLoading}
rows={1}
/>
{/* Send Button */}
<button
className="send-button"
onClick={handleSendMessage}
disabled={!inputValue.trim() || isLoading}
>
<i data-lucide="send"></i>
</button>
</div>
</div>
</div>
</div>
);
}
export default App; |