AiCredits
RAG, end to end

Building a RAG Chatbot Over Your Docs With an OpenAI-Compatible Endpoint

Build a docs RAG chatbot on an OpenAI-compatible endpoint with working Python: chunking, BM25 retrieval, grounded prompts, streaming, and verification.

Published 2026-11-04 Updated 2026-11-04 9 min

Why an OpenAI-compatible endpoint is the right base for docs RAG

A documentation chatbot lives or dies on retrieval, not on the model. The model is one interchangeable component at the end of a pipeline: chunk, retrieve, assemble context, generate, verify. Everything before generation is yours to control, and everything after generation is a quality gate you can add cheaply.

The practical reason to build on an OpenAI-compatible endpoint is that all the boring infrastructure already exists. You keep the official OpenAI SDK, streaming, retries, and the same message schema. Swapping providers becomes a two-line change (base_url and model), which means you can tune retrieval against a fixed model and tune the model against fixed retrieval instead of changing both at once and guessing which one helped.

Retrieval is the product. The model is the last mile.

The five moving parts

  • A chunker that respects markdown headings, so every chunk carries its section title into the index.

  • A retriever — lexical first, dense later, hybrid when you have evidence you need it.

  • A context builder with stable citation labels, so the model can point at sources without you parsing prose.

  • A grounded system prompt that has an explicit escape hatch for 'I do not know'.

  • An optional verification pass on a stronger model for high-stakes answers.

The pipeline below is complete and runnable. No LangChain, no vector database, no embedding service — you can have a working bot over a docs folder in an afternoon and add sophistication only where it measurably helps.

Step 1 — Chunk on headings, not on character count

Fixed-size chunking is the most common self-inflicted wound in RAG. Split a configuration page every 800 characters and half your chunks start mid-table with no idea which setting they describe. Splitting on markdown headings keeps the section title attached, which is often the exact phrase the user searched for.

Keep chunks small enough that four of them fit comfortably in a prompt, but large enough to hold a complete procedure. Around 900 characters is a reasonable starting point for prose docs; raise it for pages built around long code samples.

import pathlib, re

def chunk_markdown(text, max_chars=900):
    # Split on headings so each chunk keeps the section it belongs to.
    parts = re.split(r'(?m)^(#{1,3} .+)$', text)
    chunks, title, buf = [], 'Untitled', ''
    for part in parts:
        if re.match(r'^#{1,3} ', part):
            if buf.strip():
                chunks.append({'title': title, 'text': buf.strip()})
            title, buf = part.lstrip('#').strip(), ''
        else:
            for para in part.split('\n\n'):
                if buf.strip() and len(buf) + len(para) > max_chars:
                    chunks.append({'title': title, 'text': buf.strip()})
                    buf = ''
                buf += para + '\n\n'
    if buf.strip():
        chunks.append({'title': title, 'text': buf.strip()})
    return chunks

docs = []
for path in pathlib.Path('docs').rglob('*.md'):
    for chunk in chunk_markdown(path.read_text(encoding='utf-8')):
        chunk['source'] = str(path) + '#' + chunk['title']
        docs.append(chunk)

print(len(docs), 'chunks indexed')

Step 2 — Start with lexical retrieval (yes, really)

API documentation is dense with exact tokens: config keys, error codes, endpoint paths, flag names. BM25 indexes those perfectly, needs no embedding service, costs nothing to re-index when you add a page, and returns results you can actually debug — you can see which term matched. Those properties matter more in the first month than semantic elegance.

Dense embeddings win on paraphrase: a user asking 'how do I rotate my credentials' should still find a page titled 'Key rotation'. The mature setup is hybrid — BM25 plus a vector index, fused with reciprocal rank fusion. But ship lexical first, collect the queries it misses, and let that list tell you whether you need embeddings at all.

import math, re
from collections import Counter

def tokenize(s):
    return re.findall(r'[a-z0-9_]+', s.lower())

class BM25:
    def __init__(self, docs, k1=1.5, b=0.75):
        self.docs, self.k1, self.b = docs, k1, b
        self.tfs = [Counter(tokenize(d['title'] + ' ' + d['text'])) for d in docs]
        self.lens = [sum(tf.values()) for tf in self.tfs]
        self.avg = sum(self.lens) / max(len(self.lens), 1)
        df = Counter()
        for tf in self.tfs:
            df.update(tf.keys())
        n = len(docs)
        self.idf = {t: math.log(1 + (n - c + 0.5) / (c + 0.5)) for t, c in df.items()}

    def search(self, query, k=4):
        scored = []
        for i, tf in enumerate(self.tfs):
            score = 0.0
            for term in tokenize(query):
                if term not in tf:
                    continue
                f, length = tf[term], self.lens[i]
                score += self.idf.get(term, 0.0) * f * (self.k1 + 1) / (
                    f + self.k1 * (1 - self.b + self.b * length / self.avg))
            scored.append((score, i))
        scored.sort(reverse=True)
        return [self.docs[i] for s, i in scored[:k] if s > 0]

index = BM25(docs)
for hit in index.search('how do I rotate an api key', k=3):
    print('-', hit['source'])

Step 3 — Build the prompt so citation is mechanical

Number every context block and tell the model to cite the numbers. This gives you citations for free, lets you link back to the exact page, and — more usefully — makes unsupported claims visible. If the answer cites [4] but block 4 does not contain the claim, you have a bug to investigate.

The escape hatch matters just as much. Without an explicit instruction to say 'I do not know', a chat model will happily invent a parameter name that looks plausible. Give it a sanctioned way out and it takes it far more often than you expect.

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ['AICREDITS_API_KEY'],
    base_url='https://api.aicreditsapi.com/v1',
)

