Integrating an External Knowledge Base with Dify: A Practical Guide to RAG Retrieval
This article explains how to integrate a separately deployed retrieval service with Dify by calling an external knowledge base API and injecting the retrieved chunks into the prompt. It covers the full request flow, retrieval service preparation, port and authentication planning, embedding model and parsing choices, application-side tuning of top-N and similarity thresholds, and a pre-launch checklist for stable RAG applications.
1. Why Run Retrieval as a Separate Service
When teams build Retrieval-Augmented Generation (RAG) applications, they often assemble the agent on an application orchestration platform first and only later decide where the knowledge base should live. As the document volume grows, pressure on the retrieval side appears quickly: more document formats to handle, chunking strategies that need repeated adjustment, embedding and recall quality that must be evaluated on their own, and parsing failures that have to be re-run. Piling all of these responsibilities inside the orchestration platform couples application configuration with data engineering, so any change to the parsing strategy can ripple up into the application layer.
A cleaner approach is to separate the capabilities into layers. The orchestration layer handles the conversation flow, prompts, and tool calls. The retrieval service layer handles document ingestion, parsing and chunking, embedding, recall, and reranking. The model layer handles inference. The layers communicate through standard interfaces, and the retrieval service appears to the upper layer as an external knowledge base that can be called. Retrieval can then scale, be evaluated, and have its implementation replaced independently, while changes to the application are limited to one endpoint and a set of parameters.
This article focuses on integration in that layered model: the application platform calls an independently deployed retrieval service through an external interface, injects the recalled results into the prompt, and lets the platform-side model produce the final answer.
2. The Overall Flow and Data Path
A complete request follows this path:
- The user asks a question on the application side.
- The application forwards the question to the external retrieval service, along with the knowledge base identifier, the number of results to return, and the similarity threshold.
- The retrieval service performs vector recall in the specified knowledge base, optionally combining keyword recall and reranking.
- The retrieval service returns several text chunks with their similarity scores.
- The application assembles the chunks into a prompt template and passes it to the inference model.
- The answer is returned to the user together with the cited chunks.
Understanding this flow helps with troubleshooting. An irrelevant answer may mean recall found nothing useful. Correct recall with an off-target answer usually points to the prompt or model parameters. An interface error should be checked first at the service port and authentication level.
The calling logic can be sketched like this:
def ask(question, dataset_ids, top_n=5, threshold=0.2):chunks = retrieval_client.retrieve(question=question,dataset_ids=dataset_ids,page_size=top_n,similarity_threshold=threshold,)context = "\n".join(f"[{i+1}] {c.text}" for i, c in enumerate(chunks))prompt = TEMPLATE.format(context=context, question=question)return llm.generate(prompt)
3. Preparing the Retrieval Service
A standalone retrieval service usually relies on several components working together: a full-text and vector search engine, a relational database, object storage, a cache, and the service itself. What breaks most often during deployment is not the service process but connectivity between components and resource quotas. Confirm that every component is healthy before starting the main service.
Plan the exposed ports in advance. This kind of service typically exposes both a web access port and an API port, and only the API port is needed for integration with the application. Three points deserve attention:
- Port exposure scope. Open the API port only to the internal network or a gateway, and never expose it directly to the public internet.
- Authentication and key management. Keep calling credentials in environment variables or a secret manager on the application side, not in code or configuration screenshots.
- Timeouts and retries. Retrieval is a synchronous call, so configure connection timeouts, read timeouts, and a limited number of backoff retries to keep the upper-layer conversation from hanging.
For containerized deployments, this command confirms whether the port mapping matches expectations:
docker ps --format "table {{.Names}}\t{{.Ports}}"
4. Configuring Models and the Knowledge Base
The retrieval service needs two kinds of models: an embedding model that turns text into vectors, and an inference model that generates output. Once the embedding model is chosen, the vectors stored in the knowledge base are bound to it. Switching models midway invalidates the existing vectors and forces re-embedding, so language coverage, vector dimensions, and call quotas should be confirmed during selection.
The core decision when creating a knowledge base is the parsing method. For documents with clean layouts, general parsing is enough. For table-heavy documents, layered clauses, or scanned files, a more structured parsing strategy is required. The parsing method determines chunk quality, and chunk quality sets the ceiling on recall: no amount of retrieval strength can recover semantics that were chopped up or flattened out of order.
A few practices are recommended for document ingestion:
- Upload in batches and verify parsing results batch by batch, so failures are easy to locate instead of buried in a large one-shot submission.
- Keep the mapping between original files and parsing results for traceability.
- Run a small comparison on chunk length and overlap, using the same set of questions to compare recall hits.
- Tag knowledge bases with version markers and record them when documents are updated, which makes rollback straightforward.
5. Connecting and Tuning on the Application Side
On the application platform, an external knowledge base is usually connected as an “external retrieval service”: fill in the service address, calling credentials, and knowledge base identifier, then set the number of results and the similarity threshold. The parameters mean the following:
- The number of results determines how many chunks are injected into the context. Too many crowd the context window and introduce noise.
- The similarity threshold filters out weakly related chunks. Set it too high and recall comes back empty; set it too low and noise enters the prompt.
- The prompt template should state clearly that the model must answer only from the given material and must say when the material is insufficient, which reduces free improvisation.
Differences in output usually come from three sources: the inference models on the two sides differ, so summarization and generalization ability naturally differ; generation parameters such as temperature differ, and a higher temperature makes answers more divergent; and the prompt and context organization differ. When troubleshooting, fix the same set of questions and the same knowledge base, and change only one variable at a time rather than adjusting several at once.
6. Common Issues and an Acceptance Checklist
Before going live, self-check against this list: components are healthy and port mappings are correct; the embedding model matches the knowledge base; parsing results pass spot checks; the API is reachable on the internal network and authentication is enforced; timeout and retry policies are configured; the number of results and the threshold have been validated by comparison; the prompt includes the constraint to answer from the material; and call logs and retrieval scores are observable for later optimization.
Separating retrieval out looks like one extra deployment in the short term, but over time it buys a data foundation that can be evaluated, replaced, and scaled. When parsing strategy, recall parameters, and model choice can each be measured and iterated on their own, the stability of the upper-layer agent application is what benefits.
