Wemo.Learn

Step 4 of 11· AI Customer Support Chatbot

Embeddings and index

Turn chunks into vectors with OpenAI embeddings, log every request with its cost, and keep the index in sync with the articles.

Purpose#

Turn every chunk into a vector and store it in Postgres. Vectors make it possible to find chunks by meaning: "Can I move my appointment?" finds the section about rescheduling although the words differ. Every OpenAI request is logged with its cost from this step on.

In this step:

  • Log every request with tokens and cost
  • Embed texts with the OpenAI embeddings API
  • Sync the index with the articles: only new and changed chunks are embedded

Embeddings#

An embedding is a list of numbers (here 1536) that represents the meaning of a text. Texts with similar meaning get vectors that point in a similar direction. The similarity of two vectors is measured with cosine similarity: 1 means same direction, 0 means unrelated.

Loading diagram…

The same model must embed the chunks and the questions. Vectors from different models cannot be compared.

1. Request log#

support_desk/telemetry.py
"""A log of every OpenAI request: tokens, cost, duration and outcome. No message content.

Summary:  python -m support_desk.telemetry
"""
import logging

from support_desk.db import connect

log = logging.getLogger("support_desk")

# Dollars per million tokens (input, output). Check openai.com/api/pricing and add the models you use.
PRICES = {
    "gpt-5.4-mini": (0.75, 4.50),
    "gpt-5-mini": (0.25, 2.00),
    "text-embedding-3-small": (0.02, 0.0),
}


def cost(model: str, input_tokens: int, output_tokens: int) -> float | None:
    """Cost in dollars, or None for a model that is not in PRICES."""
    if model not in PRICES:
        return None
    price_in, price_out = PRICES[model]
    return (input_tokens * price_in + output_tokens * price_out) / 1_000_000


def log_call(kind: str, model: str, input_tokens: int, output_tokens: int, seconds: float, outcome: str) -> None:
    """Insert one row into llm_calls. `kind` is "embed" or "answer"."""
    try:
        with connect() as conn:
            conn.execute(
                "insert into llm_calls (kind, model, input_tokens, output_tokens, cost, seconds, outcome) "
                "values (%s, %s, %s, %s, %s, %s, %s)",
                (kind, model, input_tokens, output_tokens, cost(model, input_tokens, output_tokens) or 0, seconds, outcome),
            )
    except Exception:
        log.exception("Could not write the request log")  # logging must never break a customer request


def summary() -> list[dict]:
    """Totals per day and kind, with median and 95th percentile duration."""
    with connect() as conn:
        return conn.execute("""
            select created_at::date as day, kind, count(*) as calls,
                   sum(input_tokens) as input_tokens, sum(output_tokens) as output_tokens, sum(cost) as cost,
                   percentile_cont(0.5) within group (order by seconds) as p50,
                   percentile_cont(0.95) within group (order by seconds) as p95,
                   count(*) filter (where outcome = 'error') as errors
            from llm_calls group by 1, 2 order by 1, 2""").fetchall()


if __name__ == "__main__":
    rows = summary()
    print(f"{'day':<12}{'kind':<8}{'calls':>6}{'in tok':>10}{'out tok':>9}{'cost $':>9}{'p50 s':>7}{'p95 s':>7}{'errors':>7}")
    for r in rows:
        print(f"{r['day']!s:<12}{r['kind']:<8}{r['calls']:>6}{r['input_tokens']:>10}{r['output_tokens']:>9}"
              f"{r['cost']:>9.4f}{r['p50']:>7.2f}{r['p95']:>7.2f}{r['errors']:>7}")
    if not rows:
        print("No requests logged yet.")

Every OpenAI request is logged with tokens, cost and duration, never with message text, and summary() shows the totals per day.

2. Embeddings#

support_desk/embeddings.py
"""Turn text into vectors with the OpenAI embeddings API."""
import time

from support_desk import config
from support_desk.openai_client import get_client
from support_desk.telemetry import log_call

BATCH_SIZE = 100  # texts per request


