Wemo.Learn

Step 8 of 11· AI Customer Support Chatbot

API and chat widget

Expose the desk as an HTTP API with FastAPI and add an embeddable chat widget that any website can load with one script tag.

Purpose#

Make the desk available to websites. A FastAPI server provides the chat API. A small JavaScript widget adds a chat button to any page with one <script> tag.

In this step:

  • Build the HTTP API with input validation and CORS
  • Identify visitors without storing IP addresses
  • Build the chat widget
  • Test both in the browser

Endpoints#

Method and pathBodyReturns
POST /api/chat{message, conversation_id?}{conversation_id, kind, text, message_id, ticket?}
POST /api/handoff/{ticket}/contact{conversation_id, contact}{ok: true}
POST /api/feedback{conversation_id, message_id, helpful}{ok: true}
GET /healthz{ok: true} if the database is reachable
GET /widget.js, GET /The widget and a demo page

1. API#

support_desk/app.py
"""The HTTP API and the chat widget.

Run locally:  uvicorn support_desk.app:app --reload
"""
import hashlib
import logging
from contextlib import asynccontextmanager
from pathlib import Path

from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field

from support_desk import config, conversations, handoff, service
from support_desk import db
from support_desk.db import connect

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("support_desk")


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Check the settings and the database at startup, so a broken deploy fails right away, not at the first customer."""
    missing = [name for name in ("OPENAI_API_KEY", "DATABASE_URL") if not getattr(config, name)]
    if missing:
        raise RuntimeError(f"Missing settings: {', '.join(missing)}")
    if config.CLIENT_SALT == "change-me":
        log.warning("CLIENT_SALT is the default value. Set a random value before going live.")
    if not config.ALLOWED_ORIGINS:
        log.warning("ALLOWED_ORIGINS is empty: no website can use the widget.")
    with connect() as conn:  # fails here if DATABASE_URL is wrong
        conn.execute("select 1")
    yield
    db.close()  # close database connections cleanly on shutdown


app = FastAPI(title="AI Customer Support Chatbot", docs_url=None, redoc_url=None, lifespan=lifespan)
app.add_middleware(
    CORSMiddleware,
    allow_origins=config.ALLOWED_ORIGINS,  # only these websites may call the API from a browser
    allow_methods=["GET", "POST"],
    allow_headers=["Content-Type"],
)


class ChatIn(BaseModel):
    message: str = Field(min_length=1, max_length=config.MAX_MESSAGE_CHARS)
    conversation_id: str | None = None


class ContactIn(BaseModel):
    conversation_id: str
    contact: str = Field(min_length=3, max_length=200)


class FeedbackIn(BaseModel):
    conversation_id: str
    message_id: int
    helpful: bool


def client_id(request: Request) -> str:
    """A salted hash of the visitor's IP address: recognizes a returning visitor without storing the address."""
    ip = request.client.host if request.client else "unknown"
    forwarded = request.headers.get("x-forwarded-for")
    if config.TRUST_PROXY_HEADERS and forwarded:
        ip = forwarded.split(",")[-1].strip()  # the last entry is added by your hosting's proxy
    return hashlib.sha256(f"{config.CLIENT_SALT}|{ip}".encode()).hexdigest()[:32]


@app.post("/api/chat")
def chat(body: ChatIn, request: Request) -> dict:
    client = client_id(request)
    conversation_id = body.conversation_id
    if not conversation_id or not conversations.belongs_to(conversation_id, client):
        conversation_id = conversations.start(client)
    turn = service.reply(conversation_id, body.message.strip())
    # The sources stay on the server (saved with the message for the team). The visitor gets the text only.
    return {"conversation_id": conversation_id, **{k: v for k, v in turn.items() if k not in ("sources", "cached")}}


@app.post("/api/handoff/{ticket}/contact")
def contact(ticket: int, body: ContactIn) -> dict:
    value = body.contact.strip()
    if not handoff.valid_contact(value):
        raise HTTPException(422, "Enter an email address or a phone number.")
    if not handoff.add_contact(ticket, body.conversation_id, value):
        raise HTTPException(404, "Ticket not found.")
    return {"ok": True}


@app.post("/api/feedback")
def feedback(body: FeedbackIn) -> dict:
    if not conversations.add_feedback(body.conversation_id, body.message_id, body.helpful):
        raise HTTPException(404, "Message not found.")
    return {"ok": True}


