How to Build a RAG Pipeline with DeepSeek (Step-by-Step)

You have a folder of PDFs, internal docs, or support tickets. You want a chatbot that answers questions from that content — accurately, with citations, without inventing facts. That is what this DeepSeek RAG tutorial covers, end to end, on the current DeepSeek API. We will chunk documents, embed them with a dedicated embedding model, store the vectors in FAISS, retrieve the top matches at query time, and pass them to deepseek-flash for grounded answers. By the end you will have a working Python pipeline you can extend with LangChain, LlamaIndex, or your own framework, plus a costed example at DeepSeek’s October 2026 prices.
What you will build

A minimal but complete retrieval-augmented generation (RAG) pipeline that grounds DeepSeek answers in your own documents. The architecture has two halves. First, an offline indexing step: split documents into chunks, generate embeddings with a dedicated embedding model, store them in a vector index. Second, an online query step: embed the user’s question, find the top-k matching chunks, and send those chunks plus the question to deepseek-flash through the chat completions API.
One important caveat up front: DeepSeek’s API models are chat models, not embedding models. DeepSeek’s API documentation lists no embeddings endpoint and its pricing page lists only the two chat models (as of October 2026), so use a dedicated embedding model (Sentence Transformers, BGE, GTE-Qwen2, or similar) for the retrieval side, and DeepSeek for the generation side.
Prerequisites
- Python 3.10 or newer.
- A DeepSeek account with a funded balance — see how to get a DeepSeek API key.
- The OpenAI Python SDK (the DeepSeek API is OpenAI-compatible).
- FAISS for the vector index, and
sentence-transformersfor embeddings. - Roughly 200 MB of free disk space for the embedding model and a small index.
- A folder of source documents — Markdown, plain text, or extracted PDF text.
Install everything in one line:
pip install openai faiss-cpu sentence-transformers tiktoken pypdf
Step 1: Set up the DeepSeek client
The DeepSeek chat surface is OpenAI-compatible. Chat requests hit POST /chat/completions against the base URL https://api.deepseek.com; an Anthropic-compatible format is also available at https://api.deepseek.com/anthropic. For this tutorial we will use the OpenAI SDK pattern, with the API key read from an environment variable.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["DEEPSEEK_API_KEY"],
base_url="https://api.deepseek.com",
)
Two notes on model selection. DeepSeek’s pricing page lists two model IDs (October 2026): deepseek-flash, served by DeepSeek-V4.1-Flash-1017, and deepseek-v4-pro, served by DeepSeek-V4-Pro-0813. Both have open weights under the MIT license, a 1M-token context window and up to 384K tokens of output; only deepseek-flash accepts images. Thinking mode is on by default for both. For most RAG workloads deepseek-flash is the sensible default — deepseek-v4-pro costs 3.3× as much on output and 4.4× on cache-miss input.
If you have older code referencing deepseek-chat or deepseek-reasoner: those IDs were scheduled for retirement on 2026-07-24 at 15:59 UTC and are no longer listed in DeepSeek’s docs. The legacy names deepseek-v4-flash and deepseek-v4-flash-vision-exp are still accepted but are served by DeepSeek-V4.1-Flash-1017 at the Flash price. Migrating is a one-line model= change to deepseek-flash; base_url does not change. For a deeper walkthrough of the SDK setup, see the DeepSeek API getting started guide.
Step 2: Prepare and chunk your documents
Chunking is unglamorous and matters more than the model. If chunks are too big, retrieval pulls in noise and hurts precision. Too small, and the model loses the surrounding context it needs to answer. A reasonable starting point is 500–800 tokens per chunk with a 50–100 token overlap between adjacent chunks (the code below splits on words as a simple approximation).
from pathlib import Path
def load_documents(folder: str) -> list[dict]:
docs = []
for path in Path(folder).rglob("*.txt"):
docs.append({"id": str(path), "text": path.read_text(encoding="utf-8")})
return docs
def chunk_text(text: str, size: int = 700, overlap: int = 80) -> list[str]:
words = text.split()
chunks, start = [], 0
while start < len(words):
end = min(start + size, len(words))
chunks.append(" ".join(words[start:end]))
if end == len(words):
break
start = end - overlap
return chunks
documents = load_documents("./data")
chunks = []
for doc in documents:
for i, c in enumerate(chunk_text(doc["text"])):
chunks.append({"source": doc["id"], "chunk_id": i, "text": c})
For PDFs, run them through pypdf first and feed the extracted text into load_documents. For HTML, strip tags before chunking. Keep the source path on every chunk so you can show citations back to the user later.
Step 3: Generate embeddings and build the index
We will use all-MiniLM-L6-v2 from Sentence Transformers — small, fast, 384 dimensions, and good enough to demonstrate the pipeline. For higher quality, swap it later for BAAI/bge-large-en-v1.5 or Alibaba-NLP/gte-Qwen2-7B-instruct at the cost of more memory.
import numpy as np
import faiss
from sentence_transformers import SentenceTransformer
embedder = SentenceTransformer("all-MiniLM-L6-v2")
texts = [c["text"] for c in chunks]
vectors = embedder.encode(texts, normalize_embeddings=True, show_progress_bar=True)
vectors = np.asarray(vectors, dtype="float32")
dim = vectors.shape[1]
index = faiss.IndexFlatIP(dim) # inner product on L2-normalised vectors = cosine
index.add(vectors)
faiss.write_index(index, "rag.index")
Persist the chunks alongside the index — for a small corpus a JSON file is fine; for anything larger, use SQLite or a real vector database. The DeepSeek with LangChain and DeepSeek with LlamaIndex tutorials show how to wire DeepSeek into those frameworks if you would rather use their vector-store integrations.
Step 4: Retrieve the top-k chunks
Embed the query with the same model used for indexing, then search the FAISS index. Returning four to six chunks is a sensible starting band — enough context, not so much that you blow the budget on irrelevant tokens.
def retrieve(query: str, k: int = 5) -> list[dict]:
q = embedder.encode([query], normalize_embeddings=True)
q = np.asarray(q, dtype="float32")
scores, idx = index.search(q, k)
return [
{**chunks[i], "score": float(s)}
for s, i in zip(scores[0], idx[0])
if i != -1
]
Very low cosine scores usually mean weak matches. Choose a cut-off from the scores your own corpus returns for answerable and unanswerable questions, and if the top result falls below it, return “I don’t know” rather than forcing the model to answer from weak context.
Step 5: Generate the grounded answer

