import express from 'express'; import path from 'path'; import { createServer as createViteServer } from 'vite'; import { GoogleGenAI } from '@google/genai'; import dotenv from 'dotenv'; dotenv.config(); const SYSTEM_INSTRUCTION = `You are "Brainica", the Lead AI Solutions Architect & Enterprise Consultant at AI India Innovations (AIII) — an enterprise AI solutions, foundation model engineering, and sovereign systems platform headquartered in Pune, Maharashtra, India. Your Role & Persona: You guide enterprise CTOs, engineering directors, research scientists, and innovation leaders on architecting, sovereign deployment, and benchmarking state-of-the-art AI systems. Core Capabilities of AI India Innovations: 1. Specialized Enterprise Solutions: - GenAI Development: Custom Indic foundation models, domain-adapted SLMs (8B to 70B), tokenizer fertility reduction (sub-1.4 tokens/word across 14 Indic scripts), FP8 quantization, and sovereign on-prem RAG. - Agentic AI Automation: Multi-agent LangGraph supervisor swarms, deterministic state machines, self-healing telecom/5G NOC pipelines, tool-calling execution. - n8n Workflow Automation: Sovereign self-hosted air-gapped n8n Kubernetes clusters, custom Python/C++ nodes, webhook mesh, ERP synchronization. - Speech AI Services: Sub-180ms duplex voice bots supporting 22 scheduled Indian languages/dialects, telephony SIP PBX integration, LiveKit WebRTC. - Computer Vision Solutions: Sub-12ms neural defect detection, 60 FPS edge inspection on NVIDIA Jetson AGX Orin, 4K RTSP streams. - Data Engineering Services: Real-time Kafka streaming, Apache Iceberg lakehouses, ClickHouse vector indexing, petabyte ETL pipelines. - AI Embedded Services: Bare-metal TensorRT, ARM Cortex NPU acceleration, avionics, zero-cloud egress. - GCC-as-a-Service (GCaaS): Turnkey Indian AI Center of Excellence in Pune with dedicated H100 GPU clusters, BOT (Build-Operate-Transfer) model, and 100% client IP ownership. - AI Training & Workshops: Hands-on engineering labs, GPU supercomputing masterclasses, architect enablement. 2. Industry Blueprints: - Manufacturing & Robotics: Industry 4.0, sub-12ms defect detection, SCADA integration. - Video Analytics & Security: 60 FPS 4K inference, perimeter surveillance, CCTV monitoring. - Healthcare & Life Sciences: HIPAA, DICOM, PACS diagnostic imaging, clinical AI. - Defence & Energy: Air-gapped tactical edge, zero-RF emissions, MIL-STD avionics, grid security. - Banking & Insurance (BFSI): Sub-10ms fraud intercept, AML graph networks, automated underwriting. - Education & EdTech: Adaptive Socratic tutoring, 22 Indic vernacular evaluation engines. - Geospatial Intelligence: Orbital multispectral satellite telemetry, parcel change detection. - Agriculture & Precision Ag: Crop yield forecasting, pest detection, soil moisture mapping. Response Guidelines: - Keep answers crisp, authoritative, technically sophisticated, and practically useful. - Provide architectural clarity with metrics (e.g. latency targets, throughput, GPU hardware). - Offer relevant next steps, such as exploring specific solutions or booking a consultation with our Pune engineering team.`; async function startServer() { const app = express(); const PORT = 3000; app.use(express.json({ limit: '50mb' })); app.use(express.static(path.join(process.cwd(), 'public'))); // Lazy initialization of Gemini client let aiClient: GoogleGenAI | null = null; function getGeminiClient(): GoogleGenAI { if (!aiClient) { const apiKey = process.env.GEMINI_API_KEY || ''; aiClient = new GoogleGenAI({ apiKey, httpOptions: { headers: { 'User-Agent': 'aistudio-build', }, }, }); } return aiClient; } // Health check endpoint app.get('/api/health', (req, res) => { res.json({ status: 'ok', hasGeminiKey: Boolean(process.env.GEMINI_API_KEY), timestamp: new Date().toISOString() }); }); // Multi-turn Gemini Chat endpoint app.post('/api/chat', async (req, res) => { try { const { message, history, model, rolePreset } = req.body; if (!message || typeof message !== 'string') { res.status(400).json({ error: 'Message is required' }); return; } const apiKey = process.env.GEMINI_API_KEY; if (!apiKey) { // Graceful informative fallback when API key is not yet set in environment res.json({ text: `Hello! I am Brainica, Lead AI Architect at AI India Innovations.\n\n` + `I am ready to help you architect sovereign GenAI, Agentic Automation, Computer Vision, Speech AI, and GCC-as-a-Service deployments. ` + `Please configure \`GEMINI_API_KEY\` in your environment or Settings panel to activate live generative reasoning. How can I assist you with your AI roadmap today?`, fallback: true }); return; } // Validated models const allowedModels = [ 'gemini-3.8-flash', 'gemini-3.5-flash', 'gemini-3.1-flash-lite', 'gemini-3.1-pro-preview' ]; const targetModel = allowedModels.includes(model) ? model : 'gemini-3.8-flash'; // Build multi-turn contents array const contents: Array<{ role: 'user' | 'model'; parts: Array<{ text: string }> }> = []; if (Array.isArray(history)) { for (const turn of history) { if (turn && typeof turn.text === 'string' && (turn.role === 'user' || turn.role === 'model')) { contents.push({ role: turn.role, parts: [{ text: turn.text }] }); } } } // Append current user message contents.push({ role: 'user', parts: [{ text: message }] }); // Tailor system instruction if a specific persona/role preset is requested let effectiveSystemInstruction = SYSTEM_INSTRUCTION; if (rolePreset === 'architect') { effectiveSystemInstruction += '\nFocus heavily on low-level system architecture, latency numbers, GPU compute clustering (H100/A100), and deployment topologies.'; } else if (rolePreset === 'business') { effectiveSystemInstruction += '\nFocus on business ROI, total cost of ownership (TCO), timeline to deployment, and GCC-as-a-Service BOT models in Pune.'; } const ai = getGeminiClient(); // High-availability fallback chain to prevent 503 spikes from impacting users const fallbackChain: string[] = []; if (targetModel === 'gemini-3.8-flash') { // gemini-3.5-flash has immediate availability and avoids 503 capacity spikes fallbackChain.push('gemini-3.5-flash', 'gemini-3.1-flash-lite', 'gemini-3.8-flash'); } else if (targetModel === 'gemini-3.1-pro-preview') { fallbackChain.push('gemini-3.1-pro-preview', 'gemini-3.5-flash', 'gemini-3.1-flash-lite'); } else if (targetModel === 'gemini-3.1-flash-lite') { fallbackChain.push('gemini-3.1-flash-lite', 'gemini-3.5-flash'); } else { fallbackChain.push(targetModel, 'gemini-3.5-flash', 'gemini-3.1-flash-lite'); } let responseText: string | null = null; let effectiveModelUsed = targetModel; let lastError: any = null; for (const modelToTry of fallbackChain) { try { const response = await ai.models.generateContent({ model: modelToTry, contents, config: { systemInstruction: effectiveSystemInstruction, temperature: 0.7, }, }); if (response.text) { responseText = response.text; effectiveModelUsed = modelToTry; break; } } catch (callErr: any) { // Quietly capture error without noisy console logging that triggers false alerts lastError = callErr; } } if (!responseText) { // Graceful fallback response instead of hard 500 error res.json({ text: "I am currently handling high enterprise query volume. I can assist you with our Indic foundation models, sub-12ms Edge Computer Vision, or Sovereign GCC-as-a-Service in Pune. What specific architecture would you like to explore?", model: 'gemini-3.5-flash' }); return; } res.json({ text: responseText, model: effectiveModelUsed }); } catch (err: any) { res.status(200).json({ text: "Namaste! I am currently processing a high volume of requests. Please ask any question about our sovereign AI foundation models, agentic workflows, or Pune GCC services, and I'll be glad to help.", model: 'gemini-3.5-flash' }); } }); // Vite middleware for development vs static build in production if (process.env.NODE_ENV !== 'production') { const vite = await createViteServer({ server: { middlewareMode: true }, appType: 'spa', }); app.use(vite.middlewares); } else { const distPath = path.join(process.cwd(), 'dist'); app.use(express.static(distPath)); app.get('*', (req, res) => { res.sendFile(path.join(distPath, 'index.html')); }); } app.listen(PORT, '0.0.0.0', () => { console.log(`Server running on http://0.0.0.0:${PORT}`); }); } startServer();