Agent Frameworks

Haystack for Agentic RAG: Implementing Self-Correcting Retrieval Loops with Tool-Calling Agents

Retrieval-Augmented Generation (RAG) has revolutionized how Large Language Models (LLMs) access external knowledge. However, traditional RAG pipelines often suffer from a critical flaw: if the initial retrieval step fails to find the right document chunk, the LLM has no way to correct the error, leading to hallucinations or irrelevant answers. This is where Agentic RAG comes in.

By treating retrieval as a tool that an agent can invoke, evaluate, and retry, we can build systems that self-correct. Haystack 2.x provides the perfect framework for this, offering a composable architecture that seamlessly integrates LLMs, retrievers, and agents. In this guide, we will explore how to implement a self-correcting retrieval loop using Haystack’s agent capabilities.

Why Traditional RAG Falls Short

In a standard RAG pipeline, the flow is linear: User Query -> Retriever -> LLM -> Response. If the Retriever picks the wrong chunk (e.g., due to semantic ambiguity), the LLM is forced to answer based on poor context. There is no feedback loop. The model cannot say, "That document wasn't helpful, let me search for something more specific."

Agentic RAG introduces a cycle. The LLM acts as an agent that can decide whether to use a tool (the Retriever). If the retrieved context is insufficient, the agent can refine the query and call the tool again. This iterative process significantly improves the accuracy of complex, multi-step questions.

The Haystack Agent Architecture

Haystack 2.x is designed with agents in mind. It uses a Component paradigm where nodes in the pipeline can communicate via state. To build an agentic system, we typically utilize:

  1. Retriever Component: A standard BM25 or Embedding Retriever.
  2. LLM Component: A model capable of function calling (e.g., GPT-4o, Claude 3, or Llama 3 with tool support).
  3. Agent Component: A controller that manages the conversation history and decides when to stop.

While Haystack does not have a single "magic" agent class yet, we can construct a robust agent using ConditionalRouter or custom logic within a Loop structure. For simplicity, let's demonstrate the core logic using a custom function that simulates the agent's decision-making process, which can be integrated into a Haystack Pipeline.

Implementing the Self-Correcting Loop

The key to self-correction is the LLM's ability to critique the retrieved context. We will instruct the LLM to evaluate the context and return a structured response indicating whether more information is needed.

First, let's set up the retriever and LLM components.


import os
from haystack import Document
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
from haystack.components.generators import OpenAIGenerator
from haystack import Pipeline

# 1. Setup Document Store and Retriever
doc_store = InMemoryDocumentStore()
# Add your documents here
doc_store.write_documents([
    Document(content="Haystack is an open-source framework for building LLM applications."),
    Document(content="Python is a popular programming language known for its simplicity."),
    Document(content="RAG allows LLMs to access external knowledge bases.")
])

retriever = InMemoryBM25Retriever(document_store=doc_store)

# 2. Setup LLM with Tool Calling Capability
# Note: Ensure your LLM model supports function calling
llm = OpenAIGenerator(model="gpt-4o", api_key=os.environ["OPENAI_API_KEY"])

To make the LLM act as an agent, we need to define the retrieval function as a tool. In Haystack, we can wrap the retriever in a callable that returns a structured output. However, for a true agentic loop, we often use a ChatGenerator with tools defined via JSON schema.

Let's define a tool schema for the retrieval action:


import json

retrieval_tool_schema = {
    "name": "retrieve_docs",
    "description": "Retrieve relevant documents from the knowledge base based on a query.",
    "parameters": {
        "type": "object",
        "properties": {
            "query": {
                "type": "string",
                "description": "The search query to find relevant documents."
            }
        },
        "required": ["query"]
    }
}

Now, we create a function that executes this tool when called by the agent:


def execute_retrieval(query: str) -> dict:
    """
    Executes the retrieval logic and returns results in a format suitable for LLM context.
    """
    result = retriever.run(query=query, top_k=3)
    documents = result.get("documents", [])
    
    # Format documents as a string for the LLM to read
    context_text = "\n".join([doc.content for doc in documents])
    
    return {
        "status": "success",
        "context": context_text
    }