Now wire retrieval into the chat call. Two things matter here: the system prompt must constrain the model to the context, and the user message must clearly delimit context from question.
SYSTEM_PROMPT = (
"You are a documentation assistant. Answer using ONLY the context "
"between <context> tags. If the answer is not in the context, "
"reply exactly: 'I don't know based on the provided documents.' "
"Cite the source path in square brackets after each claim."
)
def build_prompt(query: str) -> str:
hits = retrieve(query, k=5)
context = "\n\n".join(
f"[{h['source']}#chunk{h['chunk_id']}]\n{h['text']}" for h in hits
)
return f"<context>\n{context}\n</context>\n\nQuestion: {query}"
def answer(query: str) -> str:
resp = client.chat.completions.create(
model="deepseek-flash",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": build_prompt(query)},
],
temperature=0.0, # only applies in non-thinking mode
max_tokens=800,
extra_body={"thinking": {"type": "disabled"}},
)
return resp.choices[0].message.content
print(answer("What is our refund policy for annual subscriptions?"))
A few notes on that snippet. Thinking mode is DeepSeek’s default, and in thinking mode temperature is accepted but has no effect, so the call switches thinking off with extra_body={"thinking": {"type": "disabled"}} to get short, deterministic extraction-style answers. DeepSeek’s temperature guidance lists 0.0 for code generation and mathematics; a low value suits answers that should quote the context. If your questions need multi-step reasoning over the retrieved evidence, use extra_body={"thinking": {"type": "enabled"}} with reasoning_effort="high" instead and drop temperature; the answer still arrives in content, with reasoning_content alongside it. The API is stateless: DeepSeek does not retain prior turns, so for multi-turn RAG you must resend the conversation history with every request — this is different from the web chat, which keeps session state for you.
Step 6: Add structured citations with JSON mode
Free-text answers are fine for chat. For agents, evaluation, or UI components, you usually want structured output. DeepSeek supports JSON mode via response_format={"type": "json_object"}. Important caveat: it is designed to return valid JSON, not guaranteed. The prompt must include the word “json” plus an example schema, and max_tokens needs to be high enough to avoid truncation — a truncated JSON is invalid JSON.
JSON_SYSTEM = (
"Reply with valid json matching this schema: "
'{"answer": str, "citations": [str], "confidence": float}. '
"Use ONLY the provided context. If unknown, set answer to "
"'I don't know' and citations to []."
)
query = "What is our refund policy for annual subscriptions?"
resp = client.chat.completions.create(
model="deepseek-flash",
messages=[
{"role": "system", "content": JSON_SYSTEM},
{"role": "user", "content": build_prompt(query)},
],
response_format={"type": "json_object"},
temperature=0.0,
max_tokens=1200,
extra_body={"thinking": {"type": "disabled"}},
)
Handle the occasional empty-content case in client code. See the DeepSeek API JSON mode reference for full details.
Step 7: Cost the pipeline honestly
Prices as of October 2026, from DeepSeek’s Models & Pricing page, per 1M tokens for deepseek-flash: cache hit $0.006 peak / $0.003 off-peak, cache miss $0.30 / $0.15, output $1.20 / $0.60. For deepseek-v4-pro: $0.044 / $0.022, $1.32 / $0.66 and $3.96 / $1.98. Peak hours are 01:00–04:00 and 06:00–10:00 UTC, Monday to Friday, excluding Chinese public holidays; every other hour is billed at the off-peak rate, which is half the peak rate.
Worked example for a customer-support RAG handling 100,000 queries per month, with a stable 1,500-token system prompt (cached after the first call), 3,000 tokens of retrieved context plus a 100-token question per call (uncached), and a 400-token answer:
Bucket (deepseek-flash) |
Tokens (per month) | Peak | Off-peak |
|---|---|---|---|
| Input, cache hit (system) | 150,000,000 | 150M × $0.006 = $0.90 | 150M × $0.003 = $0.45 |
| Input, cache miss (context + question) | 310,000,000 | 310M × $0.30 = $93.00 | 310M × $0.15 = $46.50 |
| Output | 40,000,000 | 40M × $1.20 = $48.00 | 40M × $0.60 = $24.00 |
| Total | 500,000,000 | $141.90 | $70.95 |
The same workload on deepseek-v4-pro would cost $574.20 if run entirely at peak ($6.60 + $409.20 + $158.40) and $287.10 entirely off-peak ($3.30 + $204.60 + $79.20). Real traffic usually straddles both periods, so your bill lands between the two totals. The retrieved context dominates spend — $90.00 of the $141.90 deepseek-flash peak total, about 63% — so chunk size and top-k are the biggest cost levers, not just the model choice. For more cost modelling, the DeepSeek cost estimator handles arbitrary workloads.
Step 8: Verify it worked
Three quick sanity checks before you ship anything:
- Retrieval recall. Hand-write a set of questions whose answers you know are in the corpus, and check how often the correct chunk appears in the top 5. If it is often missing, the embedding model or chunk size is wrong, not the LLM.
- Refusal behaviour. Ask a few questions whose answers are not in the corpus. The model should refuse. If it invents an answer, tighten the system prompt and, in non-thinking mode, lower the temperature.
- Citation accuracy. Spot-check that the bracketed source paths in the answer actually contain the claimed fact.
Common errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| 402 Insufficient Balance | Account has run out of balance | Check the balance and top up in the DeepSeek platform |
| Model invents facts not in context | Weak system prompt, or high temperature in non-thinking mode | Add an explicit “use ONLY the context” instruction; in non-thinking mode set temperature=0.0 |
| JSON mode returns empty or invalid content | Prompt missing the word “json” or a schema example; output truncated | Include both, raise max_tokens above any plausible output length, and retry on the occasional empty reply |
| Slow embeddings on large corpora | Single-process encoding | Batch with batch_size=64, or move to a GPU machine for indexing |
| Retrieval returns unrelated chunks | Embedding model mismatch with content language or domain | Switch to BGE-large or a domain-specific model; try hybrid BM25 + dense retrieval |
Where to go from here

