Guide · Automation

Customer support automation: a RAG bot for your knowledge base

Build a support bot for your knowledge base: chunk articles, retrieve relevant passages with embeddings, cite sources, and hand off unanswered questions.

1 hour time
Python 3.11, numpy stack
~100 lines of code
Intermediate level

Customer support automation usually comes down to one problem: the answers are already written in the FAQ, help center articles and internal policies, but customers cannot find them and contact support instead. A support bot handles these requests for your team. It finds the right passage in your documents, uses it to answer and cites the source. If the knowledge base has no answer, the bot does not make one up. It hands the question off to an agent.

This approach is called RAG (retrieval-augmented generation): first search your documents, then generate an answer from the results. In this guide we build a RAG chatbot in Python with embeddings via POST /v1/embeddings, cosine similarity search in numpy, responses from a text model, escalation to an agent and quality checks on real questions. All requests use a single llmbox key.

How a RAG bot works

The bot works in five steps:

  1. Knowledge base documents are split into chunks of a few paragraphs.
  2. Each chunk is turned into a vector called an embedding. Texts with similar meanings produce nearby vectors, even when the words differ.
  3. The customer's question is also turned into a vector, and the bot looks for the chunks closest to it.
  4. The chunks it finds are passed to a text model together with the question and an instruction to answer only from them.
  5. If there are no suitable chunks, or the model did not find the answer in them, the bot hands the question to an agent.

Steps 1 and 2 run once and are repeated only for changed documents. Steps 3 to 5 run for every question. That is why documents do not have to be reindexed on every request, and most of the cost comes from the text model's answers.

What you need

  • Python 3.11 or newer and the openai and numpy packages: pip install openai numpy.
  • An llmbox key from the Keys section of your account, saved in the LLMBOX_API_KEY environment variable. The process is described in Quickstart.
  • A knowledge base in Markdown: a kb/ folder with files like returns.md, delivery.md, payment.md. If your help center is stored in another format, export it to text first. The # and ## headings are useful: the bot uses them to understand which section a chunk belongs to.

How to choose models

The bot needs two models. The first is an embedding model for search. The catalog has two: text-embedding-3-small and text-embedding-3-large. Start with the small model because it is cheaper. If it misses relevant results in your test questions, compare it with the large model; the "How to evaluate quality" section shows how. The rates of both models are listed on their pages.

The second is a text model for the answer. It should follow instructions precisely and stay within the context; a large context window is not essential here, because only a few chunks go into the request. Fast models suit support answers:

You change the model with one line of code, so it is easy to test the choice on your own questions. More on that in the "How to evaluate quality" section.

How to split the knowledge base into chunks

A whole document is a poor unit for search: an article about payment may cover ten topics, and its vector ends up as an "average" of all of them. Chunks that are too small are bad as well: a single sentence without context loses its meaning. A workable compromise is chunks of a few paragraphs from one section, around a thousand characters.

The function below walks through the document's paragraphs, tracks the current heading and collects paragraphs into a chunk until it reaches the size limit. The section heading is added to the beginning of every chunk, so a chunk such as "Period: 14 days" remains clear to both the search system and the model.

kb.py
import hashlib, json, os, re
from pathlib import Path

import numpy as np
from openai import OpenAI

client = OpenAI(base_url="https://llmbox.cc/v1", api_key=os.environ["LLMBOX_API_KEY"])
EMBED_MODEL = "openai/text-embedding-3-small"
CHAT_MODEL = "deepseek/deepseek-v4.1-flash"
KB_DIR, INDEX = Path("kb"), Path("index.json")


def split_markdown(text: str, max_chars: int = 1000) -> list[str]:
    chunks, section, buf = [], "", []

    def flush():
        if buf:
            body = "\n\n".join(buf)
            chunks.append(f"{section}\n\n{body}" if section else body)
            buf.clear()

    for block in re.split(r"\n\s*\n", text):
        block = block.strip()
        if block.startswith("#"):
            flush()
            first, _, rest = block.partition("\n")
            section, block = first.lstrip("#").strip(), rest.strip()
        if not block:
            continue
        if buf and sum(map(len, buf)) + len(block) > max_chars:
            flush()
        buf.append(block)
    flush()
    return chunks

