From Model Inference to Knowledge QA: RAG Deployment Practices
This article explores the end-to-end deployment practices of Retrieval-Augmented Generation (RAG) systems. It covers the core objectives of building verifiable knowledge systems, the overall architecture of knowledge ingestion and online QA, pre-deployment preparations, model inference service setup, and the intricacies of document parsing, retrieval, and answer generation. It also delves into security, evaluation, and troubleshooting strategies to ensure reliable and accurate knowledge-driven responses.
1. Define the Goal: Building Answers on Verifiable Knowledge
Retrieval-Augmented Generation (RAG) is a class of technical solutions that combines external knowledge retrieval with large language model (LLM) generation. Rather than simply stuffing all documents into the model, RAG first finds relevant materials upon receiving a question, and then instructs the model to formulate an answer based on those materials.
This approach is well-suited for scenarios such as corporate policy inquiries, technical documentation Q&A, and operational manual retrieval. Compared to relying solely on the model’s pre-trained knowledge, RAG improves information timeliness through knowledge base updates and facilitates providing source citations for answers. However, it cannot automatically guarantee answer correctness: documents may be parsed incorrectly, retrieval might miss critical evidence, and the model may misread the evidence or extrapolate beyond it.
Therefore, when building the system, focus should be placed on three objectives simultaneously:
- Retrievability: The valid knowledge corresponding to the question can enter the candidate results.
- Comprehensibility: The document structure and context are reasonably preserved so the model can understand the retrieved content.
- Accuracy: The answer does not deviate from the evidence, and citations support the relevant conclusions.
The originally disparate model deployment, reranking model configuration, and knowledge base service initialization should be integrated into a complete pipeline centered around these three goals.
2. Overall Architecture: Separating Knowledge Ingestion and Online QA
A generic knowledge Q&A system can be divided into two interconnected but distinct workflows.
2.1 Knowledge Ingestion Pipeline
Original Documents→ Content Parsing and Cleaning→ Structured Chunking→ Generate Vector Representations→ Save Text, Metadata, and Retrieval Indexes
The core task of the ingestion pipeline is to transform raw materials into searchable and citable knowledge units. In addition to text content, metadata such as document identifiers, sections, page numbers, update times, and permission tags should be preserved.
This information is not just for display. It directly affects subsequent version filtering, permission control, citation location, and troubleshooting.
2.2 Online Q&A Pipeline
User Question and Identity Information→ Permission Constraints and Retrieval Conditions→ Candidate Content Recall→ Relevance Reranking→ Organize Evidence Context→ LLM Generation→ Return Answer and Citations
The online pipeline typically requires three types of model capabilities:
- Embedding Model: Converts questions and text chunks into vector representations to support semantic retrieval.
- Reranking Model: Performs finer-grained relevance assessment between the question and candidate chunks.
- Generation Model: Reads the filtered evidence and outputs a natural language answer that meets requirements.
These three capabilities solve different problems and are not interchangeable. A larger generation model does not mean the system can recall missing materials; a stronger reranking model cannot fix table relationships already lost during ingestion.
3. Pre-deployment Preparation: Constraints First, Resources Second
3.1 Define Data and Service Requirements
Before deployment, clarify the following questions:
- Are documents mostly plain text, or do they contain many scanned pages, tables, and charts?
- Does the knowledge base need isolation by department, role, or user?
- Are data updates occasional bulk imports or continuous incremental syncs?
- Is the system for a few internal users, or must it handle concentrated traffic?
- Must answers include sources? Is the model allowed to refuse to answer when evidence is insufficient?
These requirements will affect parsing strategies, index organization, model resources, and service architecture. For sensitive materials, confirm the allowed data processing scope, storage location, and access methods before discussing model selection.
3.2 Evaluate Compute and Storage Resources
Model inference must consider memory, VRAM, compute power, and concurrent load. The ability to load model weights does not mean the service can stably support the business: runtime also involves context caching, intermediate calculation results, and concurrent request consumption.
Document parsing can also consume significant resources. Scanned materials, complex tables, or bulk import tasks can easily compete with online Q&A for compute and storage throughput.
A safer approach is to validate the pipeline with a small sample first, then gradually increase the document volume, input length, and concurrency. Do not make fixed throughput commitments without testing.
3.3 Plan Persistent Directories
The temporary file system in the runtime environment should not bear the responsibility of long-term preservation for critical data. At minimum, define the storage locations for:
- Model files and caches;
- Original documents and parsing results;
- Vector indexes and other retrieval data;
- Business configurations, task states, and necessary logs.
Persistence requires not only verifying that “data can be written,” but also that it can be read after a service restart, and that a consistent Q&A environment can be re-established after backup restoration.
4. Model Inference Service Deployment: From Startup to Stability
4.1 Key Configurations for Containerized Deployment
When running model services using containers, you typically need to configure the runtime version, service ports, persistent mounts, compute resources, and startup entry points.
These configurations address different issues:
- Pinning the runtime version reduces unpredictable changes caused by upgrades;
- Mapping service ports enables callers to access the service;
- Mounting persistent directories prevents re-downloading models or losing data after rebuilds;
- Allocating compute resources limits resource contention among different services;
- Specifying the listening address determines on which network interfaces the service accepts connections.
It is crucial to distinguish between listening scope and access security. Allowing a service to listen on all network interfaces only means it can receive connections from those networks; it does not imply that authentication or access control is in place.
Production environments should not expose model management endpoints directly for debugging convenience. Protect them with network isolation, access authentication, encrypted transmission, and request rate limiting.
4.2 Step-by-Step Verification by Dependencies
Verify services in the following order:
- Confirm the process can start and resource allocation is normal;
- Load the embedding model and verify text vector output;
- Load the reranking model and verify candidate sorting behavior;
- Load the generation model and verify basic text generation;
- Test calls one by one from the knowledge Q&A application side;
- Finally, verify the complete Q&A pipeline.
The ability to open the management dashboard only proves that some services are accessible; it does not prove that the models are loaded or that business requests can execute successfully.
4.3 Check Compatibility for Three Model Types Separately
For embedding models, focus on language coverage, input length limits, vector dimensions, and task adaptation. After changing an embedding model, even if the output dimensions are the same, the old and new vector spaces may not be compatible; you usually need to regenerate document vectors and rebuild corresponding indexes.
For reranking models, check the input format, length truncation strategy, and how relevance scores are used. The returned score should not be treated as the “probability of a correct answer” without validation.
For generation models, check context length, output format constraints, and evidence adherence. The model should clearly state limitations when materials are insufficient, rather than supplementing with seemingly plausible but unsourced content.
5. Knowledge Ingestion: Preserve Document Meaning Before Seeking Retrieval Efficiency
5.1 Document Parsing Cannot Extract Only Characters
In complex documents, heading hierarchies, table column relationships, footnotes, and page order can all affect meaning. If only characters are retained while structure is lost, the system might assign table values to the wrong fields or repeatedly retrieve headers and footers as main text.
After parsing, sample and verify:
- Is the section order complete?
- Are table fields and values correctly matched?
- Are there missing pages, garbled text, or duplicate content?
- Do OCR results affect key terms?
- Can the source location be accurately traced back?
For files with substandard parsing quality, repair or flag them first instead of pushing them directly into the Q&A pipeline.
5.2 Chunking Must Balance Completeness and Precision
If chunks are too large, they tend to include irrelevant content; if too small, they may split conditions, conclusions, and exceptions, distorting the evidence.
Therefore, avoid mechanical chunking by fixed character counts. More reasonable principles include:
- Prioritize chunking along headings, paragraphs, and clause boundaries;
- Preserve necessary section titles for body text chunks;
- Keep operational steps and preconditions adjacent where possible;
- Let table chunks carry field names;
- Retain moderate context for cross-paragraph relationships.
Chunk overlap can mitigate boundary information loss but will also increase storage and retrieval duplication. The optimal size should be evaluated using representative questions rather than applying a uniform value.
5.3 Establish Versioning and Deletion Mechanisms
After document updates, simply appending new chunks will leave old content participating in answers, eventually forming contradictory evidence.
Use stable document identifiers to manage updates: identify the scope of changes, replace affected chunks, clean up invalid indexes, and retain necessary version records. For deletion operations, synchronously process derived text, vectors, and caches to ensure that deleted raw materials can no longer be retrieved.
6. Recall and Reranking: Expand Coverage First, Improve Relevance Second
Semantic retrieval excels at discovering semantic associations between different expressions but is not always the most reliable for numbers, proper nouns, and exact strings. Keyword retrieval is better suited for these exact matching needs.
Therefore, you can combine the two recall methods based on data characteristics, followed by candidate merging and deduplication. However, scores from different retrieval methods are usually not on the same scale and cannot be simply summed for reliable sorting; verified normalization or fusion strategies should be applied.
Reranking occurs after initial recall; its purpose is not to search the entire knowledge base again, but to more accurately arrange existing candidates. It cannot recover materials that were not recalled.
Reranked results also require context consolidation:
- Remove highly redundant chunks;
- Supplement adjacent clauses if necessary;
- Retain evidence supporting key conclusions;
- Control total length according to the input budget;
- Avoid leaving only short conclusions while losing applicable conditions.
More candidates usually mean more reranking computation and higher latency. A sound practice is to evaluate the quality gain from different candidate ranges, then select a configuration that meets business requirements.
7. Answer Generation: Citations as Constraints, Not Decorations
The generation phase should explicitly require the model to answer only based on provided materials, distinguishing between definitive conclusions, conditional conclusions, and knowledge gaps.
A reliable output should at least:
- Provide corresponding sources for key conclusions;
- Locate citations to specific chunks;
- Not generalize local rules into universal ones;
- Not treat outdated materials as currently valid policies;
- Explain conflicts when evidence contradicts itself;
- Clearly state inability to confirm when materials are insufficient.
Merely listing document names at the end of an answer does not prove it is evidence-based. Check whether the cited chunks actually support the corresponding conclusions and whether the time, scope, and exception conditions in the chunks are correctly understood.
Furthermore, retrieved documents should be treated as data to be analyzed, not as system instructions. If text appears in a document requiring information disclosure, behavior change, or operation execution, it should not gain higher priority because of this.
8. Security and Operations: Enforcing Boundary Control in the Retrieval Process
Permission filtering should take effect before generating the context, not just hiding sensitive content in the final answer display. Otherwise, unauthorized materials may still enter the model input and leak through summaries, inferences, or logs.
Practical systems should also focus on the following measures:
- Use least privilege for service accounts;
- Limit uploaded file types, sizes, and parsing resources;
- Set timeouts, concurrency limits, and resource budgets for model calls;
- Desensitize sensitive fields in logs;
- Record document updates, permission changes, and management operations;
- Regularly verify backup and restoration procedures.
Offline ingestion tasks and online Q&A should ideally have resource isolation or priority control to prevent widespread user request timeouts during bulk imports.
9. Evaluation and Troubleshooting: Trace the Pipeline, Don’t Blindly Swap Models
When building an evaluation set, include common questions, vague expressions, multi-condition questions, cross-document questions, no-answer questions, and unauthorized questions, preparing expected evidence and judgment criteria for each.
Evaluation can be divided into three layers:
- Parsing Layer: Are key facts in the materials correctly preserved?
- Retrieval Layer: Does the correct evidence enter the candidates and appear in an available position?
- Generation Layer: Does the answer faithfully express the evidence, are citations accurate, and does it appropriately refuse to answer?
If an answer is wrong, troubleshoot along the pipeline:
Does the raw material contain the answer→ Does the parsed result preserve the answer→ Did chunking break the context→ Did recall find the correct chunk→ Did reranking lower the position of the correct chunk→ Did the input budget truncate key evidence→ Did the model misread or extrapolate without basis
This localization method is more effective and cost-controllable than directly swapping for a larger model. Meanwhile, separately observe the latency of retrieval, reranking, and generation, as well as failure rates, queue times, and resource usage, rather than just logging a single total response time.
10. Recommended Implementation Sequence
It is recommended to start with a small number of high-quality documents with clear permissions to establish a minimum viable pipeline, then gradually expand:
- Define scenarios, data boundaries, and acceptance criteria;
- Deploy and verify the three model services;
- Complete parsing, chunking, and metadata management;
- Establish basic retrieval and source display;
- Use the evaluation set to discover recall and answer issues;
- Introduce reranking, hybrid retrieval, and context optimization as needed;
- Add incremental updates, permission control, and operational mechanisms;
- Finally, conduct capacity testing and launch validation.
The core of Retrieval-Augmented Generation is not letting the model touch more text, but enabling the system to find applicable and credible evidence within the correct permission scope and accurately express its meaning. Model inference services provide basic capabilities, document governance determines knowledge quality, retrieval and reranking determine evidence selection, and evaluation and operations determine whether the system can run reliably over the long term.