def embed(texts: list[str]) -> list[list[float]]:
    """One vector per text, in the same order."""
    vectors: list[list[float]] = []
    for start in range(0, len(texts), BATCH_SIZE):
        batch = texts[start:start + BATCH_SIZE]
        began = time.perf_counter()
        try:
            response = get_client().embeddings.create(model=config.EMBEDDING_MODEL, input=batch)
        except Exception:
            log_call("embed", config.EMBEDDING_MODEL, 0, 0, time.perf_counter() - began, "error")
            raise
        log_call("embed", config.EMBEDDING_MODEL, response.usage.total_tokens, 0, time.perf_counter() - began, "ok")
        vectors += [item.embedding for item in sorted(response.data, key=lambda item: item.index)]
    return vectors

Texts are embedded in batches of 100, and each vector is matched back to its text by position.

3. Index sync#

support_desk/index.py
"""Keep the chunks table in sync with the knowledge base folder.

Run after every change to the articles:  python -m support_desk.index
"""
from support_desk.db import connect, to_vector
from support_desk.embeddings import embed
from support_desk.kb import Chunk, load_chunks


def sync(chunks: list[Chunk], embed_fn=embed) -> dict[str, int]:
    """Add new and changed chunks, remove deleted ones. Unchanged chunks are not embedded again."""
    wanted = {c.content_hash: c for c in chunks}
    with connect() as conn:
        existing = {row["content_hash"] for row in conn.execute("select content_hash from chunks")}
        new = [c for h, c in wanted.items() if h not in existing]
        removed = [h for h in existing if h not in wanted]

        vectors = embed_fn([c.text for c in new]) if new else []
        # One transaction: visitors never see a half-updated index.
        for chunk, vector in zip(new, vectors):
            conn.execute(
                "insert into chunks (doc, title, heading, url, content, content_hash, embedding) "
                "values (%s, %s, %s, %s, %s, %s, %s::vector)",
                (chunk.doc, chunk.title, chunk.heading, chunk.url, chunk.content, chunk.content_hash, to_vector(vector)),
            )
        if removed:
            conn.execute("delete from chunks where content_hash = any(%s)", (removed,))
        # Cached answers (step 7) were written from the old articles: start over when anything changed.
        if new or removed:
            conn.execute("delete from answer_cache")
        conn.execute("delete from answer_cache where expires_at < now()")
    return {"added": len(new), "removed": len(removed), "unchanged": len(wanted) - len(new)}


if __name__ == "__main__":
    result = sync(load_chunks())
    print(f"Index updated: {result['added']} added, {result['removed']} removed, {result['unchanged']} unchanged.")

Chunks are compared by fingerprint: only new or changed chunks are embedded, deleted ones are removed, all in one transaction. When anything changed, the answer cache from step 7 is emptied too, so no answer from an old article is reused. Run the command after every change to the articles.

Checkpoint#

Terminal
uv run python -m support_desk.index

Expected output:

Output
Index updated: 21 added, 0 removed, 0 unchanged.

Run it a second time:

Output
Index updated: 0 added, 0 removed, 21 unchanged.

Change a sentence in knowledge_base/hours.md and run it again. One chunk is added and one removed. Undo the change and run it once more.

Terminal
uv run python -m support_desk.telemetry

Expected output (numbers vary):

Output
day         kind     calls    in tok  out tok   cost $  p50 s  p95 s errors
2026-11-14  embed        1       796        0   0.0000   1.77   1.77      0

In Supabase, open Table Editor → chunks. The embedding column contains the vectors.

Troubleshooting#

  • expected 1536 dimensions, not 3072: EMBEDDING_MODEL is text-embedding-3-large. Either use text-embedding-3-small, or change vector(1536) in the schema and EMBEDDING_DIM to 3072, drop the chunks table and index again.
  • Cost shows 0: the model is missing from PRICES in telemetry.py.
  • RateLimitError: new OpenAI accounts have low limits. Wait a minute and run the command again; already indexed chunks are skipped.