Three upgrades are worth adding once the basic pipeline is working. First, hybrid retrieval: combine dense vectors with BM25 to catch exact-match queries that embeddings miss. Second, re-ranking: send the top 20 candidates from FAISS through a cross-encoder (such as bge-reranker-large) and keep only the top 5, so the model sees fewer, better-matched chunks. Third, context caching: structure prompts so the system message and any stable instructions sit at the start, where DeepSeek’s cache will detect the repeated prefix and bill at the cache-hit rate.
If you want to host a chat UI on top of this pipeline, the DeepSeek Streamlit app walkthrough plugs straight into the answer() function above. For Discord or Telegram front ends, see the DeepSeek Discord bot tutorial. For other patterns and end-to-end recipes, browse the full library of DeepSeek tutorials.
Frequently asked questions
Can DeepSeek be used for retrieval-augmented generation?
Yes. deepseek-flash and deepseek-v4-pro work as the generator in a RAG pipeline: retrieved context goes in through standard chat messages, and both models have a 1M-token context window. Use a dedicated embedding model (Sentence Transformers, BGE, or GTE-Qwen2) for the retrieval side, since DeepSeek’s API offers chat models, not embeddings. Framework-based setups are covered in the DeepSeek with LangChain tutorial.
What is the best DeepSeek model for RAG: deepseek-flash or deepseek-v4-pro?
For most RAG workloads, deepseek-flash (DeepSeek-V4.1-Flash-1017) is the sensible default: it costs $1.20 per 1M output tokens at peak and $0.60 off-peak, against $3.96 / $1.98 for deepseek-v4-pro — 3.3× more. It is also the only one of the two that accepts images. Consider deepseek-v4-pro only if it measurably improves answers on your own evaluation questions. Compare both on the DeepSeek V4 models page.
How does the DeepSeek API differ from the web chat for RAG?
The API is stateless — every request must include the full conversation history and any retrieved context. The web chat and mobile app, by contrast, maintain session history server-side. For RAG you almost always want the API, since you control retrieval and prompt construction. Authentication and quickstart code live in the DeepSeek API documentation.
Does DeepSeek provide its own embedding model?
Not through its API: as of October 2026, DeepSeek’s API documentation lists no embeddings endpoint, and the pricing page lists only the two chat models. RAG pipelines pair DeepSeek’s generator with an external embedding model — Sentence Transformers MiniLM for fast prototypes, BGE-large or GTE-Qwen2 for higher recall. See the DeepSeek OpenAI SDK compatibility notes for what the OpenAI-compatible surface does and does not expose.
How much does a DeepSeek RAG application cost to run?
For 100,000 queries per month with a cached 1,500-token system prompt, 3,100 uncached input tokens (retrieved context plus question) and a 400-token answer, deepseek-flash works out to $141.90 per month if every call runs at peak and $70.95 if every call runs off-peak, at October 2026 prices ($0.006 / $0.003 cache hit, $0.30 / $0.15 cache miss, $1.20 / $0.60 output per 1M tokens). Model the numbers for your own workload with the DeepSeek API pricing reference.
Sources & Methodology
Primary sources
- OfficialDeepSeek API documentationEndpoints, request/response shape, model IDsLast checked: October 25, 2026
- PricingDeepSeek API pricing pagePer-1M-token rates, billing units, cache-hit pricingLast checked: October 25, 2026
Methodology
Information in this article was checked against the official DeepSeek documentation, the article's cited primary sources, and the deepseekai.guide pricing dataset on the date shown above. Where third-party numbers are quoted, the originating source is linked inline so the reader can verify and re-check.
Data confidence
High for facts cited inline with primary-source links; medium for context narrative.
Editorial note
AI tooling moves quickly. If you spot an outdated number or a broken link, the contact link in the footer is the fastest way to flag it for the editorial team.