Next, we set up the Chat Generator with the tool. We will use a system prompt that explicitly instructs the model to self-correct.


from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage, ToolCall

chat_llm = OpenAIChatGenerator(model="gpt-4o", api_key=os.environ["OPENAI_API_KEY"])

system_message = ChatMessage.from_system(
    "You are a helpful assistant with access to a knowledge base. "
    "You have a tool 'retrieve_docs' to find information. "
    "If the retrieved information is insufficient to answer the user's question, "
    "refine your query and call the tool again. "
    "Only provide a final answer when you are confident in the context."
)

Building the Agentic Loop

In a production environment, you would use a dedicated Agent framework or a loop within your pipeline. For this example, we will simulate the loop to show how the interaction works. In Haystack, you can achieve this by creating a SequentialPipeline with conditional branches or by using a custom component that manages the state.

Here is a simplified logic flow that mimics the agentic behavior:


def run_agentic_rag(user_query: str) -> str:
    """
    Simulates an agentic RAG loop with self-correction.
    """
    messages = [
        system_message,
        ChatMessage.from_user(user_query)
    ]
    
    max_iterations = 3
    for _ in range(max_iterations):
        # 1. LLM decides next action
        response = chat_llm.run(messages=messages, tools=[retrieval_tool_schema])
        assistant_message = response.replies[0]
        
        # 2. Check if the LLM wants to call a tool
        if assistant_message.tool_calls:
            # Process the tool call
            for tool_call in assistant_message.tool_calls:
                if tool_call.tool_name == "retrieve_docs":
                    args = tool_call.arguments
                    # Execute the tool
                    tool_result = execute_retrieval(query=args["query"])
                    
                    # Add tool result to messages
                    tool_result_message = ChatMessage.from_tool(
                        tool_call_id=tool_call.tool_call_id,
                        content=json.dumps(tool_result)
                    )
                    messages.append(assistant_message)
                    messages.append(tool_result_message)
                    
                    print(f"Iteration: Called retrieve_docs with query: '{args['query']}'")
                    print(f"Retrieved Context: {tool_result['context'][:100]}...")
            
            # Continue loop to let LLM evaluate context
            continue
        else:
            # 3. No tool call, LLM is providing a final answer
            # Self-correction check: The LLM should have already decided 
            # the context was sufficient.
            print(f"Final Answer Generated.")
            return assistant_message.text
    
    # If max iterations reached without final answer
    return "I could not find sufficient information to answer your question."

Testing the Self-Correction

Let's test this with a query that might initially retrieve suboptimal results if the query is vague. For example, "How does RAG work?" might retrieve general definitions. If the user asks a specific implementation question, the agent should refine the query.


# Example Usage
query = "What is the specific advantage of Haystack over other RAG frameworks?"
result = run_agentic_rag(query)
print(result)

Observe the logs: If the initial retrieval fails to provide specific comparative data, the LLM might refine the query to "Haystack vs LangChain RAG advantages" or similar, demonstrating the self-correcting behavior.

Best Practices and Considerations

  1. Token Efficiency: Each iteration adds to the context window. Keep the retrieved documents concise (use summarization if necessary) to avoid token bloat.
  2. Max Iterations: Always set a hard limit on the number of iterations to prevent infinite loops and control costs.
  3. Tool Feedback: Ensure the tool returns not just the content, but also metadata like "relevance score" or "number of documents found." This helps the LLM judge the quality of the retrieval.
  4. Structured Output: Encourage the LLM to output a structured decision (e.g., {"action": "retrieve", "query": "..."} or {"action": "answer", "text": "..."}) for easier parsing and debugging.

Conclusion

By combining Haystack’s composable architecture with LLM tool-calling capabilities, we can move beyond static RAG pipelines to dynamic, self-correcting agents. This approach allows models to actively seek better information, leading to more accurate and reliable responses. As agent frameworks evolve, integrating these patterns into production applications will become increasingly standard. Start experimenting with Haystack’s agent components and refine your retrieval loops today.

Share: