Enhancing RAG with an External Knowledge Base: A Practical Guide for Dify
This guide explains why built-in knowledge base retrieval often falls short in production and how to address it by separating retrieval from the workflow platform. It covers the overall architecture, deployment considerations for an external retrieval service, knowledge base construction, retrieval parameters, integration into Dify, attribution analysis for output differences, and engineering best practices. The core takeaway is to choose the right parsing template, enable reranking, and build a regression evaluation set.
1. Why Built-in Knowledge Base Retrieval Often Falls Short
When teams build question-answering applications in practice, they frequently run into the same issue: the built-in knowledge base module of a workflow platform looks fine during a demo, but answer quality drops noticeably once real business documents are connected. Retrieval results that “look relevant but miss the point” are the most common complaint from developers.
This is not a flaw in a single component, but the combined effect of multiple factors along the retrieval chain:
- Overly simplistic chunking: Fixed-length splitting cuts through semantically complete passages, mixing multiple topics in one chunk and diluting its vector representation.
- Mismatch between the embedding model and business corpus: General-purpose embedding models struggle to distinguish specialized terms, abbreviations, and names.
- No reranking stage: Vector recall only guarantees “semantic similarity,” not that a chunk actually contains the answer, so Top-K results often include distractors.
- Missing query understanding and rewriting: There is a gap between how users ask questions colloquially and how documents are written.
- Rough context assembly: Simply concatenating matched fragments can exceed the model’s effective attention range and actually degrade answer quality.
A pragmatic approach is therefore to keep the workflow platform’s strengths in orchestration, session management, and application publishing, and split out the “retrieval” step, handing it to a more specialized retrieval service. This is the core logic of external knowledge base retrieval augmentation.
2. Overall Architecture
The pipeline can be abstracted into four layers:
- Document ingestion and parsing layer: Reads multiple document formats, reconstructs layout, and extracts tables and images.
- Chunking and vectorization layer: Splits by semantic structure, calls an embedding model to generate vectors, and writes them to vector storage.
- Retrieval and reranking layer: Hybrid retrieval (keyword + vector) recalls candidates, which are then precisely ordered by a reranking model.
- Orchestration and generation layer: The workflow platform calls the retrieval service over HTTP, and passes the returned fragments to a large language model to generate the final answer.
The key design principle is single responsibility and standardized interfaces. The retrieval service exposes only “retrieval” and “result return” capabilities, while the workflow platform is unaware of the underlying storage and model details. This way, replacing the vector store or embedding model later does not affect upper-layer applications.
3. Deployment Considerations for the External Retrieval Service
Taking a common open-source retrieval solution as an example, such systems are usually composed of microservices with fairly complex dependencies, typically including:
- A full-text search engine (handling keyword recall and inverted indexing)
- A relational database (storing metadata, task status, and configuration)
- Object storage (holding original files and intermediate parsing artifacts)
- A cache service (sessions and hot data)
- The main retrieval service (parsing, chunking, vectorization, and the retrieval API)
Three points need attention during deployment:
First, plan ports and network policies in advance. Such systems usually expose both a web console port and an API port, which serve completely different purposes. Make sure the API port is reachable within the cluster and configure least-privilege network policies to avoid exposing the management console directly to the public internet.
# Check the ports actually mapped by the container and confirm the API port is exposeddocker ps --format "table {{.Names}}\t{{.Ports}}"
Second, leave headroom in resource allocation. Parsing and vectorization are CPU-intensive tasks that can easily max out resources during batch uploads. It is recommended to deploy parsing tasks and online retrieval in separate containers so that offline jobs do not affect online response latency.
Third, if running on a container platform or a cloud-hosted cluster, prefer general-purpose capabilities to carry the workload: the container platform handles orchestration and elastic scaling, object storage holds original documents, and log and monitoring/alerting services provide observability. On Baidu AI Cloud, corresponding general-purpose components can support this kind of architecture; refer to the official documentation for specific specifications.
4. Building the Knowledge Base
4.1 Model Configuration
Two types of models must first be registered in the retrieval service:
- Embedding model: Determines the quality of the vector space and should match the business corpus in language and domain.
- Inference model: Used to generate answers or summarize results.
Configuration is similar to other tools: just fill in the service address, key, and model identifier. It is advisable to first evaluate the embedding model’s recall on a small labeled set before deciding whether to switch.
4.2 Creating Datasets and Parsing Methods
The core choice when creating a knowledge base is the parsing method (chunk template). Common types include general text, question-answer pairs, tables, papers, books, resumes, and legal clauses. Different templates handle layout and structure very differently:
- The general mode suits loosely structured documents.
- The Q&A mode suits FAQ-style corpora and can significantly improve answer hit rates.
- The table mode preserves row and column relationships, avoiding misaligned numeric information.
After selecting the embedding model and parsing template, upload documents and trigger parsing. Documents are truly vectorized and retrievable only after parsing completes. For batch uploads, process in batches and retry failures; files that fail to parse usually do not enter the index and need to be investigated separately.
4.3 Retrieval Parameters
Retrieval quality depends heavily on parameters. Focus on the following:
- Top-K: The number of recalled items; too large introduces noise, too small may miss the answer.
- Similarity threshold: Filters out low-relevance fragments.
- Keyword-to-vector weight ratio: Increase keyword weight in terminology-dense scenarios.
- Rerank model: If rerank capability is available, be sure to enable it, as it usually gives the most obvious precision improvement; otherwise, leave it empty for now.
- Multi-turn rewriting: Enabling query rewriting helps handle references and omissions.
5. Connecting an External Knowledge Base in the Workflow Platform
Mainstream workflow platforms offer an “external knowledge base” capability that essentially connects to a third-party retrieval service over HTTP. The configuration steps are usually:
- Create an external knowledge base entry on the platform side, filling in the retrieval service’s API address and authentication information.
- Declare request and response field mappings to convert the platform’s standard retrieval request into parameters the retrieval service can recognize.
- Select the external knowledge base in the application or workflow node.
- Debug retrieval hits, then gradually tune the generation-side prompt and temperature parameters.
An illustrative request structure is as follows (field names are subject to the actual API documentation):
{"query": "summary of a person's experience","dataset_ids": ["kb_xxx"],"top_k": 6,"similarity_threshold": 0.35,"rerank": true}
The response usually contains fragment text, source document, page or paragraph position, and similarity score. Be sure to retain source information, as this is the basis for citation tracing and quality auditing later.
6. Attributing Output Differences
In practice, you may find that for the same document, calling the retrieval service directly versus summarizing through the workflow platform produces differences in output style and level of detail. There are usually three reasons:
- Different generation models: Models differ markedly in their ability to use long context.
- Different temperature and sampling parameters: A higher temperature makes summaries more divergent.
- Different prompt templates: The platform’s built-in template may carry extra constraints or output format requirements.
This is normal and not worth overthinking. When tuning, fix variables: first fix the generation model and temperature, adjust only retrieval parameters, and observe changes in hit rate; then fix retrieval and adjust the prompt.
7. Engineering Recommendations and Common Pitfalls
- Evaluation set first: Prepare 30–50 real questions with standard answer fragments as a regression baseline.
- Visualize chunking: Spot-check chunk content to confirm semantics are not broken apart.
- Permissions and isolation: In multi-tenant scenarios, isolate access by dataset, and do not hardcode authentication information in configuration files.
- Incremental updates: After a document changes, trigger re-parsing and clean up old-version fragments to avoid answers citing outdated content.
- Cost control: Both reranking and large model calls incur overhead; cache high-frequency Q&A and lower Top-K to control costs.
- Observability: Log each retrieval’s query, hit fragments, and scores to help determine whether “inaccurate answers” stem from retrieval or generation.
8. Summary
Built-in knowledge bases are not unusable, but in scenarios with high precision requirements, externalizing retrieval so that a specialized retrieval service handles parsing and recall, while the workflow platform handles orchestration and generation, is a cost-controlled and evolvable engineering solution. To see results in practice, focus on three things: choose the right parsing template, enable reranking, and build a regression evaluation set. When implementing on the cloud, you can rely on general-purpose capabilities such as container platforms, object storage, and logging and monitoring for deployment and operations, and Baidu AI Cloud’s related product documentation can serve as a reference for specifications and quotas.