@app.get("/healthz")
def healthz() -> dict:
    with connect() as conn:
        conn.execute("select 1")
    return {"ok": True}


# widget.js and the demo page. Mounted last, so the API routes above take precedence.
app.mount("/", StaticFiles(directory=Path(__file__).parent / "static", html=True), name="static")

FastAPI validates every request, CORS limits which websites may call the API, and visitors are identified by a salted hash of their IP address, never the address itself. At startup the app checks its settings and the database, so a broken configuration fails right away instead of at the first customer.

2. Widget#

support_desk/static/widget.js
// AI Customer Support Chatbot chat widget. Add to any page:
// <script src="https://YOUR-API/widget.js" data-api="https://YOUR-API" defer></script>
(function () {
  const script = document.currentScript;
  const API = (script && script.dataset.api) || "";
  const TITLE = (script && script.dataset.title) || "Questions? Ask us";
  const GREETING = (script && script.dataset.greeting) || "Hi! How can I help you today?";
  const KEY = "support-desk-conversation";

  const host = document.createElement("div");
  document.body.appendChild(host);
  const root = host.attachShadow({ mode: "open" }); // the page's CSS cannot break the widget, and the reverse

  root.innerHTML = `
    <style>
      :host { all: initial; font: 15px/1.45 system-ui, sans-serif; }
      .open { position: fixed; right: 20px; bottom: 20px; border: 0; border-radius: 999px; padding: 12px 18px;
              background: #111; color: #fff; font: inherit; cursor: pointer; z-index: 2147483000; }
      .panel { position: fixed; right: 20px; bottom: 76px; width: min(370px, calc(100vw - 40px)); height: min(520px, calc(100vh - 110px));
               display: none; flex-direction: column; background: #fff; color: #111; border: 1px solid #ddd;
               border-radius: 14px; box-shadow: 0 10px 40px rgba(0,0,0,.18); overflow: hidden; z-index: 2147483000; }
      .panel.visible { display: flex; }
      header { padding: 12px 16px; font-weight: 600; border-bottom: 1px solid #eee; }
      .log { flex: 1; overflow-y: auto; padding: 12px 16px; display: flex; flex-direction: column; gap: 10px; }
      .msg { max-width: 85%; padding: 8px 12px; border-radius: 12px; white-space: pre-wrap; }
      .user { align-self: flex-end; background: #111; color: #fff; }
      .bot { align-self: flex-start; background: #f2f2f2; }
      .rate button { border: 0; background: none; cursor: pointer; font-size: 15px; padding: 2px 4px; }
      form { display: flex; gap: 8px; padding: 10px; border-top: 1px solid #eee; }
      input { flex: 1; padding: 9px 10px; border: 1px solid #ccc; border-radius: 8px; font: inherit; }
      form button { border: 0; border-radius: 8px; padding: 0 14px; background: #111; color: #fff; font: inherit; cursor: pointer; }
      .contact { display: flex; gap: 6px; margin-top: 8px; }
    </style>
    <button class="open" type="button"></button>
    <div class="panel" role="dialog" aria-label="Support chat">
      <header></header>
      <div class="log" aria-live="polite"></div>
      <form><input name="q" autocomplete="off" maxlength="1000" placeholder="Type your question" aria-label="Your question"><button>Send</button></form>
    </div>`;

  const $ = (sel) => root.querySelector(sel);
  const panel = $(".panel"), log = $(".log"), form = $("form"), input = $("input");
  $(".open").textContent = TITLE;
  $("header").textContent = TITLE;
  $(".open").addEventListener("click", () => {
    panel.classList.toggle("visible");
    if (!log.children.length) bubble(GREETING, "bot"); // shown by the widget, no request to the API
    input.focus();
  });

  let conversationId = null;
  try { conversationId = sessionStorage.getItem(KEY); } catch (e) {}

  async function post(path, body) {
    // Give up after 45 seconds, so a hanging request never leaves the chat waiting forever.
    const res = await fetch(API + path, {
      method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),
      signal: AbortSignal.timeout(45000),
    }).catch(() => { throw new Error("The assistant is not responding. Please try again."); });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) throw new Error(typeof data.detail === "string" ? data.detail : "Something went wrong. Please try again.");
    return data;
  }

  // All text is set with textContent, never innerHTML: an answer can never inject HTML or scripts into the page.
  function bubble(text, who) {
    const div = document.createElement("div");
    div.className = "msg " + who;
    div.textContent = text;
    log.appendChild(div);
    log.scrollTop = log.scrollHeight;
    return div;
  }

  function addRating(div, messageId) {
    const box = document.createElement("div");
    box.className = "rate";
    for (const [label, helpful] of [["👍", true], ["👎", false]]) {
      const b = document.createElement("button");
      b.type = "button";
      b.textContent = label;
      b.setAttribute("aria-label", helpful ? "Helpful" : "Not helpful");
      b.addEventListener("click", async () => {
        try { await post("/api/feedback", { conversation_id: conversationId, message_id: messageId, helpful }); box.textContent = "Thanks for the feedback."; }
        catch (e) { box.textContent = e.message; }
      });
      box.appendChild(b);
    }
    div.appendChild(box);
  }

  function addContactForm(div, ticket) {
    const f = document.createElement("form");
    f.className = "contact";
    const field = document.createElement("input");
    field.placeholder = "Email or phone";
    field.maxLength = 200;
    field.setAttribute("aria-label", "Email or phone");
    const send = document.createElement("button");
    send.textContent = "Send";
    f.append(field, send);
    f.addEventListener("submit", async (e) => {
      e.preventDefault();
      try { await post(`/api/handoff/${ticket}/contact`, { conversation_id: conversationId, contact: field.value }); const done = document.createElement("div"); done.textContent = "Thanks. The team will contact you."; f.replaceWith(done); }
      catch (err) { field.value = ""; field.placeholder = err.message; }
    });
    div.appendChild(f);
  }

  form.addEventListener("submit", async (e) => {
    e.preventDefault();
    const question = input.value.trim();
    if (!question) return;
    input.value = "";
    bubble(question, "user");
    const pending = bubble("…", "bot");
    input.disabled = true;
    try {
      const data = await post("/api/chat", { message: question, conversation_id: conversationId });
      conversationId = data.conversation_id;
      try { sessionStorage.setItem(KEY, conversationId); } catch (e) {}
      pending.textContent = data.text;
      if (data.kind === "answer") addRating(pending, data.message_id);
      if (data.kind === "handoff") addContactForm(pending, data.ticket);
    } catch (err) {
      pending.textContent = err.message;
    } finally {
      input.disabled = false;
      input.focus();
    }
  });
})();

