Building RAG agents with LLMs involves connecting a language model to a searchable knowledge base, exposing retrieval as an approved capability, and allowing the model to request additional evidence when the first search is insufficient. A reliable design limits the number of search rounds, respects document permissions, and checks whether the available evidence supports the final answer. Our AI agent caching guide covers version-aware reuse of retrieval results and embeddings without relaxing document access requirements.
For example, a retail policy assistant might retrieve a standard return period and then search separately for clearance-item exceptions before answering a customer’s question. The language model interprets the question and helps direct retrieval; the application enforces access rules and decides which operations are allowed. For conversation state and approved cross-session preferences, see our LangChain memory guide.
What is a RAG agent?
Retrieval-augmented generation (RAG) gives a language model relevant information at request time rather than relying solely on its training data. A RAG agent adds a decision layer that can reformulate a search, choose an authorized information source, or gather missing evidence before generating an answer. For a simpler conversational system that does not need autonomous search decisions, see our generative AI chatbot development guide.
| Approach | How it works | Best fit |
|---|---|---|
| Fixed retrieval followed by generation | The application retrieves evidence once, then passes it to the model. | Straightforward questions with a predictable source. |
| Agentic RAG | The model can request further permitted searches or choose among tools. | Questions requiring several information sources or investigation steps. |
| Hybrid RAG | A fixed retrieval step is followed by validation and conditional additional searches. | Applications that need predictable initial behavior and limited flexibility. |
Use the simplest architecture that meets the task. More retrieval rounds add cost and latency, and extra model calls do not guarantee accuracy. Our guide to agentic workflows explains how model-driven decisions can be combined with fixed application rules. For a broader view of model inputs, validation and human review, see our generative AI workflow guide.
RAG agent architecture
A typical system has a preparation path and a request-time path. During preparation, the application processes authorized documents, divides them into useful passages, and indexes them with metadata. At request time, it retrieves relevant passages and supplies them to the model for interpretation.
Prepare passages, source IDs, permissions and index
Search only permitted records
Assess evidence ยท request another search if justified
Source identifiers ยท limitations ยท execution record
| Component | Purpose |
|---|---|
| Document ingestion | Extract text, track versions and assign source identifiers. |
| Retrieval index | Find relevant passages using keyword matching, semantic similarity, or both. |
| Retrieval tool | Return a limited set of authorized passages with metadata. |
| Language model | Interpret questions, propose searches, and synthesize evidence. |
| Controller | Validate tool requests, manage state, and enforce execution limits. |
| Answer validation | Check whether cited passages exist, support claims, and belong to the authorized evidence set. |
A vector database is useful for semantic retrieval, but it is not mandatory. A small, structured knowledge base can use keyword search, database queries, or an existing document search service. Knowledge graphs can complement retrieval when questions depend on explicit relationships between entities, but they introduce additional data-modeling and maintenance requirements.
How to build RAG agents with LLMs
1. Define the knowledge and task boundaries
Choose a narrow question-answering task and identify the authoritative records it requires. Decide which users may read each record and which outputs the system may produce. For a support assistant, current published policies and product documentation may be sufficient. Historical versions should not silently override current policy.
2. Prepare documents for retrieval
Split longer documents along logical boundaries such as headings, paragraphs, and related tables. Store each passage with its source ID, version, section, and access-control metadata. Do not assume that one universal chunk size works for every corpus. Evaluate whether a passage contains enough context to answer questions without pulling unrelated material into the model’s context.
Keyword search can perform well for exact identifiers and terminology. Embedding-based search helps find semantically related text, and hybrid approaches can combine the results. Re-ranking may improve the ordering of retrieved passages, but measure the benefit against additional latency.
3. Expose retrieval as a limited tool
Give the model a narrow search operation rather than raw access to the entire database. The application should determine permitted document IDs from authenticated user context, not from model-generated arguments. Set maximum result counts and return source references with the text. See our AI agent integration guide and tool discovery guide for the broader tool-access layer.
4. Add a bounded decision loop
Start with the original question. Retrieve relevant material and assess what is missing. Permit a small number of additional queries if the question needs clarification, alternative terminology, or evidence from another approved source. End when the task has sufficient evidence, when the execution budget is exhausted, or when another search is unlikely to help.
This combines tool use, planning, and optional reflection, which are covered in our agentic design patterns guide. Do not confuse a model’s self-assessment with an independent verification that the answer is correct.
5. Generate a grounded response
Supply only relevant, authorized passages and instruct the model to distinguish evidence from inference. Use structured output containing the answer, referenced passage IDs, and any missing information. Validate the references against the actual retrieved records. A valid source ID alone does not prove that the associated claim follows from the passage; evaluate claim support separately.
A practical Python retrieval example
The following dependency-free Python example demonstrates a bounded retrieval controller against three fictional policy records. It uses exact token overlap instead of embeddings and a deterministic mock decision function instead of a live language model. This isolates the behavior of the retrieval and control layers. If you are new to Python tool-calling agents, begin with our agentic AI tutorial.
Save the example as rag_demo.py and run it using Python 3. The permission set is supplied by the application. The second search deliberately looks for the clearance exception, demonstrating how a follow-up query can expand the available evidence.
import re
DOCS = {
'D1': 'Standard returns are accepted within 30 days.',
'D2': 'Clearance items are final sale.',
'D3': 'Standard shipping takes five business days.',
}
def tokens(text):
return set(re.findall(r'[a-z0-9]+', text.lower()))
def retrieve(query, allowed_ids, limit=2):
q = tokens(query)
scored = [(len(q & tokens(text)), doc_id, text)
for doc_id, text in DOCS.items()
if doc_id in allowed_ids]
ranked = sorted(scored, key=lambda x: (-x[0], x[1]))
return [(doc_id, text) for score, doc_id, text
in ranked[:limit] if score > 0]
def gather(question, allowed_ids, decide, max_rounds=3):
evidence, seen = {}, set()
query = question
for _ in range(max_rounds):
if not isinstance(query, str) or not query.strip():
break
key = query.strip().lower()
if key in seen:
break
seen.add(key)
evidence.update(retrieve(query, allowed_ids))
query = decide(question, dict(evidence))
if query is None:
return evidence
return evidence
def demo_decide(question, evidence):
if 'D2' not in evidence:
return 'clearance final sale'
return None
result = gather('standard returns', {'D1', 'D2'}, demo_decide)
print(result)
The example returns D1 and D2, the standard return rule and clearance exception. It returns evidence rather than a generated answer. The demo decision function is specific to this fictional task and is not a general-purpose agent.
Connect a real language model
To turn the mock into an LLM-driven workflow, replace the decision function with a model adapter. Provide the original question, retrieved passages, and a clear instruction to return either a new search query or a stop decision. Parse that output into a validated structure. Return None only for a valid stop decision and reject malformed or unauthorized requests. The controller must retain its search-round limit regardless of what the model requests. Our guide to LangChain alternatives discusses framework selection for bounded retrieval and agent applications. For a framework-based implementation, LangGraph supports explicit retrieval loops and conditional transitions. See our Haystack vs. LangChain comparison for alternative approaches to composing retrieval pipelines and agent tool loops.
After gathering evidence, call the model to compose the answer with the source IDs. If the evidence is incomplete or conflicting, require the answer to explain the gap or decline to make an unsupported claim. The language model API integration and final answer quality need separate testing.
Test the retrieval and control behavior
Append these assertions to the demonstration to check the expected documents, denied access, missing evidence, repeated queries, and empty results.
assert set(result) == {'D1', 'D2'}
assert retrieve('clearance', {'D1'}) == []
assert retrieve('warranty', {'D1', 'D2', 'D3'}) == []
assert gather('standard returns', {'D1'}, lambda q,e: q) == {'D1': DOCS['D1']}
assert gather('warranty', {'D1'}, lambda q,e: None) == {}
print('5/5 checks passed')
All five local checks passed when the Python retrieval example was executed. No live model request was made. These checks verify the deterministic retrieval and controller behavior, not the quality of an LLM-generated answer.
How to evaluate RAG agents
Build an evaluation set before choosing a more complex retrieval strategy. Include questions that have a clear answer, questions that need multiple passages, outdated or contradictory records, and questions that have no answer in the knowledge base. Include access-control cases where a relevant document exists but the requester is not authorized to view it.
| Evaluation area | What to measure |
|---|---|
| Retrieval quality | Whether expected supporting passages appear in retrieved results. |
| Groundedness | Whether material claims are supported by the supplied evidence. |
| Reference accuracy | Whether referenced IDs exist and refer to the correct passages. |
| Abstention | Whether the system reports insufficient evidence when necessary. |
| Access control | Whether restricted documents remain inaccessible. |
| Efficiency | Search rounds, latency, model usage and cost per verified answer. |
Compare the agentic design with a simpler retrieve-then-generate baseline. If extra searches do not improve task-level accuracy or coverage enough to justify their cost, retain the simpler design. Test on representative held-out questions rather than only the examples used during development.
Production deployment and security
Treat retrieved documents as untrusted content. A document may contain text that attempts to direct the model to reveal secrets, ignore permissions, or perform unrelated actions. Enforce access controls before retrieval, keep credentials outside prompts, and prevent retrieved text from modifying application policy.
Track document updates and deletions so stale records do not remain searchable indefinitely. Maintain an explicit retention policy for stored prompts and retrieved passages. Limit concurrent requests, tool calls, tokens, and execution time. For sensitive workflows, add independent authorization and approval gates using the principles in our AI workflow automation governance guide.
Monitor retrieval failures separately from generation failures. A correct answer is impossible when necessary records are missing or inaccessible, even if the model produces a convincing response. Investigate those failures at the data, retrieval, controller, and generation layers rather than changing the prompt indiscriminately.
Frequently asked questions
Do RAG agents require fine-tuning?
No. RAG retrieves information at request time. Fine-tuning changes model behavior through training and addresses a different requirement.
Do I need a vector database to build a RAG agent?
No. Use a retrieval method appropriate to the data and queries. Keyword search, structured queries, existing search systems, and vector search can all support RAG.
What is the difference between RAG and agentic RAG?
A conventional RAG pipeline retrieves information in a predefined sequence. Agentic RAG lets the model choose retrieval actions or request further searches within an application-controlled process.
Can RAG eliminate hallucinations?
No. Retrieval can improve grounding, but irrelevant or outdated passages and unsupported model claims remain possible. Evaluate evidence quality and final claim support.
When should a RAG agent stop searching?
Stop when the evidence is adequate, when additional retrieval is unlikely to help, or when a defined budget is reached. If required information remains unavailable, explicitly report the limitation.

