Wemo.Learn

Step 7 of 11· AI Customer Support Chatbot

Conversations and handoff

Store conversations for follow-up questions, create tickets for questions that need a person, cache answers to repeated questions, and run a chat in the terminal.

Purpose#

Connect search and answers into a chat turn. Conversations are stored, so follow-up questions work. Questions that need a person become tickets for the team. Errors also become tickets, so no question is lost. A question that was already answered gets the cached answer, without an OpenAI request.

In this step:

  • Store conversations and messages
  • Create tickets for the team
  • Cache answers to repeated questions
  • Handle one chat turn, including follow-up questions and errors
  • Chat in the terminal

Chat turn#

Loading diagram…

1. Conversations#

support_desk/conversations.py
"""Conversations and messages in Postgres. The history makes follow-up questions work."""
import json
from uuid import UUID

from support_desk.db import connect


def start(client: str) -> str:
    with connect() as conn:
        return str(conn.execute("insert into conversations (client) values (%s) returning id", (client,)).fetchone()["id"])


def belongs_to(conversation_id: str, client: str) -> bool:
    """A visitor can only continue their own conversation."""
    try:
        UUID(conversation_id)
    except ValueError:
        return False
    with connect() as conn:
        row = conn.execute("select 1 from conversations where id = %s and client = %s", (conversation_id, client)).fetchone()
    return row is not None


def add_message(conversation_id: str, role: str, content: str, sources: list | None = None,
                outcome: str | None = None, cache_key: str | None = None) -> int:
    with connect() as conn:
        row = conn.execute(
            "insert into messages (conversation_id, role, content, sources, outcome, cache_key) "
            "values (%s, %s, %s, %s, %s, %s) returning id",
            (conversation_id, role, content, json.dumps(sources or []), outcome, cache_key),
        ).fetchone()
    return row["id"]


def has_answer(conversation_id: str) -> bool:
    """True after the first real answer or handoff. Greetings and small talk don't count."""
    with connect() as conn:
        row = conn.execute(
            "select 1 from messages where conversation_id = %s and outcome in ('answered', 'handoff', 'error') limit 1",
            (conversation_id,),
        ).fetchone()
    return row is not None


def history(conversation_id: str, limit: int = 6) -> list[dict]:
    """The last `limit` messages, oldest first, in the format the OpenAI API expects."""
    with connect() as conn:
        rows = conn.execute(
            "select role, content from messages where conversation_id = %s order by id desc limit %s",
            (conversation_id, limit),
        ).fetchall()
    return [{"role": r["role"], "content": r["content"]} for r in reversed(rows)]


def transcript(conversation_id: str) -> list[dict]:
    with connect() as conn:
        return conn.execute(
            "select role, content, outcome, created_at from messages where conversation_id = %s order by id",
            (conversation_id,),
        ).fetchall()


def add_feedback(conversation_id: str, message_id: int, helpful: bool) -> bool:
    """Thumbs up or down on an assistant message of this conversation. Returns False for any other message.

    A thumbs down also removes the answer from the cache, so the next visitor gets a fresh one."""
    with connect() as conn:
        row = conn.execute(
            """insert into feedback (message_id, helpful)
               select id, %s from messages where id = %s and conversation_id = %s and role = 'assistant'
               on conflict (message_id) do update set helpful = excluded.helpful
               returning message_id""",
            (helpful, message_id, conversation_id),
        ).fetchone()
        if row and not helpful:
            conn.execute(
                "delete from answer_cache where key = (select cache_key from messages where id = %s)", (message_id,)
            )
    return row is not None

Conversations and messages are stored in Postgres, and every function checks that the conversation belongs to the visitor.

2. Handoff#

support_desk/handoff.py
"""Handoff: a ticket for a person.

Open tickets:   python -m support_desk.handoff
Close one:      python -m support_desk.handoff close 12
"""
import re

from support_desk.conversations import transcript
from support_desk.db import connect

EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
PHONE = re.compile(r"^\+?[0-9 ()./-]{6,20}$")


def create(conversation_id: str, reason: str) -> int:
    with connect() as conn:
        ticket = conn.execute(
            "insert into handoffs (conversation_id, reason) values (%s, %s) returning id", (conversation_id, reason)
        ).fetchone()["id"]
    return ticket


def valid_contact(contact: str) -> bool:
    return bool(EMAIL.match(contact) or PHONE.match(contact))


def add_contact(ticket: int, conversation_id: str, contact: str) -> bool:
    """Store the visitor's email or phone number on their own ticket."""
    with connect() as conn:
        row = conn.execute(
            "update handoffs set contact = %s where id = %s and conversation_id = %s and status = 'open' returning id",
            (contact, ticket, conversation_id),
        ).fetchone()
    return row is not None


def open_tickets() -> list[dict]:
    with connect() as conn:
        return conn.execute(
            "select id, conversation_id, reason, contact, created_at from handoffs where status = 'open' order by id"
        ).fetchall()


def close(ticket: int) -> None:
    with connect() as conn:
        conn.execute("update handoffs set status = 'closed' where id = %s", (ticket,))


if __name__ == "__main__":
    import sys

    if len(sys.argv) == 3 and sys.argv[1] == "close":
        close(int(sys.argv[2]))
        print(f"Closed ticket #{sys.argv[2]}.")
    else:
        for t in open_tickets():
            print(f"\n#{t['id']}  {t['created_at']:%Y-%m-%d %H:%M}  contact: {t['contact'] or '-'}  reason: {t['reason']}")
            for m in transcript(t["conversation_id"]):
                print(f"   {m['role']:>9}: {m['content']}")
        print("\nNo open tickets." if not open_tickets() else "")

A handoff saves a ticket; contact details can only be added to the visitor's own open ticket.

3. Answer cache#

support_desk/cache.py
"""Answer cache: a question that was already answered gets the same answer again, without an OpenAI request.

Popular answers:  python -m support_desk.cache
Empty the cache:  python -m support_desk.cache clear
"""
import hashlib
import json
import logging
import re

import psycopg

from support_desk import config
from support_desk.answer import INSTRUCTIONS
from support_desk.db import connect

log = logging.getLogger("support_desk")


def normalize(question: str) -> str:
    """Small differences must not cause a miss: "Can I cancel for free?" = "can i cancel  for free"."""
    text = question.lower().replace("’", "'").replace("‘", "'")
    return re.sub(r"\s+", " ", text).strip(" ?!.")


def cache_key(question: str) -> str:
    """The question plus every setting that changes the answer. A new model or prompt starts a fresh cache."""
    settings = [normalize(question), config.OPENAI_MODEL, config.OPENAI_REASONING_EFFORT,
                config.SEARCH_MODE, config.TOP_K, hashlib.sha256(INSTRUCTIONS.encode()).hexdigest()]
    return hashlib.sha256(json.dumps(settings).encode()).hexdigest()


def get(key: str) -> dict | None:
    """The cached answer, or None. A database error counts as a miss: the cache never breaks the chat."""
    if config.CACHE_TTL_HOURS <= 0:
        return None
    try:
        with connect() as conn:
            row = conn.execute(
                """update answer_cache set hits = hits + 1, last_hit_at = now()
                   where key = %s and expires_at > now() returning text, sources""",
                (key,),
            ).fetchone()
    except psycopg.Error:
        log.exception("Cache read failed")
        return None
    return dict(row) if row else None


def put(key: str, text: str, sources: list[dict]) -> None:
    if config.CACHE_TTL_HOURS <= 0:
        return
    try:
        with connect() as conn:
            conn.execute(
                """insert into answer_cache (key, text, sources, expires_at)
                   values (%s, %s, %s, now() + make_interval(hours => %s))
                   on conflict (key) do update set text = excluded.text, sources = excluded.sources,
                       created_at = now(), expires_at = excluded.expires_at""",
                (key, text, json.dumps(sources), config.CACHE_TTL_HOURS),
            )
    except psycopg.Error:
        log.exception("Cache write failed")


