DeepSeek RAG Knowledge Base Setup Tutorial
Build an enterprise-grade knowledge base Q&A system from scratch using DeepSeek and LangChain. Document loading, vector embeddings, semantic retrieval, intelligent Q&A with source citations, complete code, ready to use.
Start LearningWhat is RAG and why do we need it?
RAG (Retrieval-Augmented Generation) is the core technology that enables large models to answer private knowledge. Without RAG, large models can only answer content from training data; with RAG, large models can answer accurately based on your documents, databases, and knowledge bases.
RAG Principle Overview
Understanding how RAG works is a prerequisite for building a high-quality knowledge base. RAG consists of three core stages: Retrieval, Augmented, and Generation.
The Three Core Stages of RAG
| Retrieval | Convert the user's question into a vector and find the most relevant document chunks in the vector database. This is the "search" stage of RAG. |
| Augmented | Concatenate the retrieved document chunks as context into the prompt. This is the "knowledge injection" stage of RAG. |
| Generation | The DeepSeek model generates an answer based on the augmented prompt. This is the "output" stage of RAG. |
RAG Architecture Flow
The complete RAG architecture is divided into two phases: offline and online.
Offline Phase (Knowledge Base Construction):
- Document Loading: Read various documents such as PDF, TXT, Markdown, web pages, etc.
- Text Splitting: Split long documents into appropriately sized text chunks.
- Vector Embedding: Convert text chunks into vector representations.
- Vector Storage: Store vectors in a vector database such as ChromaDB.
Online Phase (Q&A):
- User Query: Receive the user's input question.
- Vector Retrieval: Convert the question into a vector and find the most similar text chunks in the database.
- Context Concatenation: Use the retrieved results as context to construct an augmented prompt.
- Model Generation: DeepSeek generates an answer based on the augmented prompt and includes source citations.
RAG vs Fine-tuning
| Comparison Dimension | RAG | Fine-tuning |
|---|---|---|
| Knowledge Update | Real-time updates; adding or removing documents takes effect immediately. | Requires retraining; long cycle. |
| Cost | Low; only needs a vector database. | High; requires GPU training resources. |
| Interpretability | Traceable to specific documents. | Black box; difficult to trace knowledge sources. |
| Applicable Scenarios | Knowledge base Q&A, document retrieval, customer service systems. | Style imitation, domain-specific terminology, instruction following |
For most enterprise scenarios, we recommend a combination of RAG and fine-tuning: use RAG for dynamic knowledge and fine-tuning to optimize model behavior. For more model details, see DeepSeek Model Architecture Explained.
Environment Preparation
Install the necessary Python dependencies. The following command installs all libraries required for RAG development at once.
Install Core Dependencies
DeepSeek API Configuration
The RAG system uses the DeepSeek API as the generation model. Set an environment variable to store the API key:
Note
If you use a locally deployed DeepSeek model via Ollama, no API key is needed; just point the API Base URL to http://localhost:11434/v1. See DeepSeek Local Deployment Tutorial.
Document Loading
LangChain provides a rich set of document loaders that support various formats such as PDF, TXT, Markdown, web pages, CSV, and more. Choose the loader that fits your document format.
Loading PDF Documents
Loading TXT and Markdown
Loading Web Pages
Using Unstructured to Load General Documents
Unstructured is a powerful document parsing library that supports 20+ formats including PDF, Word, PPT, Excel, HTML, images, and more. Recommended for complex document scenarios:
Text Splitting
Text splitting is a critical step for RAG quality. Too large splits lead to imprecise retrieval, too small splits lose context. LangChain's RecursiveCharacterTextSplitter is the most recommended text splitter.
RecursiveCharacterTextSplitter Core Parameters
| Parameter | Description | Recommended Value |
|---|---|---|
| chunk_size | Maximum number of characters per text chunk | 500-1000 |
| chunk_overlap | Number of overlapping characters between adjacent chunks | 50-200 |
| separators | Splitting priority: first by paragraph, then by sentence, finally by character | Default is fine |
Text Splitting Code
Best Practices for Text Splitting
- Adjust chunk_size by content type: Use 500-800 for technical documents, 800-1200 for long articles, 300-500 for FAQ-like content
- Do not omit chunk_overlap: Overlap prevents key information from being split at boundaries; recommended to set it to 10%-20% of chunk_size
- Preserve metadata: Keep metadata such as document source and page number during splitting for later traceability
- Chinese splitting: Add Chinese punctuation (。!?) to separators to ensure splitting at semantic boundaries
- Load first, then split: Load the full document first, then split uniformly to avoid repeated loading and splitting
Best Practices for Text Splitting
- Adjust chunk_size by content type: Use 500-800 for technical documents, 800-1200 for long articles, 300-500 for FAQ-like content
- Do not omit chunk_overlap: Overlap prevents key information from being split at boundaries; recommended to set it to 10%-20% of chunk_size
- Preserve metadata: Keep metadata such as document source and page number during splitting for later traceability
- Chinese splitting: Add Chinese punctuation (。!?) to separators to ensure splitting at semantic boundaries
- Load first, then split: Load the full document first, then split uniformly to avoid repeated loading and splitting
Vector Embeddings
Vector embeddings are the process of converting text into high-dimensional vectors (arrays of numbers). Texts with similar semantics have vectors that are closer in space. This is the core mathematical foundation for RAG retrieval.
Embedding Model Selection
| Model Name | Dimensions | Chinese Support | Model Size | Recommended Use Case |
|---|---|---|---|---|
| BAAI/bge-large-zh-v1.5 | 1024 | Excellent | 1.3GB | First choice for Chinese documents |
| BAAI/bge-small-zh-v1.5 | 512 | Excellent | 96MB | Lightweight Chinese |
| sentence-transformers/all-MiniLM-L6-v2 | 384 | Fair | 80MB | English-focused |
| shibing624/text2vec-base-chinese | 768 | Excellent | 400MB | Chinese semantic matching |
Vector Embedding Code
Embedding Model Selection Recommendations
For Chinese documents, the BGE series models are strongly recommended, as they significantly outperform general English models in Chinese semantic understanding. For local deployment, use HuggingFaceEmbeddings to load them without API costs. If you pursue ultimate performance and stability, you can use cloud-based embedding APIs.
Vector Database — ChromaDB
ChromaDB is a lightweight open-source vector database designed for LLM applications. No separate server is required; data is stored locally in files, making it perfect for small to medium-scale RAG applications.
Create Vector Database and Store
Load Existing Vector Database
Similarity Search
Other Vector Database Options
- FAISS: Meta's open-source vector indexing library, pure in-memory operations, extremely fast retrieval, suitable for millions of data points
- Milvus: Enterprise-grade distributed vector database, supports billion-scale vectors, suitable for large-scale production environments
- Weaviate: Open-source vector database with built-in vectorization and hybrid search, supports GraphQL API
- Pinecone: Commercial vector database service, no maintenance required, suitable for teams that don't want to manage infrastructure
- Qdrant: High-performance vector database written in Rust, supports filtering and group retrieval
Build Retrieval Chain
Connect vector retrieval and DeepSeek model to build a complete RAG QA chain. LangChain's RetrievalQA chain encapsulates the entire process from retrieval to generation.
Build RetrievalQA Chain
Test QA
chain_type Parameter Description
| Type | Description | Use Case |
|---|---|---|
| stuff | Put all retrieval results into the prompt at once | Few documents (k <= 4), most common |
| map_reduce | Summarize each document individually, then combine summaries | Many and long documents, need global understanding |
| refine | Iteratively refine the answer document by document | Need high-quality answers, don't mind latency |
| map_rerank | Score each document, select the highest-scoring answer | Need precise matching of specific documents |
Q&A with Source Citations
One of the core advantages of RAG is traceability. Every answer can be traced back to specific document sources, allowing users to verify the accuracy of information. Below shows how to present Q&A results with source citations in the UI.
Formatting Source Citations
Source Citation Format in Prompt
In the prompt, requiring the model to annotate source numbers when citing can effectively improve traceability:
Building a Web Q&A API
Use FastAPI to wrap the RAG system as a Web API:
Advanced RAG Techniques
Basic RAG can solve 80% of scenarios, but complex scenarios require more advanced retrieval strategies. The following techniques can help you significantly improve the answer quality of your RAG system.
Multi-Query Retrieval
Use the LLM to automatically rewrite the user's question into multiple queries from different angles, retrieve them separately, and merge the results to improve recall:
Parent Document Retriever
Use small text chunks for retrieval (to improve precision), but return large text chunks (to preserve context). This solves the problem of losing context with small chunks:
Contextual Compression
After retrieving documents, use a compressor to extract the most relevant parts to the question, removing redundant information:
Re-ranking
First use vector retrieval to get candidate documents, then use a re-ranking model to re-rank the candidate documents, greatly improving retrieval precision:
Summary of Advanced Techniques
| Technique | Problem Solved | Cost |
|---|---|---|
| Multi-Query Retrieval | Retrieval failure due to imprecise user question phrasing | Additional LLM calls |
| Parent Document Retrieval | Small chunks lose context | Storage doubles |
| Contextual Compression | The retrieval results contain a lot of irrelevant content | Additional LLM calls |
| Re-ranking | Vector retrieval is not precise enough | Additional model inference |
Complete Hands-on Project
Integrate all the previous steps into a complete document Q&A system: load PDF folders, create a vector database, interactive Q&A, and output with source citations.
Complete Code: deepseek_rag.py
Run the Project
Integration with Dify
If you don't want to write code, the Dify platform provides a visual RAG knowledge base feature. Apply the above RAG concepts to Dify to build an enterprise-level knowledge base Q&A system without coding.
RAG Mapping in Dify
| RAG Stage | Code Implementation | Dify Equivalent |
|---|---|---|
| Document Loading | PyPDFLoader / TextLoader | Knowledge Base → Upload Documents (supports PDF/Word/TXT/Web) |
| Text Splitting | RecursiveCharacterTextSplitter | Knowledge Base → Chunking Settings (custom chunk length and overlap) |
| Vector Embedding | HuggingFaceEmbeddings | Model Providers → Embedding Model Configuration |
| Vector Storage | ChromaDB | Dify Built-in Vector Database (Qdrant/Weaviate/ChromaDB) |
| Retrieval | vectorstore.similarity_search() | Knowledge Base → Recall Settings (TopK, Score Threshold) |
| Generation | ChatOpenAI + RetrievalQA | Application Orchestration → Add DeepSeek Model + Knowledge Base Node |
Dify Configuration Steps
- Deploy Dify: Use Docker Compose for one-click deployment (see DeepSeek Ecosystem Tools Dify section)
- Configure Model: Add DeepSeek in "Settings → Model Providers" (OpenAI-API-compatible method)
- Create Knowledge Base: Upload documents, set chunking parameters (chunk_size 500, chunk_overlap 100)
- Build Application: Create a "Chat Application" or "Agent", add knowledge base node in orchestration canvas
- Publish and Use: One-click publish as Web App or API, supports embedding into existing systems
Advantages of Dify
- Visual operation, no coding required
- Built-in vector database, automatic index management
- Supports hybrid retrieval (vector retrieval + keyword retrieval)
- Built-in citation tracing, automatically annotates answer sources
- Conversation logs and analytics, continuously optimize Q&A performance
- One-click publish as API, easy integration into business systems
For more Dify tips and DeepSeek integration solutions, see DeepSeek Ecosystem Tools and DeepSeek Deployment Tutorial.
DeepSeek RAG Knowledge Base FAQ
DeepSeek Related Tutorials
In-depth learning on using, deploying, and ecosystem tools for DeepSeek models.
How to Use DeepSeek Models
Four usage methods, zero-basics beginner tutorial.
DeepSeek Deployment Tutorial
Deployment solutions with Ollama, Docker, vLLM, K8s.
DeepSeek Ecosystem Tools
WebUI, IDE plugins, Agent frameworks, RAG platforms.
DeepSeek Model Architecture
Technical architecture, Benchmark, selection comparison.
DeepSeek Open Source Models
Complete catalog of 6 series, 20+ models.
DeepSeek Model Download
Download guides for Ollama, Hugging Face, GitHub.