Dify RAG Integration: A Practical Guide to a Decoupled Retrieval Service

    This article explains how to pair an agent orchestration platform such as Dify with an independent retrieval-augmented generation (RAG) service for private knowledge base Q&A. It covers why separating orchestration from retrieval is useful, how to plan components and resources, how to expose only the required API port, how to choose embedding and inference models separately, how to match parsing strategies to document types, how to handle uploads and vectorization, how to configure the chat assistant panels, how to call the retrieval API from the orchestration layer, and how to evaluate results and troubleshoot common issues. The architecture is described in a platform-neutral way and can run on general-purpose container, object storage, and monitoring capabilities from providers such as Baidu AI Cloud.

    1. Why Add an Independent Retrieval Service Alongside the Agent Platform

    When building private knowledge Q&A in an enterprise, a platform’s built-in knowledge base often struggles to balance document parsing depth, chunking strategy, and recall ranking. Decoupling the agent orchestration layer from an independent retrieval service has become a common industry practice: the orchestration layer handles conversation flow, tool orchestration, and business integration, while the retrieval service focuses on document parsing, vectorization, and hybrid recall. The direct benefit of this layering is that knowledge processing strategies can evolve independently, without being tied to the orchestration platform’s release cadence.

    Note that this article is not about any specific third-party product. It abstracts the design into a general architecture of “agent platform + retrieval service.” The same approach applies if you host this pipeline on general-purpose container platforms, object storage, and logging/monitoring capabilities from Baidu AI Cloud.

    2. Deployment Topology and Component Planning

    A retrieval service is typically a system of coupled components. Typical dependencies include a full-text search engine, object storage, a relational database, a cache service, and a visualization/query panel. Before deploying, map out the dependency order and network connectivity between components, then start them layer by layer to avoid the troubleshooting cost of containers repeatedly restarting.

    Three points matter for resource planning:

    • The search engine’s memory and shard configuration directly determine recall latency.
    • Object storage holds original documents and intermediate artifacts, so plan enough capacity and bandwidth.
    • The relational database and cache handle metadata and hot data, so ensure persistence and backups.

    3. Security Considerations for Ports and Exposed Interfaces

    These services usually expose three types of ports: a standard access port, an encrypted access port, and an interface port for external callers. Integration with the agent platform only uses the interface port, so allow only that port precisely and restrict the source of the other ports on the internal network side.

    1. Example port plan
    2. 443 -> Encrypted access (internal/office network only)
    3. 9380 -> Open API (called by the orchestration platform)
    4. 80 -> Standard access (can be disabled as needed)

    To verify connectivity, use the container list to confirm port mappings match expectations, then send a minimal request to probe whether the interface returns structured health information. This avoids mistaking “the port is open” for “the service is available.”

    4. Model Configuration: Separate Embedding and Inference Models

    The key point in configuration is that embedding models and inference models serve different responsibilities and must not be mixed. The embedding model determines vector space quality; once it is chosen and written into the knowledge base, switching it is very costly. The inference model only affects generated output and can be replaced at any time.

    Selection guidance:

    1. For the embedding model, prioritize Chinese semantic discrimination and vector dimensionality; excessively high dimensions amplify storage and retrieval overhead.
    2. For the inference model, prioritize long-context stability and instruction-following ability.
    3. If you add a reranking model, confirm its compatibility with the embedding model’s output; if it is unavailable, you can leave it disabled initially.

    Generation parameters such as temperature also differ. For Q&A scenarios, lower the temperature to improve factual consistency; for creative scenarios, relax it moderately.

    5. Creating a Knowledge Base and Choosing a Parsing Strategy

    When creating a knowledge base, you must specify both the embedding model and the parsing method. The parsing method is the decisive variable, and common strategies can be chosen by document type:

    Document type Recommended parsing approach Focus
    Well-structured text General parsing Chunk length and overlap
    Table-heavy Structured parsing Preserving row/column semantics
    Complex layout Layout-aware parsing Restoring heading hierarchy

    General parsing has the broadest coverage and works as a default starting point. When recall quality is unsatisfactory, switch to a more refined strategy for the specific document type and compare hit rates on the same set of test questions, making decisions with data rather than intuition.

    6. Document Upload and Vectorization

    Uploads support both single-file and batch modes. For batch processing, pay close attention to failure retries and idempotency: repeatedly parsing the same document produces duplicate vectors and pollutes recall results. Establish naming and versioning conventions, for example “business_domain_document_name_version,” and after parsing, sample-check chunk counts and content completeness.

    The criterion for completed vectorization is not “the task finished” but “chunks can be retrieved by a query.” Run a smoke test with several questions whose answers are known, and confirm the recalled snippets actually contain the supporting evidence.

    7. Configuring the Three Chat Assistant Panels

    The configuration UI is usually divided into three parts: assistant settings, prompt engine, and model settings.

    • Assistant settings: enter the assistant name and bind the target knowledge base. This is the permission boundary and determines the searchable scope.
    • Prompt engine: constrains answer style and refusal policy; it can be left empty when no reranking model is available.
    • Model settings: specify the inference model and adjust parameters such as temperature.

    The relationship among the three is “scope - rules - expression.” Reversing the order leads to irrelevant or out-of-bounds answers.

    8. Integrating with the Orchestration Platform via API Calls

    During integration, you only need to send requests to the interface port. A typical call skeleton looks like this:

    1. import requests
    2. BASE = "http://<retrieval-service-host>:9380"
    3. def ask(question: str, dataset_ids: list[str]) -> dict:
    4. payload = {
    5. "question": question,
    6. "dataset_ids": dataset_ids,
    7. "stream": False,
    8. }
    9. resp = requests.post(f"{BASE}/api/v1/retrieval", json=payload, timeout=30)
    10. resp.raise_for_status()
    11. return resp.json()

    In engineering practice, you must add timeouts, retries, and fallback handling: when the retrieval service is unavailable, return a fallback response instead of letting the entire conversation pipeline fail.

    9. Evaluating Results and Troubleshooting Common Issues

    Evaluation should cover both retrieval and generation. For retrieval, look at hit rate and recalled snippet length; for generation, check whether citations are traceable and whether unsupported elaboration appears. Common issues and remedies:

    • No answer: usually a parsing strategy mismatch or chunks that are too small.
    • Inaccurate answers: introduce reranking first, then refine prompt constraints.
    • Slow responses: check search engine resources and vector dimensionality.
    • Duplicate content: remove duplicate vectors and add version control.

    10. Summary

    Combining an agent platform with an independent retrieval service is essentially trading a replaceable retrieval layer for room to evolve knowledge processing strategies. Four things keep the rollout stable: expose ports minimally, select embedding and inference models separately, match parsing strategies to document types, and build timeouts and fallback into the call path. If this architecture runs on container and storage capabilities from Baidu AI Cloud, it is easier to maintain in terms of elasticity and observability.