Retrieval-augmented generation is the difference between a chatbot that confidently invents your refund policy and one that quotes it. The idea is simple: before the model answers, you fetch the handful of document chunks most likely to contain the answer and place them in the prompt. The model then reasons over evidence instead of memory.
Most RAG tutorials stop at the toy version. This one builds the thing you would actually ship: chunking with overlap, a local embedding index so you are not locked to a second vendor, citation-backed answers, and a confidence check that decides when it is worth paying for a stronger model.
Everything runs against the DeepSeek models served by AiCredits, so the OpenAI SDK client you already have works unchanged.
The moving parts
Ingest — split source documents into overlapping chunks and embed each one.
Retrieve — at query time, embed the question and pull the nearest chunks by cosine similarity.
Generate — hand only those chunks to deepseek-v4-flash and ask for a cited answer.
Verify — detect when retrieval was weak and either escalate the model or refuse to answer.
Step 1 — Point the OpenAI SDK at AiCredits
Install the SDK and confirm the connection before you build anything else. The base URL and a two-word model ID are the only differences from a standard OpenAI setup, which means every pattern you already know transfers directly.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": "Say hello in one short sentence."}],
)
print(resp.choices[0].message.content)
Step 2 — Chunk and embed your documents
Chunk size is the single most consequential knob in a RAG system. Too small and a chunk loses the sentence that gives it meaning. Too large and you dilute the embedding with unrelated text, so it stops matching specific questions. Around 800 characters with roughly 120 characters of overlap is a sensible starting point — overlap exists so that a fact straddling a boundary still appears whole in at least one chunk.
For embeddings, this tutorial uses a small local sentence-transformer. It keeps the retrieval half of the stack free, offline, and swappable, which matters when you want to re-embed a corpus without re-uploading it anywhere. If you would rather keep everything on one API, check the current embedding lineup in the AiCredits docs before you commit to a dimension — changing embedding models later means re-indexing every chunk.
import numpy as np
from sentence_transformers import SentenceTransformer
embedder = SentenceTransformer("all-MiniLM-L6-v2")
def chunk_text(text, size=800, overlap=120):
assert overlap < size, "overlap must be smaller than chunk size"
chunks, start = [], 0
while start < len(text):
end = min(start + size, len(text))
chunks.append(text[start:end])
if end == len(text):
break
start = end - overlap
return chunks
def build_index(docs):
"""docs: {"doc-id": "full document text", ...}"""
chunks = []
for doc_id, text in docs.items():
for i, piece in enumerate(chunk_text(text)):
chunks.append({"id": f"{doc_id}#{i}", "text": piece})
vectors = embedder.encode(
[c["text"] for c in chunks], normalize_embeddings=True
)
return chunks, np.asarray(vectors)
Step 3 — Retrieve by cosine similarity
Because both chunks and queries are unit-normalised, a plain dot product is already cosine similarity — no extra maths, no vector database required. A NumPy array of a few thousand chunks searches in milliseconds, so resist adding infrastructure until you have measured a reason to. Reach for a dedicated vector store when you need persistence, per-tenant filtering, or millions of vectors.
def retrieve(query, chunks, vectors, k=4):
q = embedder.encode([query], normalize_embeddings=True)[0]
scores = vectors @ q # cosine similarity on unit vectors
top = np.argsort(-scores)[:k]
return [chunks[i] for i in top], scores[top]
Step 4 — Generate a grounded, cited answer
The prompt does more anti-hallucination work than the model choice does. Three rules matter: only answer from the context block, cite the bracketed chunk ID after each claim, and return a fixed refusal string when the context is insufficient. That last rule is what turns a vague "the model seems unsure" into a checkable condition in your code.
Put the context before the question. Models attend more reliably to material they have already read when the instruction arrives at the end, and every chunk carries its ID so the answer is traceable back to a source.
SYSTEM = (
"You are a documentation assistant. Answer only from the <context> block. "
"Cite the bracketed chunk id after each claim. If the answer is not in "
"the context, reply exactly: Not in the provided documents."
)
def answer(question, chunks, vectors, history=None, k=4,
model="deepseek-v4-flash"):
hits, _ = retrieve(question, chunks, vectors, k=k)
context = "\n\n".join(f"[{h['id']}]\n{h['text']}" for h in hits)
messages = [{"role": "system", "content": SYSTEM}]
messages += history or []
messages.append({
"role": "user",
"content": f"<context>\n{context}\n</context>\n\n{question}",
})
stream = client.chat.completions.create(
model=model,
messages=messages,
temperature=0.2,
stream=True,
)
out = []
for event in stream:
delta = event.choices[0].delta.content
if delta:
out.append(delta)
print(delta, end="", flush=True)
print()
return "".join(out)
Step 5 — Escalate to deepseek-v4-pro only when retrieval is weak
Running the strongest model on every turn is wasteful when most questions are answered by a single obvious chunk. Instead, use retrieval confidence as the router: if the best cosine score clears a floor you tuned on your own data, answer with deepseek-v4-flash; if it does not, the question is probably multi-hop, ambiguous, or simply outside the corpus, and that is exactly when the stronger model earns its extra cost.
def answer_adaptive(question, chunks, vectors, confidence_floor=0.35):
_, scores = retrieve(question, chunks, vectors, k=1)
best = float(scores[0]) if scores.size else 0.0
if best >= confidence_floor:
return answer(question, chunks, vectors) # fast path
return answer( # escalate
question,
chunks,
vectors,
model="deepseek-v4-pro",
)
Treat confidence_floor as a tunable, not a constant. Log the best score alongside every answer and every user thumbs-down, then move the threshold until escalation happens only when it actually helps.
Where flash ends and pro begins
| Stage | Model | Why |
|---|---|---|
| Chunk labelling during ingest | deepseek-v4-flash | High volume, tolerant of minor mistakes |
| Default chat turns | deepseek-v4-flash | Low latency on every message, cheapest per turn |
| Low-confidence or multi-hop questions | deepseek-v4-pro | Better at reconciling chunks that disagree |
| Final self-check pass | deepseek-v4-flash | Cheap way to flag unsupported sentences |
Five failure modes that quietly break RAG
Chunks with no ID — the model cannot cite, so you cannot verify. Always embed an identifier in the prompt text.
Retrieval on raw pronouns — a follow-up like "what about the second one?" embeds to nothing useful. Rewrite the query using chat history before searching.
Stuffing everything into one prompt — more context is not better context. Retrieve fewer, higher-ranked chunks.
No explicit refusal string — without one you have no programmatic way to detect abstention.
Assuming the index is current — re-embed on every document change, or your answers quietly go stale.
Running this in production on AiCredits
The whole stack stays OpenAI-compatible, so nothing in the code above changes when you deploy it. AiCredits serves DeepSeek credits to international developers who pay by card or PayPal — no Chinese phone number or bank account required, which is usually the first blocker people hit when they try to call DeepSeek directly.
Pricing is qualitative and worth understanding before you scale: cache hits are cheaper than fresh input, off-peak traffic costs less than peak, and deepseek-v4-pro costs more per token than deepseek-v4-flash. That is exactly why the escalation router in Step 5 pays for itself — you reserve the expensive model for the minority of turns that genuinely need it. Current rates live at aicreditsapi.com/pricing.
FAQ
No. A NumPy array handles a few thousand chunks in milliseconds and keeps the tutorial dependency-free. Move to a dedicated vector store when you need persistence across restarts, metadata filtering, or a corpus large enough that a full scan becomes the bottleneck.
It keeps retrieval offline, free, and independently swappable from your generation model. If you prefer one vendor for everything, check the current embedding models in the AiCredits documentation first — whatever dimension you pick, you will have to re-index the corpus if you change it later.
Four things together: a system prompt that forbids outside knowledge, bracketed chunk IDs that force citation, a fixed refusal string you can detect in code, and low temperature. Then measure — log retrieval scores next to user feedback and tune from there.
No. AiCredits is built for international developers and accepts card or PayPal, so you can sign up and run the code in this tutorial the same day.