A paragraph longer than max_chars stays whole as its own chunk: cutting it mid-sentence is worse than getting one long piece. Tables and lists are best kept together with the heading they belong to, and the function does that as long as there are no blank lines between the list items.

How to get embeddings and save the index

The /v1/embeddings endpoint accepts an array of strings, so you can send chunks in batches. The model limits the number of strings and the input length: if a batch is too large, you get a 400 error and need to reduce its size. Vectors are normalized to unit length immediately, so cosine similarity reduces to a dot product.

The index is stored in index.json: for each file, it contains a content hash, the chunks and their vectors. On subsequent runs, the script compares hashes and sends only new and changed documents for embedding. Deleted files disappear from the index automatically because only existing files are included in the new index.

kb.py
def embed(texts: list[str]) -> np.ndarray:
    vectors = []
    for i in range(0, len(texts), 100):
        resp = client.embeddings.create(model=EMBED_MODEL, input=texts[i:i + 100])
        vectors += [d.embedding for d in sorted(resp.data, key=lambda d: d.index)]
    v = np.array(vectors, dtype=np.float32)
    return v / np.linalg.norm(v, axis=1, keepdims=True)


def build_index() -> dict:
    old = json.loads(INDEX.read_text(encoding="utf-8")) if INDEX.exists() else {}
    new = {}
    for path in sorted(KB_DIR.rglob("*.md")):
        text = path.read_text(encoding="utf-8")
        key, digest = path.relative_to(KB_DIR).as_posix(), hashlib.sha256(text.encode()).hexdigest()
        if old.get(key, {}).get("sha256") == digest:
            new[key] = old[key]
            continue
        chunks = split_markdown(text)
        if chunks:
            new[key] = {"sha256": digest, "chunks": chunks, "vectors": embed(chunks).tolist()}
            print("indexed:", key)
    INDEX.write_text(json.dumps(new, ensure_ascii=False), encoding="utf-8")
    return new


INDEX_DATA = build_index()
TEXTS = [c for doc in INDEX_DATA.values() for c in doc["chunks"]]
SOURCES = [key for key, doc in INDEX_DATA.items() for _ in doc["chunks"]]
MATRIX = np.array([v for doc in INDEX_DATA.values() for v in doc["vectors"]], dtype=np.float32)

JSON is the simplest way to store the vectors: the entire file is read into memory, and search comes down to a single matrix-vector multiplication. For a knowledge base of hundreds or thousands of chunks, this is enough. When the knowledge base grows to hundreds of thousands of chunks, or several services need the index at once, move the vectors to a vector database or a vector extension in your DBMS. The bot's logic stays the same; only the search function changes.

If the index takes up a lot of space, you can reduce the vector size of the text-embedding-3-* models with the dimensions parameter. Use the same value for indexing and for search. Details are on the Embeddings documentation page.

How to find the right chunks

Search takes three lines: the question vector is multiplied by the matrix of knowledge base vectors, and the chunks with the highest scores are selected. The closer the score is to one, the closer the chunk is in meaning.

kb.py
def search(question: str, k: int = 4) -> list[tuple[float, str, str]]:
    scores = MATRIX @ embed([question])[0]
    top = np.argsort(-scores)[:k]
    return [(float(scores[i]), SOURCES[i], TEXTS[i]) for i in top]

How many chunks should go into the request? Three to five is usually enough. One is too few: an answer is often assembled from two sections, for example "return period" and "how to submit a request". With ten or more, noise from neighboring topics gets into the context, the model starts mixing conditions, and every request becomes more expensive. Start with four and change k if the check shows that the right chunk often ends up slightly lower.

How to answer strictly from the knowledge base

