You’ve built a RAG system. You’ve evaluated it, and your retrieval metrics are stellar: Context Precision is 0.92, Context Recall is 0.88. The vector database is successfully fetching the exact right documents (strong top-k). Yet, your end-users are still complaining. The final answers are hallucinated, overly verbose, or fail to answer the specific question.
Welcome to the Generation Bottleneck.
When retrieval is strong but generation is weak, the problem isn't your vector database; it’s how the LLM processes, reasons over, and synthesizes the retrieved context. In this end-to-end guide, we will diagnose this exact paradox and solve it using LangGraph. We will build a self-correcting RAG pipeline using a real-world enterprise use case.
The Real-World Use Case: Live CloudOps Incident Resolution
The Scenario: You are building an AI assistant for a DevOps team.
The User Query: "The payment-gateway pod in the us-east-1 cluster is throwing OOM (Out of Memory) kills. Based on our post-mortems, what was the root cause of the similar incident last month, and what is the exact kubectl command to apply the memory limit fix?"
The Basic RAG Failure:
Your retriever perfectly fetches the 3 relevant Jira tickets and Confluence post-mortems from last month. However, the basic RAG pipeline just dumps these documents into a prompt and asks the LLM to "answer the question."
The Result: The LLM suffers from the "lost in the middle" phenomenon. It writes a generic summary of the post-mortems but fails to provide the exact
kubectlcommand, or it hallucinates a command because it got confused by the lengthy context.
The Fix: We need the LLM to not just generate an answer, but to evaluate its own answer against the user's specific constraints (e.g., "Did I actually provide the exact kubectl command?"). If it failed, it needs to try again. This requires cyclic state management, which is exactly what LangGraph is built for.
The Architecture: A Self-Correcting LangGraph RAG
Instead of a linear pipeline (Retrieve -> Generate -> Output), we will build a graph with a Reflection Loop.
Retrieve: Fetch the top-k documents (we assume this is already working well).
Generate: The LLM drafts an initial answer.
Reflect (The Critic): A separate LLM call evaluates the draft. Is it grounded in the docs? Did it answer all parts of the prompt?
Route: If the answer is perfect, output it. If it's flawed, pass the critique back to the Generator.
Revise: The LLM rewrites the answer using the critique.

Step-by-Step Implementation
Prerequisites
pip install langgraph langchain-openai langchain-core pydanticStep 1: Define the State and Pydantic Models
In LangGraph, the State is the single source of truth that flows through your nodes. We will also use Pydantic to force the "Critic" LLM to output structured data.
from typing import TypedDict, List, Annotated
from langchain_core.documents import Document
from langchain_core.messages import HumanMessage, AIMessage, BaseMessage
import operator
# 1. Define the Graph State
class AgentState(TypedDict):
query: str
documents: List[Document]
messages: Annotated[List[BaseMessage], operator.add]
critique: str
iterations: int
# 2. Pydantic model for the Critic's structured output
from pydantic import BaseModel, Field
class Critique(BaseModel):
is_grounding_correct: bool = Field(description="Is the answer strictly based on the provided documents?")
is_complete: bool = Field(description="Did the answer address ALL parts of the user's query?")
feedback: str = Field(description="Specific, actionable feedback on what is missing or wrong.")
is_acceptable: bool = Field(description="Overall pass/fail for the answer.")Step 2: Build the Nodes
Now we define the functions that will act as nodes in our graph.
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
llm = ChatOpenAI(model="gpt-4o", temperature=0)
# --- NODE 1: GENERATE ---
def generate_answer(state: AgentState):
query = state["query"]
docs = state["documents"]
context = "\n\n".join([doc.page_content for doc in docs])
prompt = ChatPromptTemplate.from_template(
"""You are an expert DevOps engineer. Answer the user's query using ONLY the provided context.
Context:
{context}
Query: {query}
{critique_section}
"""
)
# If there is a critique from a previous iteration, include it
critique_section = ""
if state.get("critique"):
critique_section = f"CRITIQUE OF PREVIOUS ATTEMPT:\n{state['critique']}\nPlease fix these issues in your new answer."
chain = prompt | llm
response = chain.invoke({
"context": context,
"query": query,
"critique_section": critique_section
})
# Update iterations
iterations = state.get("iterations", 0) + 1
return {
"messages": [response],
"iterations": iterations
}
# --- NODE 2: REFLECT (CRITIC) ---
def reflect_answer(state: AgentState):
query = state["query"]
docs = state["documents"]
context = "\n\n".join([doc.page_content for doc in docs])
last_message = state["messages"][-1].content
prompt = ChatPromptTemplate.from_template(
"""You are a strict QA engineer reviewing a DevOps assistant's answer.
Context provided to the assistant:
{context}
User Query:
{query}
Assistant's Draft Answer:
{answer}
Evaluate the draft. Check if it is grounded in the context and if it fully answers the query.
"""
)
# Use structured output to force the LLM to use the Pydantic model
structured_llm = llm.with_structured_output(Critique)
chain = prompt | structured_llm
critique_obj = chain.invoke({
"context": context,
"query": query,
"answer": last_message
})
# Format the critique for the next generation step
critique_text = f"Grounding: {'Pass' if critique_obj.is_grounding_correct else 'Fail'}\n"
critique_text += f"Completeness: {'Pass' if critique_obj.is_complete else 'Fail'}\n"
critique_text += f"Feedback: {critique_obj.feedback}"
return {
"critique": critique_text,
"messages": [AIMessage(content=f"[Internal Critique]: {critique_text}")]
}



Join the conversation! Your thoughts help the community grow.