xAI Chatbot (Howie) Widget

A lightweight chat widget that can be embedded into any page. Users enter their contact details, then engage in a live conversation with the AI assistant, Howie. The implementation consists of three files:

  • index.php – HTML structure & resource links
  • script.js – Client-side logic (UI control, HTTP & WebSocket communications)
  • style.css – Visual styling for the widget

index.php

Defines the HTML scaffold for the chat widget and links the necessary assets.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>xAI Chatbot</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div id="chat-widget">
    <div id="chat-header" onclick="toggleChat()">Chat with Tech</div>
    <div id="chat-container">
      <div id="intro-form">
        <p>Please enter your details to start chatting:</p>
        <input type="text" id="intro-name" placeholder="Your Name" required>
        <input type="email" id="intro-email" placeholder="Your Email" required>
        <input type="tel" id="intro-phone" placeholder="Your Phone" required>
        <button onclick="submitIntro()">Start Chat</button>
      </div>
      <div id="chat-content" style="display: none;">
        <div id="chat-messages"></div>
        <div id="typing-indicator" style="display: none;">Howie is typing...</div>
        <div id="chat-input">
          <input type="text" id="user-input" placeholder="Type your message...">
          <button onclick="sendMessage()">Send</button>
        </div>
      </div>
    </div>
  </div>
  <script src="script.js"></script>
</body>
</html>

Key Elements

Element ID Role
chat-widget Outer wrapper for the entire widget
chat-header Clickable bar to toggle the chat window
chat-container Holds both the intro form and the active chat interface
intro-form Collects name, email, phone before chat starts
chat-content Displays messages and input once user details are submitted
chat-messages Message history area
typing-indicator Shows “Howie is typing…” during AI response generation
chat-input Text input and send button for ongoing conversation

script.js

Manages UI state, captures user input, communicates with the AI backend, and handles message display.

let sessionId = null;
let awaitingContact = false;
let ws = null;
let userInfo = null;
let isAgentChat = false;

function toggleChat() {
  const container = document.getElementById('chat-container');
  if (!container) return console.error('Chat container not found');
  const opening = !container.classList.contains('open');
  container.classList.toggle('open');
  if (!opening && sessionId && !awaitingContact) {
    closeSession();
  } else if (opening && sessionId) {
    connectWebSocket(sessionId);
  }
}

async function submitIntro() {
  const name  = document.getElementById('intro-name').value.trim();
  const email = document.getElementById('intro-email').value.trim();
  const phone = document.getElementById('intro-phone').value.trim();
  if (!name || !email || !phone) {
    return alert('Please fill all fields');
  }
  userInfo = { name, email, phone };
  document.getElementById('intro-form').style.display   = 'none';
  document.getElementById('chat-content').style.display = 'block';

  try {
    const response = await fetch('http://50.57.15.194:3000/chat', {
      method:  'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        message: '',
        session_id: sessionId,
        user_name: userInfo.name,
        user_email: userInfo.email,
        user_phone: userInfo.phone
      })
    });
    const data = await response.json();
    if (data.reply) {
      const messagesDiv = document.getElementById('chat-messages');
      messagesDiv.innerHTML = `<div class="message bot-msg">Howie: ${data.reply}</div>`;
      sessionId = data.session_id;
      localStorage.setItem('chat_session_id', sessionId);
      connectWebSocket(sessionId);
    }
  } catch (error) {
    console.error('Initial greeting error:', error);
    document.getElementById('chat-messages').innerHTML =
      `<div class="message bot-msg">Howie: Failed to connect</div>`;
  }
}

// ... Additional functions: sendMessage(), connectWebSocket(), showContactForm(), submitContact(), closeSession() ...

Core Functions

  • toggleChat() 🛠️
    Opens/closes the chat pane; initiates or terminates session.

  • submitIntro() 📨
    Validates user details, hides intro form, shows chat, sends an empty initial message to start the session.

  • sendMessage() 💬
    Appends user message to the UI, scrolls, then posts it to the AI or routes via WebSocket if transferred to a human agent.

  • connectWebSocket() 🔌
    Establishes a WebSocket to receive live responses or agent messages.

  • showContactForm() & submitContact() 📇
    Display a fallback contact form if no agents are available, then POST details to /submit-contact.

Message Flow

sequenceDiagram
    participant U as User
    participant UI as Browser UI
    participant S as Chat Server
    participant WS as WebSocket

    U->>UI: Click “Chat with Tech”
    UI->>UI: toggleChat()
    U->>UI: Fill details & click Start Chat
    UI->>S: POST /chat {user details, session_id}
    S-->>UI: {reply, session_id}
    UI->>WS: Open WebSocket(session_id)
    loop Conversation
      U->>UI: type & send message
      UI->>S: POST /chat {message, session_id}
      S-->>UI: {reply}
    end

API Endpoint

{
  "title": "Chat Message Endpoint",
  "description": "Sends a user message (or empty initial greeting) and returns a bot reply with a session ID.",
  "method": "POST",
  "baseUrl": "http://50.57.15.194:3000",
  "endpoint": "/chat",
  "headers": [
    {
      "key": "Content-Type",
      "value": "application/json",
      "required": true
    }
  ],
  "pathParams": [],
  "queryParams": [],
  "bodyType": "json",
  "requestBody": "{\n  \"message\": \"Your question here\",\n  \"session_id\": null,\n  \"user_name\": \"Jane Doe\",\n  \"user_email\": \"[email protected]\",\n  \"user_phone\": \"1234567890\"\n}",
  "responses": {
    "200": {
      "description": "Successful reply from Howie",
      "body": "{\n  \"reply\": \"Hello! How can I assist you today?\",\n  \"session_id\": \"abcd1234\"\n}"
    },
    "500": {
      "description": "Server error",
      "body": "{\n  \"error\": \"Internal server error\"\n}"
    }
  }
}

style.css

Provides the visual design for the widget. Though the full stylesheet isn’t shown here, it typically includes:

  • Positioning: Fixed bottom-right corner, high z-index
  • Visibility transitions: .open class toggles height/opacity
  • Header styling: Background color, cursor pointer
  • Message bubbles: .bot-msg vs. .user-msg alignment and colors
  • Input & buttons: Padding, hover states, responsive sizing

Tip: Ensure .open is defined to animate #chat-container smoothly.


Integration & Usage

  1. Copy the entire howie/ folder into your project.
  2. Include the widget where desired:
    <link rel="stylesheet" href="howie/style.css">
    <script src="howie/script.js" defer></script>
    <?php include 'howie/index.php'; ?>
    
  3. Start a PHP server or configure CORS if hosting assets separately.
  4. Run an AI backend on http://50.57.15.194:3000 listening at /chat.

Dependencies & Design Notes

  • Backend: Expects a JSON-based chat API and WebSocket server.
  • Storage: Uses localStorage to persist chat_session_id.
  • Error Handling: Fallback “contact” form if human agent handoff fails.
  • Extensibility:
    • Add OAuth tokens or headers in fetch() calls.
    • Customize UI by extending style.css.
    • Hook into connectWebSocket() events for analytics.

🔧 Enjoy embedding a seamless AI chat experience on your logistics portal!