October 26, 2026
Implementation and Validation of a RAG System for Query Optimization in Corporate Documents
Rosicleide Aparecida Fonseca Xistulino; Edilson José Rodrigues
DOI: 10.22167/2675-6528-202603436
Article derived from a Course Conclusion Work (TCC), with content based on the student’s original work and adapted to the editorial format of the E&S Magazine with the support of the ResumeAI tool, an artificial intelligence solution developed by Instituto Pecege for textual synthesis and organization.
Summary
The use of large language models in corporate environments presented limitations related to factuality, information traceability, and access to specific domain content, potentially compromising the reliability of generated responses. A Retrieval-Augmented Generation (RAG) architecture was implemented and validated to optimize queries in technical documents, simulating a corporate document base. The research, of an applied and experimental nature, was developed in Python. Documents were segmented into chunks of 500 tokens with an overlap of 80, converted into embeddings, and stored in the ChromaDB vector database. For each query, the five semantically most similar chunks were retrieved, used as context for generating responses by a GPT language model. Performance was evaluated through precision, recall, latency, semantic similarity, context fidelity, hallucination rate, and security tests. The system achieved a precision of 1.00, recall of 0.88, and an average latency of 2.39 seconds. Semantic similarity and context fidelity averaged 0.85, with a hallucination rate of 0.00 and 100% guardrail effectiveness in tests. The results indicated that the implemented architecture increased the adherence of responses to the documentary content, demonstrating potential for corporate applications that demand greater precision, traceability, and control of information.
Keywords: embeddings; guardrails; artificial intelligence; language models; semantic retrieval.
1. Introduction
The evolution of large language models (LLMs) has significantly expanded the possibilities for applying Natural Language Processing (NLP) in activities related to information retrieval, interpretation, and generation. These models have demonstrated the ability to generate coherent and contextually relevant texts in various tasks.
However, the use of these models in corporate environments has presented notable challenges. Limitations include issues of factuality, information traceability, and access to domain-specific content. Such challenges can result in the generation of inaccurate or unfounded information, a phenomenon known as hallucination, compromising the reliability of the produced responses.
In this context, Retrieval-Augmented Generation (RAG) emerged as a promising alternative. This architecture integrates the generative capability of language models with information retrieval mechanisms from external databases. The RAG approach allows complementing the parametric knowledge of the models with information retrieved at query time, reducing exclusive reliance on the data used during their training and favoring access to specific and updated content (CASELI; NUNES, 2024).
The RAG architecture combines semantic retrieval and natural language generation mechanisms, enabling relevant documents to be selected and used as context for elaborating responses. This characteristic is especially relevant in organizational applications, where the precision and traceability of information are important requirements for the use of language models. Previous studies have indicated that the incorporation of external information retrieval mechanisms contributes to increasing the accuracy and relevance of responses and reducing the occurrence of content not based on domain-specific queries (ARSLAN et al., 2024; MEDEIROS; OLIVEIRA, 2025).
In the corporate environment, a large part of organizational knowledge is stored in technical documents, manuals, standards, and procedures. Locating specific information in these textual archives can be time-consuming. Semantic retrieval-based systems, such as RAG, show potential for transforming these static documentary sets into knowledge bases that can be queried using natural language. The application of the RAG architecture is therefore relevant for situations where answers need to remain linked to the available documentary content, allowing for greater control over the information used by the model.
Given this context, this work aimed to implement and validate a system based on the Retrieval-Augmented Generation architecture to optimize the query of technical documents used as a simulation of a corporate document base.
2. Material and Methods
The research was characterized as applied, experimental, and quantitative, focused on the development, implementation, and evaluation of a computational system. The study was conducted in a controlled environment, aiming to evaluate the capacity of a Retrieval-Augmented Generation (RAG) system to retrieve information from technical documents and generate natural language responses. The work was developed in Python language, implementing the RAG architecture, which integrated semantic retrieval mechanisms, vector storage, and response generation by a large language model. Controlled experiments were performed, including a comparison between the RAG architecture and a language model without context retrieval (pure LLM), to verify the impact of document retrieval on the quality and adherence of the responses.
The knowledge base was composed of vehicle technical manuals, publicly available online, which served as a textual corpus to simulate a corporate document base. These documents were selected for their structured technical content, specific terminology, and the need for precise information localization to answer queries.
The documentary corpus was subjected to stages of textual extraction, segmentation, transformation into vector representations, and storage. The documents were divided into “chunks” of 500 tokens, with an overlap of 80 tokens between consecutive segments, aiming to preserve semantic continuity and minimize information loss in transitions.
After segmentation, the chunks were converted into embeddings using the text-embedding-3-small model. The resulting vectors were stored in the ChromaDB vector database. This database was used both for indexing the documentary segments and for retrieving the content semantically most related to user questions.
For each query, its vector representation was compared with the representations stored in ChromaDB. The five most semantically similar segments (top-k = 5) were retrieved, using cosine similarity as the criterion. These selected segments were combined with the original question and used as context for the language model’s response generation.
In the generation stage, the OpenAI API was used to access a GPT family model. The model received the user’s query and the retrieved segments, producing the response based on the provided context. Generation was configured with a maximum limit of 200 tokens per response and the model’s temperature was set to 0.0, to reduce variability and promote consistency.
The model’s behavior was controlled by a structured prompt, which instructed it to respond solely based on the retrieved context and to report the absence of information in the manual, including the page when possible. This control aimed to restrict the response to the information in the documentary base and avoid the generation of unsubstantiated content.
The system validation was performed through quantitative and qualitative analyses, evaluating response quality, computational performance, and architecture robustness. Performance dimensions included precision, recall, total response latency, semantic similarity, faithfulness to context, occurrence of hallucinations, and behavior when faced with adversarial or out-of-domain queries. The comparative evaluation between RAG and pure LLM used 100 questions representative of the technical manual’s domain. The robustness of the security mechanisms, or guardrails, was evaluated with out-of-domain questions, requests for non-existent functionalities, attempts to induce hallucinations, and prompt injection attacks. Behavior was considered adequate when the system refused the request or restricted its response to the content available in the documentary corpus.
3. Results and Discussion
The experiments carried out allowed us to evaluate the behavior of the RAG architecture in relation to a language model used without context retrieval, as well as to analyze the quality of the produced responses, the temporal performance, the fidelity to the documentary content, and the robustness of the security mechanisms. The results were evaluated considering the metrics defined in the methodology and interpreted according to the characteristics of the implemented architecture, providing a comprehensive view of the system’s performance.
Comparison between pure LLM and RAG architecture
The comparison between the purely generative language model, named pure LLM, and the RAG architecture was performed using 100 questions representative of the technical manual domain used in the study. The questions covered general content and specific technical information, allowing for the evaluation of the behavior of both methods when faced with different levels of complexity, which provided a comprehensive basis for comparative analysis.
The RAG architecture presented, in most queries, higher semantic similarity values than those obtained by the pure LLM. The RAG results were predominantly concentrated above 0.80 and reached values close to or equal to 1.00 in some questions, indicating greater consistency and precision. In contrast, the pure LLM showed greater variability, with a higher occurrence of intermediate values and sharper drops in certain queries, evidencing lower stability in the quality of responses. The distribution of these semantic similarity scores across the evaluated questions illustrated this performance difference.
The observed differences in semantic similarity indicated greater stability of the RAG architecture in producing responses semantically close to the expected content. This behavior was directly related to the incorporation of the retrieval step, which provided the model with information directly extracted from the documentary corpus before generating the response. In the model used without retrieval, the response remained more dependent on the parametric knowledge acquired during training, which can lead to greater variations in quality and factuality.
This result aligned with the foundation presented by Arslan et al. (2024), who highlighted how the incorporation of external retrieval mechanisms in generative systems can elevate the precision and relevance of responses in domain-specific queries. Semantic retrieval also allowed for the location of content conceptually related to the questions even when there was no literal term correspondence, a characteristic compatible with the functioning of dense retrieval described by Karpukhin et al. (2020), reinforcing the system’s ability to understand context.
Despite the general superiority observed for RAG, the variation in scores across questions demonstrated that the use of context retrieval did not entirely eliminate performance differences. The quality of the answers remained dependent on the retrieval mechanism’s ability to select suitable segments from the corpus, an aspect directly related to the segmentation strategy, the embeddings used, and the number of retrieved segments, suggesting areas for future optimization.
Accuracy of responses
In the specific evaluation of the RAG system, precision equal to 1.00 and recall equal to 0.88 were obtained. The precision value indicated that, among the answers provided by the system in the evaluated set, no incorrect answers were identified, demonstrating high assertiveness. The recall of 0.88, however, showed that approximately 12% of the questions considered in the evaluation process did not receive a valid answer from the system, pointing to a limitation in the total coverage of queries.
The difference between the two metrics highlighted a conservative behavior of the architecture. The system showed high assertiveness when it responded, but did not achieve full coverage of the queries, which is an indication of caution. This behavior may be associated with the retrieval stage, as the absence of sufficiently relevant segments may have led the model not to produce a response, in accordance with the restrictions imposed by the prompt, prioritizing quality over the quantity of responses.
From a reliability standpoint, this result represented a positive characteristic, as the architecture favored the absence of a response in situations of insufficient information rather than the generation of content without documentary support. On the other hand, the recall below 1.00 evidenced a coverage limitation that should be considered in applications where it is necessary to respond to the largest possible proportion of queries, balancing precision with completeness.
System temporal performance
The total latency of the RAG system varied between approximately 0.86 and 5.56 seconds, with an average of 2.39 seconds per question. The measurement included both the time required for retrieving segments semantically related to the query and the inference time of the language model for producing the final answer, providing a complete view of temporal performance.
Even with the inclusion of the additional retrieval step, the average time remained in a few seconds during the experiments conducted. This result indicated that the inclusion of the vector database and semantic search did not impede the interactive functioning of the system in the adopted experimental environment, which is crucial for real-time applications. Compared to the pure LLM, RAG showed a reduction in latency for some of the evaluated queries, suggesting an optimization in specific scenarios.
This result should be interpreted specifically in the experimental context of the work, as the response time can be influenced by the query content, the volume of context provided to the model, the computational environment, and the API processing time. Therefore, it was not possible to state, based on the experiments conducted, that the RAG architecture would necessarily produce lower latency in other environments or documentary sets, highlighting the need for validation in different scenarios.
Semantic similarity of responses
In the specific evaluation of the responses produced by the RAG system, the semantic similarity values ranged between 0.80 and 0.92, with an overall average of 0.85. The results indicated a high proximity of meaning between the generated responses and the expected responses, even when there was no exact textual correspondence, which demonstrates the system’s ability to capture the essence of the information.
This behavior was compatible with the generative nature of the model employed, as semantically equivalent responses could be formulated with different linguistic constructions. Thus, the semantic similarity evaluation allowed for the preservation of the essential content of the response without requiring literal reproduction of the text used as reference, an important aspect for the flexibility and naturalness of interactions.
Fidelity to the retrieved context
In addition to the proximity to the expected answers, it was assessed whether the produced content remained grounded in the retrieved documents. Fidelity to context presented an average of 0.85, with values between approximately 0.80 and 0.92. Question 11 presented the highest recorded score, equivalent to 0.92, indicating strong adherence. The distribution of individual values and the average obtained by the system are presented below.
In the analysis of contextual fidelity, the values remained equal to or higher than approximately 0.80, demonstrating that the responses presented a high degree of adherence to the information provided during the retrieval stage. This finding is crucial for reliability in corporate environments, where information traceability is a fundamental requirement.
Context fidelity was a relevant metric for the study’s purpose because it assessed not only whether the response presented a similar meaning to the expected content, but also whether it remained grounded in the evidence provided to the model. This result was related to the central objective of the RAG architecture to use retrieved documents as a basis for textual generation. Context fidelity and relevance metrics are used precisely to evaluate the grounding of RAG systems and the adequacy of the information retrieved for the query made (ES et al., 2023), confirming the validity of the approach.
The average result of 0.85 also indicated that fidelity was not absolute across all questions. The differences between the scores demonstrated that the quality of the reasoning varied according to the query and the segments provided to the model. Thus, the results did not allow for the retrieval to be considered invariably perfect, but they showed a high level of adherence in the analyzed set, which is a positive point for practical application.
Hallucination rate
The hallucination rate recorded in the evaluated set was 0.00. According to the criterion adopted in the study, none of the classified responses presented information not based on the reference documents, which is a highly desirable outcome for corporate information systems. This finding reinforces the architecture’s ability to avoid generating inaccurate content.
The result indicated that the combination of semantic retrieval, restrictive prompt, and control mechanisms was effective in the experimental set used. The model was instructed to use only the information provided in the context and not to respond when there was insufficient content available, a behavior that also contributed to simultaneously explaining the absence of hallucinations and a recall of 0.88, evidencing a robust safety strategy.
The absence of hallucinations should, however, be interpreted within the limits of the experiment. The result corresponded to the questions and evaluation criteria used in this work and did not mean that the architecture was unable to produce hallucinations in other datasets, domains, or conditions of use. The literature used to ground the study itself highlighted that the RAG architecture reduces the risk of unfounded information, but its performance remains associated with the quality of retrieval and the context provided to the model (ARSLAN et al., 2024), indicating the need for continuous vigilance.
Security and robustness evaluation of guardrails
Security tests included questions outside the manual’s domain, requests for non-existent functionalities, attempts to induce hallucination, queries requiring knowledge external to the corpus, and prompt injection attacks. In the evaluated scenarios, the system refused requests deemed incompatible with the domain or restricted its responses to information available in the documentary base, demonstrating its self-protection capability.
The effectiveness recorded for the guardrails was 100% on the specific test set developed for this purpose. The result demonstrated that the instructions embedded in the system were respected in all evaluated adversarial situations, which is a strong indicator of the robustness of the implemented security mechanisms. This level of effectiveness is fundamental for the adoption of LLMs in sensitive corporate environments.
The observed behavior reinforced the importance of using additional control mechanisms in conjunction with the RAG architecture. Context retrieval, in isolation, did not constitute a complete security mechanism. The guardrails acted as a complementary layer intended to restrict out-of-domain responses and attempts to alter system instructions, an approach consistent with the function assigned to these mechanisms in corporate applications (ZHOU et al., 2024), ensuring the integrity and compliance of the responses.
Just as with the hallucination rate, the 100% effectiveness corresponded specifically to the test set used in this study. The quantity and diversity of adversarial attempts were limited, therefore the result did not allow us to infer absolute resistance to all possible forms of attack or manipulation, suggesting that more extensive and varied tests would be beneficial for a complete robustness evaluation.
Jointly, the results indicated that the implemented RAG architecture presented greater adherence to the documentary content than the language model used without context retrieval, responding to the study’s objective. The precision of 1.00 evidenced high assertiveness of the provided answers, while the recall of 0.88 demonstrated that this assertiveness was accompanied by lower coverage of part of the queries. Semantic similarity and context fidelity presented an average of 0.85, and no hallucinations were identified according to the criteria adopted in the evaluated set. The guardrails also responded adequately to all security tests performed, reinforcing the system’s reliability.
From an applied point of view, these findings demonstrated the potential of the RAG architecture for querying technical document bases in contexts that require greater traceability and substantiation of answers. Content retrieval before generation allowed for reduced exclusive reliance on the model’s parametric knowledge and linked the answers to the information present in the corpus used, which is a significant advantage for corporate knowledge management. However, the results also highlighted relevant limitations, such as the evaluation in a controlled environment and the dependence on the performance of segmentation and embedding parameters, suggesting the need for future investigations in more complex scenarios.
4. Conclusion
This work aimed to implement and validate a system based on the Retrieval-Augmented Generation architecture to optimize the query of technical documents, simulating a corporate document base. It was found that the RAG architecture demonstrated greater stability and semantic similarity in responses compared to a language model used without context retrieval. A precision of 1.00 was observed, indicating high assertiveness of the provided answers, and a recall of 0.88, which reflected a conservative behavior of the system by prioritizing quality over completeness of answers in case of insufficient context. Semantic similarity and fidelity to the retrieved context showed an average of 0.85, evidencing the high adherence of the answers to the documentary content. Additionally, a hallucination rate of 0.00 and an effectiveness of 100% of the guardrails in security tests were recorded, reinforcing the system’s reliability and robustness. These findings indicate the potential of the RAG architecture to transform static document bases into searchable knowledge sources, offering greater precision, traceability, and control of information in corporate environments.
However, the results should be interpreted considering the study’s limitations. The evaluation was conducted in a controlled environment, using technical documents to represent a corporate database, without encompassing the complexity of real organizational environments, such as document heterogeneity, outdatedness, or multiple users. The system’s performance also proved dependent on parameters like segmentation strategy, embedding model, and retrieval approach. For future studies, it is recommended to evaluate the RAG architecture in more complex scenarios, including real corporate documents and larger, more heterogeneous databases. It is also suggested to explore different configurations of segmentation, embeddings, and retrieval strategies, as well as to conduct tests in operational environments with multiple users for a more comprehensive evaluation of the system’s scalability, performance, and robustness.
Bibliographic References
Arslan, M.; Ghanem, H.; Munawar, S.; Cruz, C. 2024. A survey on RAG with LLMs. Procedia Computer Science 246: 3781-3790.
Caseli, H.M.; Nunes, M.G.V. (org.). 2024. Processamento de Linguagem Natural: conceitos, técnicas e aplicações em português. 3ed. BPLN, São Carlos. Disponível em: <https://brasileiraspln.com/livro-pln>. Acesso em: 23 abr. 2026.
Es, S.; James, J.; Espinosa-Anke, L.; Schockaert, S. 2023. RAGAS: automated evaluation of retrieval-augmented generation. arXiv preprint. Disponível em: <https://arxiv.org/abs/2309.15217<. Acesso em: 23 abr. 2026.
Karpukhin, V. et al. 2020. Dense retrieval para recuperação de informações em sistemas de pergunta e resposta.
Medeiros, L.S.F.; Oliveira, H.T.A. 2025. Comparação de modelos de embeddings e LLMs para geração aumentada por recuperação em português. IFES.
Zhou, J.; Patel, R.; Singh, A.; Kumar, V. 2024. Building guardrails for large language models: ensuring safety and reliability in enterprise applications. arXiv preprint. Disponível em: <https://arxiv.org/abs/2403.12345>. Acesso em: 23 abr. 2026.
Article originating from the Final Course Project of the Specialization in Data Science and Analytics of the MBA USP/Esalq
To learn more about the course, click here and access the MBX Academy platform