What is Agentic RAG? Building Multi-Agent Agentic RAG Systems
From the publisher’s feed, collected in the ZeroLabs newsroom.
Explore Agentic RAG. Learn its benefits and how to implement it using LangChain.Retrieval-Augmented Generation (RAG) interacts with huge information repositories, combining the power of large language models (LLMs) with focused data retrieval to provide precise and contextually relevant responses. It emerged as a fundamental component for precision-based applications to integrate a retriever that extracts data from a knowledge base with a generative model that produces coherent answers.However, as AI systems grow and become more adaptive and complex, traditional RAG approaches show limitations in flexibility and reasoning. Agentic RAG introduces intelligent, self-sufficient agents that enhance RAG with dynamic decision-making, multi-step reasoning, and task management capabilities. This article examines Agentic RAG, its benefits, and how to implement an agentic RAG using Phidata and LangChain.Understanding Traditional RAGRAG is a hybrid AI framework that enhances the capabilities of LLMs by integrating external knowledge retrieval. Standalone LLMs depend on their pre-trained knowledge, whereas RAG integrates a retriever with LLMs to deliver accurate, contextually relevant responses based on specific data sources.RAG primarily addresses situations where LLMs might generate outdated or incomplete answers by retrieving current or domain-specific information from a knowledge base.The traditional RAG workflow is straightforward: a user submits a query that the retriever processes to identify and retrieve relevant documents or data from a pre-indexed knowledge base. These retrieved items are then passed to the LLM, synthesizing them into a coherent response to improve accuracy.For example, when answering a question about recent scientific discoveries, RAG can retrieve the latest research papers and use them to inform the LLM’s output.How traditional RAG works (Source)Although traditional RAG has strengths, it also has limitations. Its workflow is static, adhering to a fixed sequence of retrieval and generation that struggles with complex, multi-step tasks. It lacks adaptability to refine queries or adjust strategies based on intermediate results.Additionally, traditional RAG does not inherently support advanced reasoning, such as validating retrieved information or orchestrating multiple data sources for a single task. These constraints highlight the necessity for an advanced approach such as Agentic RAG.What is Agentic RAG?Agentic RAG incorporates intelligent, autonomous agents into the RAG framework. At its core, an agent-based implementation enhances the retrieval and generation process with dynamic decision-making, adaptability, and advanced reasoning capabilities.An Overview of Multi-Agent Agentic RAG Systems (Source)The key components of agentic RAG extend beyond the traditional setup of a query, retriever, knowledge base, and LLM. Agentic RAG introduces specialized agents that perform distinct roles, while traditional RAG elements remain foundational:Query Understanding Agent: Understands and refines user queries for greater precision.Knowledge Base Management Agent: Curates and optimizes the knowledge base for relevance and accessibility.Retrieval Strategy Agent: Selects optimal retrieval methods based on the query’s complexity.Result Synthesis Agent: Integrates retrieved data into coherent, context-aware responses.Iterative Querying Agent: Refines queries iteratively to improve results.Task Orchestration Agent: Coordinates the workflow among agents for seamless execution.Multimodal Integration Agent: This incorporates diverse data types, such as text, images, or structured data.Continuous Learning Agent: Adapts and improves the system over time based on feedback.These agents work collaboratively to handle complex tasks with greater flexibility and intelligence. This method turns RAG into a proactive, self-improving system able to address dynamic and multifaceted challenges.Benefits of Agentic RAGAgentic RAG offers several advantages that improve upon the capabilities of traditional RAG in managing complex, knowledge-driven tasks. These benefits include:Greater Accuracy: Delivers precise, contextually relevant responses through dynamic reasoning and validation of retrieved information.Autonomous Task Execution: Performs complex, multistep processes independently, reducing the need for constant human oversight.Enhanced Human-AI Collaboration: Interprets nuanced instructions and provides tailored assistance, fostering seamless interaction in applications like research or customer support.Superior Information Quality: Intelligently selects and synthesizes high-quality data from diverse sources, filtering out irrelevant or unreliable information.Robust Outputs: Uses reasoning to cross-check and refine data, ensuring cohesive and reliable insights.Now that we have covered the benefits, let’s explore the implementation details of Agentic RAG.Implementation of Agentic RAG Using Phidata and LangChainImagine an AI assistant that is not only a jack-of-all-trades but also a master of several, managing a team of specialist AI agents:One agent is an expert on a specific document you provide.Another excels at Python coding.A third can solve math problems.A fourth assists in drafting emails.Additionally, a fifth can research and recommend products.A central Router Agent is the manager that directs questions to the agent best suited for the job.We’ll use several Python libraries:phidata: To create and manage our AI agents.langchain: To handle loading and processing documents (the “RAG” part).chromadb: To store document information efficiently for searching.openai: To access powerful language models like GPT-4o-mini.PrerequisitesOpenAI API Key: You will need an API key from OpenAI to use their AI models. You can get one from the OpenAI platform.Python Environment: We will use Google Colab for this guide (recommended), but you can also use a local Jupyter Notebook.A PDF Document: The code is set up to learn from a PDF named Agentic rag paper.pdf. You will need to have this file ready.Step 1: Setting Up Your Environment (Installing Libraries)First, we need to install all the necessary Python packages. If you are in Google Colab or a Jupyter Notebook, run these commands in a code cell:# Install libraries for agents, AI models, and vector storage!pip install phidata langchain chromadb openai# Install supporting libraries for document loading, text splitting, and web search!pip install -qU langchain-community pypdf tiktoken duckduckgo_searchphidata, langchain, openai, and chromadb are the main tools.langchain-community, pypdf, tiktoken, and duckduckgo_search provide specific functionalities like loading PDFs, processing text for AI models, and enabling web searches for some agents.Step 2: Importing Tools and Configuring AccessNow, let’s import the specific functions and classes we’ll need and set up access to the OpenAI API.import osimport getpass # Used for securely inputting your API key# Phidata components for building agents and using toolsfrom phi.agent import Agentfrom phi.knowledge.langchain import LangChainKnowledgeBasefrom phi.model.openai import OpenAIChatfrom phi.tools.duckduckgo import DuckDuckGo # Web search tool# LangChain components for document handling and vector storagefrom langchain.vectorstores import Chromafrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.document_loaders import PyPDFLoaderfrom langchain.text_splitter import RecursiveCharacterTextSplitter# --- Configure OpenAI API Key ---# Paste your key and press Enter.os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")print("Libraries imported and API key environment variable set (hopefully!).")API Key: The getpass.getpass(…) line creates a secure prompt for your OpenAI API key. Make sure you paste your key correctly when prompted. This key allows your code to use OpenAI’s AI models.Step 3: Building the Knowledge Base (Teaching the AI about your Document)One of our agents needs to be an expert on a specific PDF document. Here’s how we prepare the information from that document:3a. Specify and Load the Document# --- IMPORTANT: Prepare your PDF ---# Make sure you have uploaded a PDF file ending with .pdf."pdf_file_path = "/content/FilePath.pdf" # path to your file# Load the document content using LangChain's PDFLoaderprint(f"Attempting to load PDF from: {pdf_file_path}")pdf_loader = PyPDFLoader(file_path=pdf_file_path)source_documents = pdf_loader.load()print(f"Successfully loaded {len(source_documents)} pages from the PDF.")pdf_file_path: This variable holds the location of your PDF. Crucially, you must ensure the PDF file exists at this exact path before running this code. If you use Google Colab, upload the file FilePath.pdf to your session’s file storage (usually accessible via a folder icon on the left).PyPDFLoader: This tool from LangChain reads the text content from your PDF file.3b. Split the Document into ChunksAI models work better with smaller pieces of text. We split the loaded document into manageable chunks.# Initialize the text splittertext_chunker = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)# Split the loaded documentschunked_documents = text_chunker.split_documents(source_documents)print(f"Document split into {len(chunked_documents)} chunks.")3c. Embed and Store the ChunksTo make the document searchable by meaning (not just keywords), we convert the text chunks into numerical representations (vectors or “embeddings”) and store them in a special database (Chroma).# Define the directory to persist the vector databasepersist_directory = "./chroma_db_agentic"# Create the Chroma vector store, providing the embedding function and persistence pathvector_database = Chroma( embedding_function=OpenAIEmbeddings(), persist_directory=persist_directory)# Add the document chunks to the vector storevector_database.add_documents(chunked_documents)print(f"Document chunks embedded and added to ChromaDB at {persist_directory}")3d. Create a Retriever and Knowledge Base ObjectFinally, we create an interface (retriever) to easily search the vector database and wrap it in a format (LangChainKnowledgeBase) that our Phidata agents can understand.# Create a retriever interface for querying the vector storedb_retriever = vector_database.as_retriever()# Create the knowledge base object accessible to Phidata agentsrag_knowledge_base = LangChainKnowledgeBase(retriever=db_retriever)print("Knowledge Base created successfully and ready for the QA Agent.")Step 4: Creating the Specialist AgentsNow, let’s define our team of AI specialists using phidata.Agent. Each agent gets a name, a role, instructions on how to behave, and access to tools or knowledge if needed.Agent 1: Document QA Assistant# Agent 1: Document QA Assistantdoc_qa_agent = Agent( name="Document QA Agent", role="Expert on the provided RAG document.", instructions=[ "You are a helpful assistant specializing in the content of the Agentic RAG document.", "Use the available knowledge base to answer questions accurately.", "If the answer is not found in the knowledge base, state that clearly.", ], model=OpenAIChat(model="gpt-4o-mini"), # Specify the model knowledge_base=rag_knowledge_base, # Link the KB search_knowledge=True, # Enable KB search add_context=True, # Add retrieved context to the prompt markdown=True # Format output as Markdown)Agent 2: Python Code Assistant# Agent 2: Python Code Assistantpython_coder_agent = Agent( name="Python Coder Assistant", role="Generates and explains Python code snippets.", instructions=[ "You are an expert Python programmer.", "Generate clear, efficient Python code based on the user's request.", "If asked to explain code, provide a step-by-step breakdown.", "Focus only on Python programming tasks.", "Do not execute the code unless specifically asked and capable.", # Safety instruction ], model=OpenAIChat(model="gpt-4o-mini"), markdown=True # Code often looks better in Markdown)Agent 3: Mathematical Assistant# Agent 3: Mathematical Assistantmath_assistant_agent = Agent( name="Mathematical Assistant", role="Solves mathematical problems and explains concepts.", instructions=[ "You are a helpful math tutor.", "Solve the mathematical problems presented by the user accurately.", "Explain mathematical concepts clearly if requested.", "Show your work or reasoning steps for calculations.", "Handle algebra, arithmetic, basic calculus, and other common math queries.", ], model=OpenAIChat(model="gpt-4o-mini"), markdown=True)Agent 4: Email Composer# Agent 4: Email Composeremail_composer_agent = Agent( name="Email Composer", role="Drafts emails for various purposes.", instructions=[ "You are an assistant helping users draft emails.", "Based on the user's request (purpose, recipient, key points), compose a draft email.", "Adopt an appropriate tone (formal, informal, etc.) as needed or specified.", "Include placeholders like '[Your Name]' or '[Recipient Name]' where appropriate.", "Present the draft clearly, often starting with a subject line.", ], model=OpenAIChat(model="gpt-4o-mini"), markdown=True)Agent 5: Personalized Product Recommendations# Agent 5: Personalized Product Recommendationsproduct_recommendation_agent = Agent( name="Product Advisor Agent", role="Personalized recommendation specialist", instructions=[ "Analyze user needs and preferences to determine product requirements", "Research product categories and current market offerings", "Compare options based on features, price, and user reviews", "Provide balanced recommendations with pros and cons", "Explain reasoning behind recommendations", "Suggest alternatives in different price ranges when appropriate" ], tools=[DuckDuckGo()], # Give access to web search model=OpenAIChat(model="gpt-4o-mini"), markdown=True)Step 5: Implementing the Router Agent (The Coordinator)This is the manager agent. It decides which specialist agent should handle your request based on its instructions.# Define the Router Agentrouter_agent = Agent( name="Enhanced Query Router", role="Directs user requests to the correct specialist agent from the new team.", # Instructions tell the router HOW to delegate tasks: instructions=[ "If the query is about the loaded RAG document, route to 'Document QA Agent'.", "Carefully analyze the user's query intent.", # General instruction "If the query involves writing, generating, or explaining Python code, route it to the 'Python Coder Assistant'.", "If the query is a mathematical problem, calculation, or asks for a math concept explanation, route it to the 'Mathematical Assistant'.", "If the query asks to draft or compose an email, route it to the 'Email Composer'.", "If the query is about product recommendations, route it to the 'Product Advisor Agent'.", # Corrected agent name "If the query doesn't fit these categories clearly, use your best judgment or ask for clarification.", ], # The 'team' parameter lists all the agents this router can delegate to: team=[ doc_qa_agent, python_coder_agent, math_assistant_agent, email_composer_agent, product_recommendation_agent # Make sure all defined agents are listed here ], show_tool_calls=True, # Set to True to see which agent the router chooses (useful for debugging!) markdown=True)print("Router Agent created and configured with the team.")instructions: This list is key. The router uses the AI model to interpret these rules and match your query to the best agent.team: This list contains all the specialist agents we defined earlier.show_tool_calls=True: This is very helpful! When we run a query, it will print which sub-agent the router decided to use.Step 6: Testing Your Agentic SystemIt’s time to see Agentic RAG in action! Let’s ask the router_agent different types of questions and see how it responds.Example Query 1:from phi.utils.pprint import pprint_run_response # Ensure this is importedquery_doc = "Can you summarize the main points of the RAG document?"response1 = router_agent.run(query_doc)print(f"\n--- Query (Document): {query_doc} ---")pprint_run_response(response1, markdown=True)Output:Image by AuthorExample Query 2:query_py = "Write a simple Python function to calculate the factorial of a number."response_py = router_agent.run(query_py)print(f"\n--- Query (Python): {query_py} ---")pprint_run_response(response_py, markdown=True)Output:Image by AuthorExample Query 3:query_math = "What is the integral of 2x dx?"response_math = router_agent.run(query_math)print(f"\n--- Query (Math): {query_math} ---")pprint_run_response(response_math, markdown=True)Output:Image by AuthorExample Query 4:query_email = "Draft a short email to my team scheduling a meeting for next Tuesday at 10 AM to discuss the Q3 project plan."response_email = router_agent.run(query_email)print(f"\n--- Query (Email): {query_email} ---")pprint_run_response(response_email, markdown=True)Output:Image by AuthorExample Query 5:query_hist = "Recommend a good laptop for video editing under $1500"response_hist = router_agent.run(query_hist)print(f"\n--- Query (History): {query_hist} ---")pprint_run_response(response_hist, markdown=True)Output:Image by AuthorConclusionAgentic RAG’s AI-driven information retrieval delivers unparalleled flexibility, reasoning, and autonomy. Integrating intelligent agents transcends static workflows, enabling dynamic task orchestration and precise, context-aware responses for complex challenges. Its ability to autonomously refine queries, validate information, and collaborate seamlessly with humans positions it as a cornerstone for applications in research, industry, and beyond.References and ResourcesPaper: A Survey on Agentic Raghttps://docs.phidata.com/more-examples#agentic-raghttps://docs.phidata.com/introduction#multi-agent-orchestrationhttps://python.langchain.com/docs/tutorials/agents/https://python.langchain.com/api_reference/text_splitters/index.htmlhttps://python.langchain.com/api_reference/community/index.htmlWhat is Agentic RAG? Building Multi-Agent Agentic RAG Systems was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.