Wemo.Learn

Step 5 of 11· AI Customer Support Chatbot

Search

Find the chunks that match a question with keyword search, vector search, and hybrid search with reciprocal rank fusion.

Purpose#

Find the chunks that answer a question. The answer step (step 6) can only be as good as the chunks it receives. This step implements three search methods; step 9 measures which one works best for this help center.

In this step:

  • Keyword search with Postgres full-text search
  • Vector search with pgvector
  • Hybrid search: both combined with reciprocal rank fusion

Search module#

support_desk/search.py
"""Find the chunks that best match a question: keyword, vector or hybrid search.

Try it:  python -m support_desk.search "can I cancel for free?"
"""
from dataclasses import dataclass

from support_desk import config
from support_desk.db import connect, to_vector
from support_desk.embeddings import embed

COLUMNS = "id, doc, title, heading, url, content"
CANDIDATES = 20  # how many results each method contributes to hybrid search
RRF_K = 60       # standard constant for reciprocal rank fusion


@dataclass
class Hit:
    id: int
    doc: str
    title: str
    heading: str
    url: str
    content: str
    score: float


def keyword_search(conn, query: str, k: int) -> list[Hit]:
    """Full-text search. Matches chunks that contain any of the words in the question, best matches first."""
    rows = conn.execute(
        f"""
        with q as (select replace(plainto_tsquery('english', %s)::text, '&', '|') as words)
        select {COLUMNS}, ts_rank_cd(fts, to_tsquery('english', q.words)) as score
        from chunks, q
        where q.words <> '' and fts @@ to_tsquery('english', q.words)
        order by score desc, id limit %s
        """,
        (query, k),
    ).fetchall()
    return [Hit(**row) for row in rows]


def vector_search(conn, query_vector: list[float], k: int) -> list[Hit]:
    """Semantic search. `<=>` is cosine distance in pgvector, so 1 - distance is the similarity."""
    vector = to_vector(query_vector)
    rows = conn.execute(
        f"select {COLUMNS}, 1 - (embedding <=> %s::vector) as score from chunks order by embedding <=> %s::vector limit %s",
        (vector, vector, k),
    ).fetchall()
    return [Hit(**row) for row in rows]


def fuse(result_lists: list[list[Hit]], k: int) -> list[Hit]:
    """Reciprocal rank fusion: a chunk scores 1 / (60 + rank) in every list it appears in."""
    scores: dict[int, float] = {}
    hits: dict[int, Hit] = {}
    for results in result_lists:
        for rank, hit in enumerate(results, start=1):
            scores[hit.id] = scores.get(hit.id, 0.0) + 1.0 / (RRF_K + rank)
            hits[hit.id] = hit
    best = sorted(scores, key=lambda chunk_id: (-scores[chunk_id], chunk_id))[:k]
    return [Hit(**{**hits[i].__dict__, "score": scores[i]}) for i in best]


def search(query: str, k: int | None = None, mode: str | None = None, embed_fn=embed) -> list[Hit]:
    k, mode = k or config.TOP_K, mode or config.SEARCH_MODE
    if mode not in ("keyword", "vector", "hybrid"):
        raise ValueError(f"Unknown search mode: {mode}")
    query_vector = embed_fn([query])[0] if mode != "keyword" else None  # embed before opening a connection
    with connect() as conn:
        if mode == "keyword":
            return keyword_search(conn, query, k)
        if mode == "vector":
            return vector_search(conn, query_vector, k)
        return fuse([keyword_search(conn, query, CANDIDATES), vector_search(conn, query_vector, CANDIDATES)], k)


if __name__ == "__main__":
    import sys

    question = " ".join(sys.argv[1:]) or "can I cancel for free?"
    for hit in search(question, k=3):
        print(f"{hit.score:.3f}  {hit.title} > {hit.heading}\n       {hit.content}\n")

Keyword search matches words with Postgres full-text search, vector search finds the closest meaning with pgvector, and hybrid merges both lists by rank. The desk uses the mode in SEARCH_MODE, vector by default.

Checkpoint#

Ask a question in other words than the article uses:

Terminal
uv run python -m support_desk.search "I need to move my appointment to Friday, does that cost anything?"

Output from a real run (scores vary slightly):

Output
0.440  Cancellation and rescheduling > Late cancellation
       A cancellation less than 24 hours before the arrival window is charged 50% of the visit price.

0.431  Cancellation and rescheduling > Free cancellation
       You can cancel or reschedule a visit free of charge up to 24 hours before the start of the arrival window.

0.418  Prices > Extra charges
       There is no travel fee inside our service areas. Parking fees at your address are added to the invoice at cost.

The first two chunks contain the answer: free up to 24 hours before, 50% after that. The question says "move", the article says "reschedule". Search finds it by meaning, not by matching words.

Try another question:

Terminal
uv run python -m support_desk.search "phone number"
Output
0.383  Opening hours and holidays > Support hours
       Customer support is available Monday to Friday from 8:00 to 18:00, by phone at 555-0142 and through the chat on this website.
...

Troubleshooting#

  • No keyword results for a non-English question: full-text search uses the English dictionary. Vector search works across languages.
  • Vector search returns unrelated chunks: check that the index was built with the same EMBEDDING_MODEL as the questions. After changing the model, delete all rows (delete from chunks; in the SQL Editor) and run the index again.