|
| 1 | +// ═══════════════════════════════════════════════════════════════════════════════ |
| 2 | +// 🚀 GraTech Commander - AI API Integration (Secure Proxy Version) |
| 3 | +// By Suliman Nazal Alshammari | @Grar00t | @GrAxOS |
| 4 | +// "Building with HONESTY - Not Vaporware" |
| 5 | +// ═══════════════════════════════════════════════════════════════════════════════ |
| 6 | + |
| 7 | +// 🔒 API Configuration - Uses Azure Functions Proxy for security |
| 8 | +const API_CONFIG = { |
| 9 | + // Free demo proxy (rate limited) |
| 10 | + proxyUrl: 'https://gratech-ai-proxy.azurewebsites.net/api/chat', |
| 11 | + |
| 12 | + // Direct Azure (if user has own key) |
| 13 | + directEndpoint: null, |
| 14 | + directKey: null, |
| 15 | + |
| 16 | + apiVersion: '2024-08-01-preview', |
| 17 | + |
| 18 | + // Available Models |
| 19 | + models: { |
| 20 | + 'gpt-4o': { name: 'GPT-4o', icon: '🚀', description: 'الأسرع والأذكى' }, |
| 21 | + 'gpt-4.1': { name: 'GPT-4.1', icon: '💬', description: 'متوازن' }, |
| 22 | + 'gpt-35-turbo': { name: 'GPT-3.5', icon: '⚡', description: 'اقتصادي' } |
| 23 | + } |
| 24 | +}; |
| 25 | + |
| 26 | +// 🎯 Rate Limiting for Free Demo |
| 27 | +const RATE_LIMIT = { |
| 28 | + maxRequestsPerHour: 20, |
| 29 | + maxTokensPerRequest: 2000, |
| 30 | + requests: [], |
| 31 | + |
| 32 | + canMakeRequest() { |
| 33 | + const now = Date.now(); |
| 34 | + const hourAgo = now - (60 * 60 * 1000); |
| 35 | + this.requests = this.requests.filter(t => t > hourAgo); |
| 36 | + return this.requests.length < this.maxRequestsPerHour; |
| 37 | + }, |
| 38 | + |
| 39 | + recordRequest() { |
| 40 | + this.requests.push(Date.now()); |
| 41 | + localStorage.setItem('gratech_requests', JSON.stringify(this.requests)); |
| 42 | + }, |
| 43 | + |
| 44 | + getRemainingRequests() { |
| 45 | + const now = Date.now(); |
| 46 | + const hourAgo = now - (60 * 60 * 1000); |
| 47 | + this.requests = this.requests.filter(t => t > hourAgo); |
| 48 | + return this.maxRequestsPerHour - this.requests.length; |
| 49 | + }, |
| 50 | + |
| 51 | + init() { |
| 52 | + const saved = localStorage.getItem('gratech_requests'); |
| 53 | + if (saved) { |
| 54 | + try { |
| 55 | + this.requests = JSON.parse(saved); |
| 56 | + } catch(e) { |
| 57 | + this.requests = []; |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | +}; |
| 62 | + |
| 63 | +// 🤖 AI Chat Function |
| 64 | +async function sendToAI(message, model = 'gpt-4o') { |
| 65 | + // Check if user has custom key |
| 66 | + const customKey = localStorage.getItem('gratech_api_key'); |
| 67 | + const customEndpoint = localStorage.getItem('gratech_endpoint'); |
| 68 | + |
| 69 | + if (customKey && customEndpoint) { |
| 70 | + // Use custom key - unlimited |
| 71 | + return await sendWithCustomKey(message, customKey, customEndpoint, model); |
| 72 | + } |
| 73 | + |
| 74 | + // Demo mode - rate limited |
| 75 | + if (!RATE_LIMIT.canMakeRequest()) { |
| 76 | + return { |
| 77 | + success: false, |
| 78 | + error: '⚠️ وصلت للحد الأقصى (20 رسالة/ساعة)\n\n💡 للاستخدام غير المحدود:\n1. أدخل مفتاحك الخاص في الإعدادات\n2. أو انتظر ساعة واحدة' |
| 79 | + }; |
| 80 | + } |
| 81 | + |
| 82 | + // Call the proxy |
| 83 | + try { |
| 84 | + console.log('🚀 Sending to GraTech AI Proxy...'); |
| 85 | + |
| 86 | + const response = await fetch(API_CONFIG.proxyUrl, { |
| 87 | + method: 'POST', |
| 88 | + headers: { |
| 89 | + 'Content-Type': 'application/json', |
| 90 | + }, |
| 91 | + body: JSON.stringify({ |
| 92 | + message: message, |
| 93 | + model: model, |
| 94 | + sessionId: getSessionId() |
| 95 | + }) |
| 96 | + }); |
| 97 | + |
| 98 | + const data = await response.json(); |
| 99 | + |
| 100 | + if (response.ok && data.message) { |
| 101 | + RATE_LIMIT.recordRequest(); |
| 102 | + return { |
| 103 | + success: true, |
| 104 | + message: data.message, |
| 105 | + model: API_CONFIG.models[model]?.name || model, |
| 106 | + remaining: RATE_LIMIT.getRemainingRequests() |
| 107 | + }; |
| 108 | + } else { |
| 109 | + return { |
| 110 | + success: false, |
| 111 | + error: data.error || 'فشل في الاتصال' |
| 112 | + }; |
| 113 | + } |
| 114 | + } catch (error) { |
| 115 | + console.error('API Error:', error); |
| 116 | + |
| 117 | + // Fallback - show demo response |
| 118 | + return getDemoResponse(message, model); |
| 119 | + } |
| 120 | +} |
| 121 | + |
| 122 | +// 🔄 Use Custom API Key (BYOK) - Unlimited |
| 123 | +async function sendWithCustomKey(message, apiKey, endpoint, model = 'gpt-4') { |
| 124 | + const url = `${endpoint}/openai/deployments/${model}/chat/completions?api-version=2024-08-01-preview`; |
| 125 | + |
| 126 | + const body = { |
| 127 | + messages: [ |
| 128 | + { role: 'system', content: 'أنت مساعد ذكي يتحدث العربية بطلاقة. صُنعت بواسطة GraTech 🇸🇦' }, |
| 129 | + { role: 'user', content: message } |
| 130 | + ], |
| 131 | + max_tokens: 4000, |
| 132 | + temperature: 0.7 |
| 133 | + }; |
| 134 | + |
| 135 | + try { |
| 136 | + const response = await fetch(url, { |
| 137 | + method: 'POST', |
| 138 | + headers: { |
| 139 | + 'Content-Type': 'application/json', |
| 140 | + 'api-key': apiKey |
| 141 | + }, |
| 142 | + body: JSON.stringify(body) |
| 143 | + }); |
| 144 | + |
| 145 | + const data = await response.json(); |
| 146 | + |
| 147 | + if (response.ok && data.choices) { |
| 148 | + return { |
| 149 | + success: true, |
| 150 | + message: data.choices[0].message.content, |
| 151 | + model: model, |
| 152 | + unlimited: true |
| 153 | + }; |
| 154 | + } else { |
| 155 | + return { |
| 156 | + success: false, |
| 157 | + error: data.error?.message || 'API Error' |
| 158 | + }; |
| 159 | + } |
| 160 | + } catch (error) { |
| 161 | + return { success: false, error: error.message }; |
| 162 | + } |
| 163 | +} |
| 164 | + |
| 165 | +// 🎮 Demo Response (fallback when proxy is unavailable) |
| 166 | +function getDemoResponse(message, model) { |
| 167 | + const responses = { |
| 168 | + 'شرح': '💡 **شرح:**\n\nهذا سؤال رائع! دعني أشرح لك...\n\n*للحصول على إجابات حقيقية من الذكاء الاصطناعي، يرجى إدخال مفتاح API الخاص بك في الإعدادات.*', |
| 169 | + 'كود': '```javascript\n// مثال كود\nfunction greet() {\n console.log("مرحباً من GraTech!");\n}\n```\n\n*للحصول على كود مخصص، أدخل مفتاح API الخاص بك.*', |
| 170 | + 'default': `🤖 **وضع العرض التوضيحي**\n\nشكراً على تجربة GraTech Commander!\n\n📝 رسالتك: "${message.substring(0, 50)}..."\n\n⚙️ النموذج: ${model}\n\n💡 للحصول على ردود حقيقية من AI:\n1. اذهب للإعدادات ⚙️\n2. أدخل مفتاح Azure OpenAI الخاص بك\n3. استمتع بمحادثات غير محدودة!\n\n🔗 احصل على مفتاح مجاني من:\nhttps://azure.microsoft.com/free/` |
| 171 | + }; |
| 172 | + |
| 173 | + const lowerMsg = message.toLowerCase(); |
| 174 | + let response = responses.default; |
| 175 | + |
| 176 | + if (lowerMsg.includes('شرح') || lowerMsg.includes('explain')) { |
| 177 | + response = responses['شرح']; |
| 178 | + } else if (lowerMsg.includes('كود') || lowerMsg.includes('code')) { |
| 179 | + response = responses['كود']; |
| 180 | + } |
| 181 | + |
| 182 | + RATE_LIMIT.recordRequest(); |
| 183 | + |
| 184 | + return { |
| 185 | + success: true, |
| 186 | + message: response, |
| 187 | + model: API_CONFIG.models[model]?.name || model, |
| 188 | + remaining: RATE_LIMIT.getRemainingRequests(), |
| 189 | + demo: true |
| 190 | + }; |
| 191 | +} |
| 192 | + |
| 193 | +// 🆔 Session ID for rate limiting |
| 194 | +function getSessionId() { |
| 195 | + let sid = localStorage.getItem('gratech_session'); |
| 196 | + if (!sid) { |
| 197 | + sid = 'gt_' + Math.random().toString(36).substr(2, 9); |
| 198 | + localStorage.setItem('gratech_session', sid); |
| 199 | + } |
| 200 | + return sid; |
| 201 | +} |
| 202 | + |
| 203 | +// 📊 Usage Stats |
| 204 | +function getUsageStats() { |
| 205 | + return { |
| 206 | + remaining: RATE_LIMIT.getRemainingRequests(), |
| 207 | + max: RATE_LIMIT.maxRequestsPerHour, |
| 208 | + hasCustomKey: !!(localStorage.getItem('gratech_api_key')) |
| 209 | + }; |
| 210 | +} |
| 211 | + |
| 212 | +// Initialize |
| 213 | +RATE_LIMIT.init(); |
| 214 | + |
| 215 | +// Export for use |
| 216 | +window.GraTechAI = { |
| 217 | + send: sendToAI, |
| 218 | + sendCustom: sendWithCustomKey, |
| 219 | + getStats: getUsageStats, |
| 220 | + models: API_CONFIG.models |
| 221 | +}; |
| 222 | + |
| 223 | +console.log('🚀 GraTech AI Ready!'); |
| 224 | +console.log('📊 Demo mode - Remaining:', RATE_LIMIT.getRemainingRequests(), 'requests'); |
0 commit comments