SYSTEM = (
    'You answer using ONLY the numbered context blocks. Cite them as [1], [2]. '
    'If the context does not contain the answer, say you do not know, name what '
    'is missing, and suggest a better search phrase. Never invent config keys, '
    'endpoint paths, or parameter names.'
)

def build_context(hits):
    return '\n\n'.join(
        f"[{i}] {h['title']} - {h['source']}\n{h['text']}"
        for i, h in enumerate(hits, 1)
    )

def answer(question, history, index):
    hits = index.search(question, k=4)
    messages = [
        {'role': 'system', 'content': SYSTEM},
        *history[-6:],
        {'role': 'user', 'content': 'Context:\n' + build_context(hits)
                                    + '\n\nQuestion: ' + question},
    ]
    resp = client.chat.completions.create(
        model='deepseek-v4-flash',
        messages=messages,
        temperature=0.2,
    )
    return resp.choices[0].message.content

Step 4 — Stream the answer, bound the history

Streaming is a UX decision, not a performance one: a support bot that starts typing immediately feels dramatically better than one that pauses. Bound the history to the last few turns as well. Old turns are the main source of context bloat in chat RAG, and they compete with the retrieved documentation for the model's attention.

def chat_loop(index):
    history = []
    while True:
        question = input('\nYou: ').strip()
        if question.lower() in {'exit', 'quit'}:
            break
        hits = index.search(question, k=4)
        messages = [
            {'role': 'system', 'content': SYSTEM},
            *history[-6:],
            {'role': 'user', 'content': 'Context:\n' + build_context(hits)
                                        + '\n\nQuestion: ' + question},
        ]
        stream = client.chat.completions.create(
            model='deepseek-v4-flash',
            messages=messages,
            temperature=0.2,
            stream=True,
        )
        print('\nBot: ', end='')
        reply = ''
        for chunk in stream:
            delta = chunk.choices[0].delta.content or ''
            reply += delta
            print(delta, end='', flush=True)
        print()
        history += [
            {'role': 'user', 'content': question},
            {'role': 'assistant', 'content': reply},
        ]

chat_loop(index)

Step 5 — Add a verification pass where it pays off

Drafting is a high-volume, low-stakes job: flash handles it well. Verification is the opposite — it requires carefully comparing an answer against context, which is exactly the kind of reading task a stronger model does better. Run the check on a sample of traffic, or only on questions your logs flag as sensitive (billing, security, data deletion), rather than on every turn.

Compounding failure is the thing to watch for. Catching one wrong answer per session is usually the difference between a bot users trust and one they stop opening.

def verify(question, reply, hits):
    # Run only for high-stakes answers; it doubles the cost of a turn.
    resp = client.chat.completions.create(
        model='deepseek-v4-pro',
        messages=[
            {'role': 'system',
             'content': 'You are a strict fact-checker. Compare the answer to the '
                        'context. Reply PASS or FAIL followed by one sentence.'},
            {'role': 'user',
             'content': 'Context:\n' + build_context(hits)
                        + '\n\nQuestion: ' + question + '\n\nAnswer: ' + reply},
        ],
        temperature=0,
    )
    verdict = resp.choices[0].message.content.strip()
    return verdict.upper().startswith('PASS'), verdict

Choosing a model per stage

StageSuggested modelWhy
Drafting the answerdeepseek-v4-flashFast and inexpensive enough to run on every turn, including streaming
Rewriting a follow-up into a search querydeepseek-v4-flashVery short input, very low risk
Offline chunk labelling and summariesdeepseek-v4-flashBatched once at index time; throughput matters more than depth
Groundedness verificationdeepseek-v4-proRequires careful cross-reading; used on a small share of traffic
Hard debugging and long-context synthesisdeepseek-v4-proWorth the extra spend on the few questions flash gets wrong

Where the cost and latency actually go

  • Context size dominates the bill. Four 900-character chunks is a bigger lever than which model you pick — tighten retrieval before you downgrade the model.

  • Cache hits are cheaper. Keep the system prompt and any static documentation prefix byte-identical between calls so the provider can reuse the prefix instead of reprocessing it.

  • Off-peak requests cost less than peak ones. Move re-indexing, backfills, and evaluation runs to quiet hours.

  • Pro costs more than flash per token. Reserve it for verification and escalation, not for the default path.

  • Latency follows output length. Asking for a three-sentence answer with citations cuts wait time more than any infrastructure change.

Current rates live at aicreditsapi.com/pricing — check there rather than trusting a number in a blog post, including this one.

Why the endpoint in these snippets is AiCredits

Every example above talks to https://api.aicreditsapi.com/v1. AiCredits sells DeepSeek API credits with international card or PayPal checkout and no Chinese phone number or bank account requirement, which is the practical blocker for a lot of developers who want to build on these models. The wire format is the standard OpenAI one, so the code you just read is unchanged — if you move providers later, only base_url and model change.

FAQ

Do I need a vector database to ship this?

No. The BM25 index above is roughly 30 lines and handles exact-token queries — config keys, error codes, endpoint names — better than embeddings usually do. Add a vector store when your logs show paraphrase misses, not before.

How many chunks should I retrieve?

Start with four. More chunks means more context, more cost, and a higher chance of the model latching onto an irrelevant block. If answers feel thin, improve chunking before raising k.

Can I switch to a different provider later?

Yes. Because the base_url is the only provider-specific line, moving means changing base_url and model. Keep the OpenAI SDK wrapper in one module so the swap touches one file.

How do I stop the bot from answering off-topic questions?

Two layers: return an empty retrieval result as a hard stop before calling the model, and instruct the model in the system prompt to say it does not know rather than answer from general knowledge.

Does this work with streaming?

Yes. The endpoint supports stream=True with the same chunk shape as the OpenAI API, so any client-side streaming code you already have works unchanged.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×