Chat about this codebase

AI-powered code exploration

Online

Project Overview

Zot-ChatBot integrates a Node.js/Express backend with a static, dark-themed front-end to deliver AI-powered chat and content-generation in the browser. It leverages Google GenAI models to process text prompts, multi-turn conversations, and image inputs, simplifying the creation of interactive assistant experiences.

Problems It Solves

  • Rapid AI integration: Exposes text-generation and chat endpoints over HTTP.
  • Multimodal inputs: Accepts text, voice, image or file uploads in a single UI.
  • Unified assistant interface: Combines prompt handling, chat history, and settings into one browser application.

High-Level Architecture

Backend (index.js)

  • Uses Express to serve API routes and static assets.
  • Key routes:
    • POST /generate-text – single-prompt text generation
    • POST /chat – multi-message chat sessions
    • POST /generate-text-from-image – OCR + generative response

Front-end (public/index.html + public/script.js)

  • HTML/CSS: Dark-themed chat interface with header, message pane, input controls and settings modal.
  • JavaScript: Handles user input (text, speech, files), persona selection, and invokes backend APIs via fetch. Renders AI responses in real time.

Workflow Example

  1. User types or speaks a message.
  2. script.js sends a POST request to /chat with the message history.
  3. Express handler forwards prompts to Google GenAI, receives a response.
  4. Server returns JSON; script.js updates the chat window.

Starting the Server

// index.js
const express = require('express');
const app = express();
app.use(express.json());
app.use(express.static('public'));

// Mount AI endpoints here...
app.post('/chat', async (req, res) => {
  // call Google GenAI with req.body.messages
  res.json({ reply: 'AI response here' });
});

app.listen(3000, () =>
  console.log('Zot-ChatBot listening on http://localhost:3000')
);

Front-end API Call

// public/script.js
async function sendMessage(messages) {
  const response = await fetch('/chat', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ messages })
  });
  const { reply } = await response.json();
  appendMessage('assistant', reply);
}

This architecture lets developers extend personas, customize prompts, add new UI controls, or integrate alternative AI backends with minimal effort.

Quick Start

Get the Zot-ChatBot running locally in minutes. You’ll clone the repo, install dependencies, configure your Google GenAI credentials, then launch the chat UI.

1. Prerequisites

  • Node.js v16 or later
  • A Google Cloud project with Vertex AI API enabled
  • Service-account JSON key with Vertex AI permissions

2. Clone the repo

git clone https://github.com/novafs/Zot-ChatBot.git
cd Zot-ChatBot

3. Install dependencies

npm install

4. Set up Google GenAI credentials

  1. Create or download a service-account key JSON from Google Cloud Console.

  2. Point the SDK to your key file:

    export GOOGLE_APPLICATION_CREDENTIALS="/full/path/to/your-key.json"
    
  3. (Optional) Override defaults via environment variables:

    export GOOGLE_PROJECT_ID="your-gcp-project-id"
    export GOOGLE_LOCATION="us-central1"        # default region for Vertex AI
    export TEXT_MODEL="text-bison@001"          # text generation model
    export IMAGE_MODEL="vision-gecko@001"       # image-based generation model
    

5. Run the server

Use npm scripts to start the Express server:

npm start
# or, to auto-reload on changes:
npm run dev

By default, the server listens on port 3000.

6. Open the chat UI

In your browser, navigate to:
http://localhost:3000
You can now send prompts, carry on conversations, or upload images for GenAI-powered responses.

Using Zot-ChatBot

Zot-ChatBot provides a web-based chat interface with dynamic personas, image-based prompts, and persistent settings. This guide shows you how to send messages, switch personas, upload images, and manage your conversation.

1. Accessing the Chat Interface

  1. Start the server (npm start) and open http://localhost:3000 in your browser.
  2. The main layout includes:
    • Chat window: displays user and bot messages.
    • Input bar: type your text prompt.
    • Send button (⏵): submits your message.
    • Settings button (⚙️): opens persona and appearance options.
    • Clear chat button (🗑️): resets the conversation.

2. Sending Text Messages

• Click the input bar at the bottom, type your question or instruction, then press Enter or click ⏵.
• Zot-ChatBot streams responses in real time.
• Example prompt:
“Explain the observer pattern in JavaScript with a code sample.”

3. Uploading Images for AI-Driven Text

Use the image upload feature to generate captions, descriptions, or analyses.

  1. Click the “Upload Image” icon (📷) next to the input bar.
  2. Select an image file (PNG, JPG, GIF).
  3. Enter your prompt in the text field (e.g., “Write a creative caption for this photo”).
  4. Click Send to receive an AI-generated response based on both the image and prompt.

4. Switching Personas

Zot-ChatBot lets you tailor the assistant’s tone and expertise.

  1. Click Settings (⚙️) → “Persona” dropdown.
  2. Choose one of:
    – Default: friendly generalist
    – Code: expert programmer
    – Design: creative UI/UX consultant
    – Research: factual research assistant
    – Creative: imaginative writing partner
  3. Click Save. The choice persists across browser sessions.
  4. The next message you send uses the selected persona’s style.