The main requirement for a support bot is to prevent the model from filling in gaps. The system prompt explicitly forbids answers outside the context, requires a source and defines a signal word for cases with no answer. Each chunk is passed with its file name so the model can include it in the "Source" line.

kb.py
SYSTEM = """You are a customer support agent. Answer only from the knowledge base fragments in the message.
Do not add terms, deadlines or amounts that are not in the fragments.
If the fragments do not contain the answer to the question, reply with one word: OPERATOR.
At the end of the answer, give the file the answer was taken from, in the form "Source: file_name"."""

THRESHOLD = 0.3  # a starting value: tune it on your own questions
HANDOFF = "I'm passing your question to an agent. They will reply in this chat."


def answer(question: str) -> str:
    hits = search(question)
    if not hits or hits[0][0] < THRESHOLD:
        return HANDOFF
    context = "\n\n---\n\n".join(f"[{src}]\n{text}" for _, src, text in hits)
    r = client.chat.completions.create(
        model=CHAT_MODEL,
        messages=[
            {"role": "system", "content": SYSTEM},
            {"role": "user", "content": f"Knowledge base fragments:\n\n{context}\n\nCustomer question: {question}"},
        ],
    )
    text = (r.choices[0].message.content or "").strip()
    return HANDOFF if not text or text.startswith("OPERATOR") else text

Escalation to a person happens in two cases. First the similarity threshold is checked: if even the best chunk is far from the question, no request goes to the text model. Then the model's answer is checked: if the chunks do not contain the needed information, the model returns the signal word. This way the bot does not answer "Do you sell gift cards?" with an invented "yes" when the knowledge base says nothing about it.

Test the module from the command line: python -c "from kb import answer; print(answer('How do I return an item?'))". The first run indexes the whole kb/ folder, and later runs index only the changes.

Where to connect the bot

The answer function does not depend on the channel, so the same knowledge base can be connected in several places.

Telegram bot. The skeleton of an aiogram bot with a key and .env is covered in detail in the guide An AI Telegram bot in 15 minutes: Python and one API key. For support, only the handler changes: instead of a free-form conversation it calls answer, and on escalation it forwards the question to the agents' chat.

bot.py
import asyncio, os
from aiogram import Bot, Dispatcher
from aiogram.types import Message
from kb import answer, HANDOFF

bot = Bot(os.environ["BOT_TOKEN"])
dp = Dispatcher()
OPERATORS_CHAT_ID = int(os.environ["OPERATORS_CHAT_ID"])

@dp.message()
async def handle(msg: Message):
    if not msg.text:
        return
    reply = await asyncio.to_thread(answer, msg.text)
    await msg.answer(reply)
    if reply == HANDOFF:
        await bot.send_message(OPERATORS_CHAT_ID, f"Question from chat {msg.chat.id}:\n{msg.text}")

asyncio.run(dp.start_polling(bot))

asyncio.to_thread is needed because answer uses a synchronous client: this way the bot is not blocked while it waits for the model's reply.

A widget on your website. Wrap answer in a small HTTP endpoint on your server, for example with FastAPI, and call it from the chat on the page. The llmbox key stays on the server: never put it in the page code, or any visitor will see it.

n8n. If requests arrive by email or from a form, an HTTP Request node calls the same endpoint. The workflow then decides whether to send the answer to the customer or create a ticket for an agent. Workflow examples and model setup in n8n are in the guide n8n and AI models: ready-made automation workflows.

How to keep the knowledge base up to date

A knowledge base changes constantly: terms and plans are updated, old rules stop applying. A bot that answers from an outdated policy is worse than a bot with no answer, so reindexing should be part of the normal process of editing the help center.

  • Run build_index() after every change to the files: manually, on a schedule, or in CI after edits are merged. Thanks to the hashes, only changed documents are sent for embedding on subsequent runs.
  • After reindexing, restart the bot or reload index.json so the matrix in memory is updated.
  • When you change the embedding model or the dimensions parameter, delete index.json and reindex the knowledge base from scratch: vectors from different models cannot be compared.
  • Watch the questions passed to agents. A recurring unanswered question is a signal to add an article to the knowledge base.