One script tag adds the chat to any page; Shadow DOM keeps its styles separate, answers are inserted as text, never as HTML, and a request that takes longer than 45 seconds shows an error instead of waiting forever.

3. Demo page#

support_desk/static/index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Brightside Cleaning Co. (demo)</title>
  <style>body { font: 16px/1.5 system-ui, sans-serif; max-width: 640px; margin: 60px auto; padding: 0 20px; }</style>
</head>
<body>
  <h1>Brightside Cleaning Co.</h1>
  <p>Demo page for the AI Customer Support Chatbot. Open the chat in the bottom right corner.</p>
  <script src="/widget.js" data-api="" defer></script>
</body>
</html>

data-api="" means the API is on the same address as the page.

Checkpoint#

Server:

Terminal
uv run uvicorn support_desk.app:app --reload

In a second terminal:

Terminal
curl -s -X POST localhost:8000/api/chat -H "Content-Type: application/json" -d '{"message": "What is your phone number?"}'

Output from a real run:

JSON
{"conversation_id":"3e754b45-0f1b-4c39-9d4d-33bbc05e653f","kind":"answer","text":"Our phone number is 555-0142.","message_id":74}

Browser: open http://localhost:8000 and click Questions? Ask us.

  1. The chat opens with "Hi! How can I help you today?". Type "Hello". The reply asks what you would like to know, without a contact field.
  2. Ask "Can I cancel tomorrow's cleaning for free?". Click 👍 under the answer; the widget shows "Thanks for the feedback."
  3. Ask "Do you clean boats?". The handoff text and a contact field appear. Enter an email address. uv run python -m support_desk.handoff shows the ticket with the contact.
  4. Open the browser's developer tools, Network tab. Each question is one POST /api/chat.

Troubleshooting#

  • The server does not start, Missing settings: …: OPENAI_API_KEY or DATABASE_URL is empty in .env.
  • The widget button does not appear: check the browser console. A 404 for widget.js means the server was not started from the support-desk directory.
  • CORS error in the console: the page's address (scheme, host and port) is not in ALLOWED_ORIGINS. Restart the server after changing .env.
  • Every question starts a new conversation: the browser blocks sessionStorage, or the page is opened as a file (file://). Open it through the server.