RAG with External Knowledge Base Retrieval in Dify: A Practical Guide
This guide explains how to integrate external knowledge base retrieval into Dify using Retrieval-Augmented Generation (RAG). It covers building the knowledge base—choosing an embedding model, selecting a parsing strategy, and running an observable, idempotent ingestion pipeline—along with tuning retrieval parameters such as similarity thresholds, result count, reranking, and metadata filtering. It then walks through orchestration on the conversation platform side (assistant settings, prompt engine, and model settings) and lists common issues with practical engineering tips for moving a RAG pipeline from demo to stable production use.
1. Why Add External Knowledge Base Retrieval to a Chat Platform
In most enterprise Q&A scenarios, relying only on a large language model’s parametric knowledge is not enough. A model’s knowledge is bounded by its training cutoff and cannot cover private data such as internal documents, product manuals, and support ticket records. The core idea of Retrieval-Augmented Generation (RAG) is to first retrieve relevant passages from an external knowledge source before inference, then inject those passages into the prompt as context, so the model can “answer based on the source material.”
Decoupling knowledge base retrieval from the chat platform and delegating it to a standalone retrieval service is a common and clean engineering separation of concerns. The chat platform handles session orchestration, prompt assembly, and model invocation; the retrieval service handles document parsing, chunking, vectorization, index building, and recall ranking. The two interact through a standard interface: the platform simply forwards the user’s question to the retrieval service and gets back the relevant passages. The direct benefit of this layering is that updating and scaling the knowledge base does not require changes to the chat flow, and retrieval strategy changes can also be validated independently through gradual rollout.
2. Building the Knowledge Base: From Documents to Searchable Vectors
2.1 Choosing an Embedding Model
The embedding model determines how text is mapped into the vector space and directly affects recall quality. Three points usually matter when selecting one: first, vector dimensionality—higher dimensions mean stronger expressive power but also greater index storage and retrieval overhead; second, language fit—Chinese corpora need a model that performs stably on Chinese semantic matching; third, resource fit with the inference pipeline—the embedding model must be deployed or called separately, so you need to evaluate whether throughput and latency meet the dual demands of batch ingestion and online queries.
A practical point: once the embedding model is chosen, all vectors in the knowledge base must be generated by that same model. Switching models means rebuilding the entire index, so it is better to run a comparative evaluation on a small sample set early in the project rather than migrating repeatedly after launch.
2.2 Choosing a Parsing Method
Document parsing is the process of turning unstructured files into structured text, and it is also the most underestimated step in the whole pipeline. Layouts differ greatly across document types, so parsing strategies are usually divided by document form:
- General parsing: suited to plain-text, single-column documents with clean layouts; splits by paragraphs and punctuation, simple to implement and high in throughput;
- Layout-aware parsing: recognizes heading levels, tables, and image caption regions, preserving section structure; suitable for manual-type documents;
- Table and structured parsing: restores tables to row-and-column semantics, avoiding separation of headers from data after chunking;
- Q&A parsing: for knowledge organized as question-answer pairs, keeps each “question-answer” unit from being split.
The selection principle is to first look at the actual form of the corpus, then at the retrieval granularity you need. If tables and multi-level headings make up a large share of the documents, prefer a parsing method that preserves layout structure; if the corpus is mostly short text, general parsing is often enough, and overly complex parsing can introduce noise instead.
An illustrative configuration description can be understood like this (not a specific interface, only expressing parameter semantics):
knowledge_base:embedding_model: <your-embedding-model>chunking:strategy: general # general | layout_aware | table | qachunk_size: 512 # target length per chunk, counted in tokensoverlap: 50 # overlap between adjacent chunks to ease semantic truncationindex:metric: cosine # similarity metric
2.3 Document Ingestion and Vectorization
The ingestion flow usually has four steps: upload the original file, parse it into text chunks, call the embedding model to generate vectors, and write to the index. Engineering considerations include:
- Batch and single-file parallel support. Initial builds often involve hundreds or thousands of documents, and batch parsing significantly shortens waiting time; for daily incremental updates, single-file parsing is more flexible.
- Observable parsing status. Maintain a “pending-parsing—parsing—completed—failed” status for each file, and keep the error reason for failed tasks so they can be rerun.
- Idempotency and deduplication. Use a file fingerprint as the unique identifier so that re-uploading does not produce duplicate indexes, avoiding recall results being crowded out by the same content.
- Incremental updates. When a document changes, rebuild only the affected chunks instead of the whole base; this is especially critical for scenarios with frequently changing knowledge.
3. Key Retrieval Parameters and Tuning
Recall quality is not determined by the embedding model alone; retrieval parameters matter just as much.
- Similarity threshold: too low introduces irrelevant passages, too high may return nothing. It is recommended to first collect similarity distributions from a batch of real questions, then set the threshold range.
- Number of results and context budget: the number of returned passages should match the model’s context window. Too many passages dilute key information and also increase inference cost.
- Reranking: introducing a cross-encoder to fine-rank candidate passages after initial recall usually improves the relevance of top results noticeably. If a rerank model is not yet available, you can start with vector recall only and treat reranking as a later optimization; the pipeline is still usable.
- Metadata filtering: tag documents with metadata such as source, effective time, and permission labels, then filter before ranking at retrieval time; this solves the problem of “right content but citing an outdated version.”
For tuning, use regression with a fixed evaluation set: prepare dozens to a hundred questions with standard answers, change only one variable at a time, and record hit rate and answer accuracy, avoiding repeated adjustments based on gut feeling.
4. Orchestration on the Chat Platform Side
Once the retrieval service is ready, configuration on the chat platform usually revolves around three panels.
Assistant settings. Fill in the assistant name and bind the knowledge base to use. One assistant can bind one or more knowledge bases; for multi-base scenarios, it is recommended to split by business domain to avoid cross-domain content interfering with each other.
Prompt engine. This decides “how to use the recall results.” A robust prompt structure has four parts: role definition, answer constraints, a reference material section, and output format requirements. The constraint part should make clear that “when the material is insufficient, state that you cannot answer”; this is key to suppressing model fabrication.
You are an enterprise knowledge assistant.Answer only based on the reference material below; when the material does not cover it, clearly state that you cannot answer, and do not speculate.Reference material:{{retrieved_chunks}}User question: {{question}}
Model settings. Choose a large language model for inference and set parameters such as temperature and maximum output length. Q&A scenarios usually use a lower temperature for greater stability; raise it appropriately when generating long-form content.
After configuring the three panels, you can run integration testing. During integration testing, it is recommended to cover three types of questions: those directly answerable from the knowledge base, those requiring synthesis across passages, and those not covered by the knowledge base at all, to verify that the system behaves as expected in all three cases.
5. Common Issues and Engineering Notes
- Empty recall: mostly caused by a threshold set too high or parsing failures that leave text chunks empty; check parsing status first, then adjust the threshold.
- Vague answers: usually caused by chunks that are too large or a prompt lacking constraints; reduce chunk granularity and strengthen the “answer based on the material” instruction.
- Garbled table data: indicates the parsing method did not preserve table structure; switch to a layout- or table-aware parsing strategy.
- Permission overreach: always do metadata filtering at the retrieval layer; do not expect the model to judge the visible scope on its own.
- Out-of-control cost: limit the number of returned passages, cache recall results for high-frequency questions, and summarize long documents before ingestion.
6. Summary
Making knowledge base retrieval an independent service layer and letting the chat platform handle orchestration is a practical path that balances maintainability and the upper bound of quality when building an enterprise Q&A system. In practice, focus on four levers: choose the right embedding model and parsing strategy, make the ingestion flow observable and idempotent, drive parameter tuning with a fixed evaluation set, and make the “no source, no answer” boundary explicit in the prompt. Following this approach, a RAG pipeline can move from a demo to stable operation.