How to evaluate quality

Without testing, it is hard to tell whether the bot helps or gets in the way. From your support history, collect a few dozen real questions in the customers' own wording, including typos and missing context. For each one, note the file that contains the correct answer. Add some questions outside the scope of the knowledge base too: the bot should pass those to an agent.

eval.py
import json
from kb import search, THRESHOLD

found = total = 0
for line in open("questions.jsonl", encoding="utf-8"):
    item = json.loads(line)  # {"q": "How do I return an item?", "source": "returns.md"} or "source": null
    hits = search(item["q"])
    sources = [src for _, src, _ in hits]
    if item["source"]:
        total += 1
        found += item["source"] in sources
    mark = "agent" if hits[0][0] < THRESHOLD else ""
    print(f"{hits[0][0]:.2f} {mark:9} {item['source'] or '-':15} {sources[0]}  {item['q']}")
print(f"Right document in the results: {found} of {total}")

The script evaluates retrieval, the first half of the bot. Its output shows three things:

  • The share of questions for which the right document appeared in the results. If it is low, revisit the chunking, increase k or compare embedding models.
  • The similarity scores for questions about the knowledge base and for off-topic ones. Set THRESHOLD between them: above the scores of off-topic questions and below most of the correct ones.
  • Cases where retrieval is correct but the document is worded differently from the customers' questions. It is worth adding the customers' wording to those articles.

Review the second half, the answers, manually on the same set: run the questions through answer and note where an answer is inaccurate, where the source is missing and where the bot escalated to an agent unnecessarily. Repeat the check after every change to the model, prompt or chunking so you can see whether the results improved or worsened.

What it costs

The cost has two parts. Embeddings are billed for input tokens only: once when you index the knowledge base, then one short request for each customer question. The rates are on the pages of text-embedding-3-small and text-embedding-3-large.

Most of the cost comes from the text model's answers. The input to each request includes the system prompt, four chunks and the question, so it is noticeably larger than the output. Enter your own number of requests per day and request size in the calculator:

Per month on DeepSeek V4.1 Flash ≈ $2.35 16.2M in · 2.7M out

For questions passed to an agent by the similarity threshold, the text model is not called: only a request to the embedding model is needed. You pay from your balance for actual usage, and every request with its tokens and cost is visible in the Logs section of your account. After the first week of use, you can refine the budget using the actual numbers.

For more on how tokens are counted, see the article What are tokens and how to calculate the cost of a request. The embeddings endpoint parameters are collected in the post Embeddings: POST /v1/embeddings and in the documentation.

Questions

How is a RAG bot different from a regular AI chatbot?

A regular bot answers from the model's general knowledge and may invent policies or terms that do not exist. A RAG bot retrieves passages from your knowledge base before every answer and replies only from them, citing the source.

Which embedding model should I choose?

Start with text-embedding-3-small: it is cheaper. If it often misses relevant results in your test set, compare it with text-embedding-3-large. When you switch models, reindex the whole knowledge base: vectors from different models are incompatible.

Do I need a vector database?

For a knowledge base of hundreds or thousands of chunks, a numpy array in memory and an index file are enough. A vector database or a vector extension in your DBMS becomes useful when the number of chunks grows very large or several services need to read the index.

How often should I reindex the knowledge base?

After every change to the documents. The script in this guide compares file hashes and sends only new and changed documents for embedding, so you can run it after every edit.

How much does such a bot cost?

Embeddings are billed for input tokens only: once when you index the knowledge base, and one short request per question. The main cost is the text model's answers. You can estimate it with the calculator in this article, and the actual amounts are visible in the Logs section of your account.

Published November 15, 2026

One key — every model

GPT, Gemini, DeepSeek, Qwen, video and audio. Pay as you go.

Create a key