RAG with Dify: Connecting an External Knowledge Base Retrieval Service
This article explains how to decouple retrieval from an orchestration platform and connect a self-hosted retrieval service to Dify as an external knowledge base for end-to-end RAG question answering. It covers the layered architecture, deployment considerations for the retrieval service, the request and response structures used for integration, prompt templates with citation markers, retrieval quality tuning methods, and a troubleshooting checklist.
1. Why Run Retrieval as a Separate Service
When teams start building Retrieval-Augmented Generation (RAG) applications, they often use the built-in knowledge base of an agent orchestration platform to validate an idea quickly. As document volume grows, parsing requirements become more complex, and concurrency increases, the built-in retrieval module tends to hit limits in parsing depth, control over chunking strategies, recall and ranking capability, and operational observability.
A more sustainable approach is to separate retrieval from orchestration into two layers that evolve independently:
- Orchestration layer: handles the conversation flow, prompt assembly, tool calls, business system integration, and front-end experience.
- Retrieval layer: handles document ingestion, deep parsing, chunking, vectorization and hybrid recall, reranking, and citation traceability.
This separation brings three direct benefits: the retrieval layer can scale and be upgraded independently; multiple business lines can share the same knowledge assets; and retrieval quality can be tuned continuously without touching the conversation flow. This article focuses on how the orchestration layer can connect to a self-hosted retrieval service through a generic interface to deliver knowledge-augmented question answering end to end.
2. Overall Architecture
A typical decoupled architecture includes the following components:
- Document ingestion and parsing service: accepts uploads in multiple formats and performs preprocessing such as layout analysis, table extraction, and OCR for images and scanned documents.
- Chunking and index building: splits text along semantic boundaries and builds both vector and keyword indexes.
- Hybrid retrieval and reranking: runs vector recall and keyword recall in parallel, merges the results, and reranks them.
- External knowledge base adapter: registered on the orchestration platform as an “external knowledge base”, translating platform requests into calls to the retrieval service.
- Observability and evaluation: tracks metrics such as recall hit rate, citation accuracy, and time to first token, closing the iteration loop.
The orchestration platform here acts only as the request initiator and answer generator. It does not need to know the underlying index details, and this contract-based design is what makes the system replaceable and extensible later.
3. Deploying the Retrieval Service
A self-hosted retrieval service usually relies on container orchestration and a few supporting components. Key deployment concerns include:
- Resource planning: parsing and vectorization are compute-intensive, so they should be deployed separately from the online retrieval path to keep bulk ingestion from affecting online latency.
- Storage tiers: raw documents in object storage, metadata in a relational database, and vector plus inverted indexes in a dedicated search engine.
- Service exposure: expose only the necessary retrieval and document management APIs, reachable over the internal network or a gateway, with authentication enabled.
- Configuration management: parsing parameters, chunking granularity, and recall counts should be externalized as configuration so they can be tuned per knowledge base.
- Health checks and elasticity: set backlog alerts for the parsing task queue, and timeouts plus fallback strategies for the retrieval APIs.
Because dependencies and initialization steps differ across distributions and versions, follow the official documentation and the open-source repository instructions, and complete a full validation in a staging environment before moving to production.
4. Connecting on the Orchestration Platform Side
The key step is registering the external retrieval service as an “external knowledge base” and filling in the service address, authentication details, and retrieval parameters correctly. A sample request structure looks like this (field names are expressed in generic terms; refer to your platform’s documentation for the actual schema):
{"knowledge_id": "kb_enterprise_docs","query": "报销流程需要哪些审批节点","top_k": 6,"score_threshold": 0.35,"filters": { "department": "finance" }}
The retrieval service should return results in a consistent structure so the orchestration layer can assemble context directly:
{"results": [{"content": "……命中的原文片段……","score": 0.82,"doc_name": "财务制度v3.pdf","doc_id": "d-1024","position": { "page": 12, "block": 3 }}]}
In the prompt template, inject the chunk number together with its source, and instruct the model to answer only from the provided material:
请仅依据以下资料回答问题,并在句末标注引用编号。资料:[1] {chunk_1}[2] {chunk_2}无法从资料中得出时,请明确说明"资料中未提及"。问题:{question}
5. Tuning Retrieval Quality
- Chunking strategy: prefer splitting by heading hierarchy and semantic paragraphs, define separate rules for tables and code blocks, and keep the section path as metadata on each chunk.
- Hybrid recall: vector recall handles semantically similar content well, while keyword recall handles proper nouns and identifiers; combining them significantly reduces missed recall.
- Reranking: add a cross-encoder reranking model to fine-rank the candidate set, which is usually more cost-effective than simply increasing top_k.
- Threshold governance: a score threshold that is too high produces “no answer”, while one that is too low introduces noise, so calibrate it per knowledge base.
- Metadata filtering: pre-filter on fields such as department, time, and version to improve both accuracy and response time.
- Evaluation loop: build an evaluation set containing questions, reference answers, and expected citation sources, and run a regression comparison after every change.
6. Common Issues and Troubleshooting Checklist
- Always returning empty results: check whether authentication passed, whether the knowledge base identifier is correct, and whether the score threshold is too high.
- Answers inconsistent with the material: usually caused by disordered context assembly or weak prompt constraints; keep the order fixed with material first and question last.
- Sudden latency spikes: typically bulk ingestion saturating resources, so isolate offline indexing from online retrieval.
- Citations that cannot be located: require the retrieval service to return document identifiers and position information, not just text.
- Permission leaks: enforce filtering in the retrieval layer rather than relying on the generation layer to behave.
7. Conclusion
Pushing retrieval down into an independent service and consuming it from the orchestration platform through a standard interface is an effective way to get enterprise-grade retrieval quality while keeping the architecture simple. The recommended pace is to get the pipeline working first and tune gradually: complete a minimal viable integration, then improve chunking, hybrid recall, reranking, and evaluation in turn. If the whole system runs in a cloud environment such as Baidu AI Cloud, deployment and operations can build on common capabilities like container platforms, object storage, log services, and monitoring alerts, leaving the team to focus on knowledge quality and business outcomes.
