Spaces:
Running
Running
| // Using DeepSeek Chat API (open source alternative) | |
| const API_URL = 'https://api.deepseek.com/v1/chat/completions'; | |
| // Main chat function with improved error handling | |
| async function callChatAPI(message, imageData = null) { | |
| try { | |
| if (imageData) { | |
| return "I see you've uploaded an image. Currently I can process text messages. Please describe the image to me."; | |
| } | |
| const response = await fetch(API_URL, { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/json' | |
| }, | |
| body: JSON.stringify({ | |
| model: 'deepseek-chat', | |
| messages: [{ | |
| role: 'user', | |
| content: message | |
| }], | |
| temperature: 0.7, | |
| max_tokens: 200 | |
| }) | |
| }); | |
| if (!response.ok) { | |
| throw new Error('API request failed'); | |
| } | |
| const data = await response.json(); | |
| return data.choices[0]?.message?.content || "I didn't get a response. Please try again."; | |
| } catch (error) { | |
| console.error('API Error:', error); | |
| return "Sorry, I'm having trouble connecting to the AI service. Please try again later."; | |
| } | |
| } | |
| // Utility function to convert file to base64 | |
| function fileToBase64(file) { | |
| return new Promise((resolve, reject) => { | |
| const reader = new FileReader(); | |
| reader.readAsDataURL(file); | |
| reader.onload = () => resolve(reader.result); | |
| reader.onerror = error => reject(error); | |
| }); | |
| } | |
| // Initialize chat with welcome message | |
| document.addEventListener('DOMContentLoaded', () => { | |
| const chatContainer = document.getElementById('chat-container'); | |
| if (chatContainer && chatContainer.children.length === 1) { | |
| const welcomeMsg = `Hello! I'm your AI assistant. How can I help you today? I can: | |
| - Answer questions | |
| - Explain concepts | |
| - Help with coding | |
| - Provide suggestions | |
| Try asking me anything!`; | |
| const messageDiv = document.createElement('div'); | |
| messageDiv.className = 'flex justify-start mb-4'; | |
| messageDiv.innerHTML = ` | |
| <div class="bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-white rounded-lg rounded-bl-none p-3 max-w-xs"> | |
| ${marked.parse(welcomeMsg)} | |
| </div> | |
| `; | |
| chatContainer.appendChild(messageDiv); | |
| } | |
| }); | |