5. Clearing or Resetting the Conversation

• Click the trash icon (🗑️) in the header to clear all messages.
• Clearing resets the context; the assistant starts fresh.
• Persona and theme settings remain intact.

6. Keyboard Shortcuts

– Enter: send message
– Ctrl + K (or ⌘ + K on Mac): focus input bar
– Esc: close settings modal

7. Troubleshooting & Tips

• If the bot doesn’t respond, check the server console for errors.
• Large image files may slow down uploads—keep images under 5 MB.
• Use concise prompts for faster, more focused answers.
• Refresh the page to reload the latest build after code changes.

With these controls, you can interact naturally with Zot-ChatBot, leverage AI for text and image tasks, and customize the assistant’s tone to suit your needs.

Customization & Deployment

This section shows how to adapt Zot-ChatBot: adjust GenAI parameters, tweak the UI, change hosting ports, and deploy to Render, Vercel, or a VPS.

1. Tweak GenAI Model Parameters

Zot-ChatBot’s Express server reads model settings from environment variables or defaults in index.js.

// index.js (excerpt)
const genAIOptions = {
  model: process.env.GENAI_MODEL || 'models/text-bison-001',
  temperature: parseFloat(process.env.GENAI_TEMP) || 0.7,
  maxTokens: parseInt(process.env.GENAI_MAX_TOKENS) || 512,
};

// Generate-text route uses these options
app.post('/generate-text', async (req, res) => {
  const prompt = req.body.prompt;
  const response = await genAI.generateText({ prompt, ...genAIOptions });
  res.json({ text: response.text });
});

Override defaults by exporting env vars:

export GENAI_MODEL="models/text-bison-002"
export GENAI_TEMP=0.3
export GENAI_MAX_TOKENS=256
node index.js

For per-request overrides, extend the route to accept temperature and maxTokens from req.body.

2. Customize UI Styles & Behavior

a. Edit Styles

Override CSS variables in public/style.css:

:root {
  --primary-color: #4A90E2;
  --bg-color: #f5f5f5;
  --text-color: #333;
}

/* Example: change chat bubble color */
.message.bot {
  background: var(--primary-color);
  color: #fff;
}

b. Modify Personas & Endpoints

In public/script.js, adjust persona list and backend URL:

// script.js (excerpt)
const API_BASE = process.env.API_BASE_URL || 'http://localhost:3000';
const personas = [
  { name: 'Tutor', prompt: 'You are a friendly tutor...' },
  { name: 'Coach', prompt: 'You are a life coach...' } // added
];

// Populate selector
personas.forEach(p => {
  const opt = new Option(p.name, p.prompt);
  personaSelect.add(opt);
});

You can also swap endpoints:

// Use a custom chat endpoint
fetch(`${API_BASE}/custom-chat`, { method: 'POST', body: JSON.stringify({ messages }) });

3. Configure Hosting Port

Express reads PORT env var in index.js:

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server runs on port ${PORT}`));

Launch on a different port:

PORT=8080 npm start

4. Deploy to Render

Create render.yaml at repo root:

services:
  - type: web
    name: zot-chatbot
    env: node
    plan: free
    buildCommand: npm install
    startCommand: npm start
    envVars:
      - key: PORT
        value: "10000"
      - key: GENAI_MODEL
        value: "models/text-bison-001"

Push to your Render-linked Git branch. Render installs deps and runs npm start.

5. Deploy to Vercel

Add vercel.json:

{
  "version": 2,
  "builds": [
    { "src": "index.js", "use": "@vercel/node" },
    { "src": "public/**/*", "use": "@vercel/static" }
  ],
  "routes": [
    { "src": "/(.*)", "dest": "/index.js" }
  ],
  "env": {
    "GENAI_MODEL": "models/text-bison-001",
    "GENAI_TEMP": "0.7",
    "GENAI_MAX_TOKENS": "512"
  }
}

Install Vercel CLI, then:

vercel deploy --prod

6. Deploy to a VPS

  1. Clone & install:

    git clone https://github.com/novafs/Zot-ChatBot.git
    cd Zot-ChatBot
    npm install
    
  2. Create a .env in project root:

    PORT=3000
    GENAI_MODEL=models/text-bison-001
    GENAI_TEMP=0.7
    GENAI_MAX_TOKENS=512
    
  3. Start with PM2:

    npm install -g pm2
    pm2 start index.js --name zot-chatbot --env production
    pm2 save
    
  4. Configure Nginx as a reverse proxy:

    /etc/nginx/sites-available/zot-chatbot.conf

    server {
      listen 80;
      server_name your.domain.com;
    
      location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
      }
    }
    

    Enable and reload:

    ln -s /etc/nginx/sites-available/zot-chatbot.conf /etc/nginx/sites-enabled/
    nginx -t && systemctl reload nginx
    

Your Zot-ChatBot instance now runs behind Nginx, scalable via PM2.