if __name__ == "__main__":
    import sys

    with connect() as conn:
        if sys.argv[1:] == ["clear"]:
            removed = conn.execute("delete from answer_cache").rowcount
            print(f"Removed {removed} cached answers.")
        else:
            rows = conn.execute(
                "select text, hits, expires_at from answer_cache where expires_at > now() order by hits desc limit 10"
            ).fetchall()
            for r in rows:
                print(f"{r['hits']:>4} hits  until {r['expires_at']:%Y-%m-%d}  {r['text'][:90]}")
            print("No cached answers." if not rows else "")

The cache lives in Postgres, so every server instance shares it. The key is a hash of the normalized question plus every setting that changes the answer: model, reasoning effort, search mode, TOP_K and the prompt. Change one of them and the old entries are simply never matched again.

What keeps it safe:

  • Only standalone questions. A follow-up like "and on weekends?" depends on the conversation, so only questions asked before the first answer in a conversation are cached or served from the cache. Greetings don't count.
  • Only verified answers. Handoffs, small talk and errors always run fresh, so every handoff still creates a ticket.
  • No visitor data. The table stores a hash of the question, never the question itself.
  • Expiry and invalidation. Entries expire after CACHE_TTL_HOURS (default 168, 7 days). The index sync empties the cache when an article changes. A thumbs down removes that answer from the cache.
  • Never breaks the chat. A database error in the cache counts as a miss and is logged.

4. Chat turn#

support_desk/service.py
"""One chat turn: save the question, search, answer or hand off, save the reply."""
import logging

from support_desk import cache, conversations, handoff
from support_desk.answer import AnswerError, answer
from support_desk.search import search

log = logging.getLogger("support_desk")

# Fixed texts, written by you. The model decides which one fits; it never writes them.
SMALL_TALK_TEXT = ("Happy to help. I can answer questions about booking, prices, cancellations and our guarantee. "
                   "What would you like to know?")
HANDOFF_TEXT = ("I can't answer that from our help center, so I've passed it to the team. "
                "Leave your email or phone number and we'll get back to you within one business day.")
ERROR_TEXT = ("Sorry, I can't answer right now. I've passed your question to the team. "
              "Leave your email or phone number and we'll get back to you.")


def search_query(question: str, history: list[dict]) -> str:
    """Follow-ups like "and on weekends?" need the previous question to find the right chunks."""
    previous = [m["content"] for m in history if m["role"] == "user"][-1:]
    return "\n".join(previous + [question])


def reply(conversation_id: str, question: str) -> dict:
    history = conversations.history(conversation_id)
    conversations.add_message(conversation_id, "user", question)

    # Only a standalone question is cached: a follow-up like "and on weekends?" depends on the conversation.
    key = None if conversations.has_answer(conversation_id) else cache.cache_key(question)
    if key and (hit := cache.get(key)):
        message_id = conversations.add_message(conversation_id, "assistant", hit["text"], hit["sources"], "answered", key)
        return {"kind": "answer", "text": hit["text"], "sources": hit["sources"], "message_id": message_id, "cached": True}

    try:
        result = answer(question, search(search_query(question, history)), history)
    except AnswerError:
        log.exception("Answer failed")
        return hand_off(conversation_id, question, "error: the answer service failed", ERROR_TEXT, "error")

    if result.kind == "handoff":
        return hand_off(conversation_id, question, result.reason, HANDOFF_TEXT, "handoff")
    if result.kind == "small_talk":
        message_id = conversations.add_message(conversation_id, "assistant", SMALL_TALK_TEXT, outcome="small_talk")
        return {"kind": "small_talk", "text": SMALL_TALK_TEXT, "sources": [], "message_id": message_id}

    sources = [{"title": h.title, "heading": h.heading, "url": h.url} for h in result.sources]
    if key:
        cache.put(key, result.text, sources)
    message_id = conversations.add_message(conversation_id, "assistant", result.text, sources, "answered", key)
    return {"kind": "answer", "text": result.text, "sources": sources, "message_id": message_id, "cached": False}


def hand_off(conversation_id: str, question: str, reason: str, text: str, outcome: str) -> dict:
    ticket = handoff.create(conversation_id, reason)
    message_id = conversations.add_message(conversation_id, "assistant", text, outcome=outcome)
    return {"kind": "handoff", "text": text, "sources": [], "message_id": message_id, "ticket": ticket}


if __name__ == "__main__":
    conversation = conversations.start("cli")
    print("Ask a question. Empty line to quit.")
    while question := input("\nYou: ").strip():
        turn = reply(conversation, question)
        print(f"Desk ({turn['kind']}{', cached' if turn.get('cached') else ''}): {turn['text']}")
        for source in turn["sources"]:
            print(f"   source: {source['title']} > {source['heading']}  {source['url']}")

One chat turn: save the question, check the cache, search with the previous question as context, then answer, hand off or reply to small talk with your fixed texts. Errors become tickets too.

Checkpoint#

Terminal chat:

Terminal
uv run python -m support_desk.service

Output from a real run (wording varies):

Output
Ask a question. Empty line to quit.

You: Hello
Desk (small_talk): Happy to help. I can answer questions about booking, prices, cancellations and our guarantee. What would you like to know?

You: Do you offer recurring discounts?
Desk (answer): Yes. Recurring plans get a discount on the hourly price: 15% for weekly visits, 10% for visits every two weeks, and 5% for monthly visits.
   source: Prices > Recurring discounts  https://brightside.example/help/pricing

You: and for monthly visits?
Desk (answer): Monthly visits get a 5% discount on the hourly price.
   source: Prices > Recurring discounts  https://brightside.example/help/pricing

You: Why was I charged twice on my last invoice?
Desk (handoff): I can't answer that from our help center, so I've passed it to the team. Leave your email or phone number and we'll get back to you within one business day.

List the open tickets:

Terminal
uv run python -m support_desk.handoff
Output
#1  2026-11-14 23:37  contact: -  reason: The sources do not contain information about a specific invoice or why it was charged twice. This needs a person to review the customer's billing account.
        user: Hello
   assistant: Happy to help. I can answer questions about booking, prices, ...
        user: Do you offer recurring discounts?
   assistant: Yes. Recurring plans get a discount on the hourly price: ...
        user: and for monthly visits?
   assistant: Monthly visits get a 5% discount on the hourly price.
        user: Why was I charged twice on my last invoice?
   assistant: I can't answer that from our help center, so I've passed it to the team. ...

Close the ticket:

Terminal
uv run python -m support_desk.handoff close 1

Answer cache: start the terminal chat again and ask the same first question. The answer comes from the cache, with no OpenAI request:

Output
You: Do you offer recurring discounts?
Desk (answer, cached): Yes. Recurring plans get a discount on the hourly price: 15% for weekly visits, 10% for visits every two weeks, and 5% for monthly visits.
   source: Prices > Recurring discounts  https://brightside.example/help/pricing

The most reused answers:

Terminal
uv run python -m support_desk.cache
Output
   1 hits  until 2026-11-27  Yes. Recurring plans get a discount on the hourly price: 15% for weekly visits, 10% for vi

uv run python -m support_desk.cache clear empties the cache.

Troubleshooting#

  • A repeated question is not cached: only the first question of a conversation is cached, and only answers with a verified source. Check that CACHE_TTL_HOURS is not 0.

  • An outdated answer after editing an article: run uv run python -m support_desk.index, which empties the cache, or uv run python -m support_desk.cache clear.

  • The follow-up is handed off: check that search_query() adds the previous question, and that history is passed to answer().