Retrieval-Augmented Generation Implementation in LangChain and LlamaIndex
LlamaIndex excels at retrieval quality while LangGraph controls complex, stateful workflows.

Retrieval-augmented generation implementation in LangChain and LlamaIndex comes down to finding the bottleneck. In 2026, both frameworks cover retrieval and orchestration, but their defaults still differ. LlamaIndex favors ingestion quality and retrieval depth. LangGraph favors stateful agent control. The right architecture puts each where it solves a real problem, rather than adding a framework before the pipeline needs it.
Why RAG has become the default architecture for production LLM applications
Organizational knowledge changes faster than model training can reasonably follow. RAG addresses that gap by fetching current, access-controlled documents at inference time and supplying them as context for generation. For knowledge customization, that offers a faster path to production and lower compute cost than equivalent fine-tuning approaches. It also reduces hallucinations when the retrieved evidence supports the answer. The model still needs useful evidence to work with.
That condition separates a demonstration from a production system. Retrieval can get worse, latency can jump when the load is high, and answers can still sound sure even when the evidence is weak. Without tracing, engineers cannot see how the system came up with a response. Without evaluation, they cannot reliably detect regressions. Framework selection therefore needs to answer concrete questions about retrieval, latency, failure handling, observability, and testing, rather than how quickly a tutorial produces its first answer.
How the LangChain-vs-LlamaIndex framing has become misleading
The familiar split assigns orchestration to LangChain and data to LlamaIndex. That describes their origins better than their current scope. Since 2025, both have taken on more of what the other does, so it is less useful to compare them as a strict either-or choice. The distinction has narrowed, but not disappeared. Their centers of gravity still shape how much engineering each task requires.
LangChain now recommends LangGraph for production agent systems, with explicit state graphs in place of the original chains-and-agents approach. LangChain’s official forum announced the coordinated LangChain 1.0 and LangGraph 1.0 launches on October 22, 2025. Those releases provide a reference point for this comparison. Meanwhile, LlamaIndex Workflows adds async-first, event-driven orchestration with state management to its retrieval core. Both can now support multi-step applications, so capability alone no longer settles the decision.
What the two frameworks are actually optimized for in 2026
LlamaIndex puts most of its engineering work into making sure the system can get the data it needs. Its ingestion ecosystem supports over 160 file formats, with LlamaParse providing the native path for complex documents. Hierarchical chunking preserves relationships among sections, paragraphs, and tables rather than treating documents as undifferentiated text. That changes what reaches the model. LangChain’s default splitters need custom code to reach equivalent structural awareness.
The query engine abstraction then gives retrieval, re-ranking, and response synthesis the same interface. Together with LlamaIndex’s indexing and embedding components, it reduces the wiring needed for a baseline production pipeline. Its advantage is strongest when engineers spend their time repairing document extraction or tuning retrieval precision. Workflows can coordinate multi-step execution too. However, its stateless default differs from LangGraph’s built-in state graph model, even though workflows can maintain state across steps.
LangGraph starts from a different constraint, namely controlling execution. Its nodes are Python functions, and its edges show how it moves through an explicit state schema. Persistent checkpoints, human review, and time-travel debugging support tasks that must pause, branch, or resume. LangSmith adds tightly integrated tracing, evaluation, and monitoring. The trade-off is deeper abstraction, noticeable import overhead, and an API history that can leave tutorial code stale.
If documents lose meaning before retrieval, LlamaIndex addresses the constraint directly. If the system retrieves well but cannot coordinate approvals, retries, and policy branches, LangGraph is the stronger fit. Neither advantage excludes the other framework. It identifies which set of defaults will save the most work.
Building the ingestion and retrieval layer with LlamaIndex
When retrieval quality is weak, ingestion sets the practical limit. When a parser loses the structure of a table, the retriever gets only part of the evidence, whatever generation model is used. LlamaParse handles complex PDFs, tables, mixed media, and long policy documents. Chunking then shapes how much of that extracted context stays together. Splitting only by character count can separate a table header from its rows or fragment the section needed to support a citation.
An illustrative ingestion path is to parse documents with LlamaParse, split them into structure-aware nodes, embed those nodes, build the index, and expose a query engine. Each stage has a separate job to do. Nodes have metadata such as source, date, and access level so retrieval can filter what goes to generation. Hierarchical indices support paragraph-, section-, and document-level queries without re-indexing. Hybrid search and a re-ranker then improve which candidate passages reach response synthesis.
The query engine is also the handoff to orchestration. It can be exported as a callable tool rather than replaced when the application grows more complex. That preserves the retrieval work already done. There is a planning consideration for long-term dependence, however. LlamaIndex’s GitHub README says the company now puts most of its effort into its commercial parsing platform, so teams that rely heavily on the open-source library should watch how well it is maintained over time.
Building the orchestration layer with LangGraph
LangGraph is useful when execution needs to branch, pause for approval, or resume after a failure. A state schema defined as a TypedDict describes the information nodes read and update, while conditional or unconditional edges determine what runs next. The graph compiles into a runtime with support for persistence, checkpointing, and streaming. A paused task can expose its current state and resume after explicit approval.
The minimal RAG pattern uses a StateGraph with retrieve and generate nodes. The retrieve node calls a retriever and writes context into state. The generate node reads that context and the messages, then writes the answer. Edges connect the nodes before compilation and invocation with a message payload. The retriever can be a callable wrapper around a LlamaIndex query engine that returns documents, keeping the graph independent of retrieval internals.
LangSmith provides the visibility needed to inspect this execution. It traces model calls, tool invocations, and node execution while tracking latency, token usage, and cost. Saved trace datasets also support regression tests. LlamaIndex offers native OpenTelemetry-based observability and integrations with Langfuse and Arize Phoenix, so visibility is not exclusive to LangGraph. The distinction is how tightly the control runtime and evaluation tools fit together.
That control has a cost in agentic systems. Typical agentic RAG query latency in 2026 deployments runs from 2 to 10 seconds, while non-deterministic loops are harder to reproduce and debug. Stable factual lookups often get the same answer from a well-tuned non-agentic pipeline at much lower cost. A complex retrieval task alone is not enough reason to use an agent.
The hybrid stack: LlamaIndex for retrieval, LangGraph for orchestration
LlamaParse handles parsing, and LlamaIndex manages hierarchical indexing, hybrid search, and re-ranking. LangGraph controls multi-step execution, approval gates, branches, and resumable checkpoints. LangSmith traces execution and supports evaluation against saved datasets. Each layer answers a different production requirement.
The integration seam is a LangChain-compatible tool wrapping the LlamaIndex query engine. LangGraph calls it as a tool node without needing to know how documents were parsed or ranked. Retrieval and control remain separate concerns. This is a direct fit for applications that need both reliable evidence and stateful execution.
Haystack from deepset is another fit when staging, built-in evaluation, and commercial support dominate the work. Its modular pipelines and first-class evaluation serve that deployment constraint, although its ecosystem is smaller than LangChain’s. For RAG-only applications, its pipeline learning curve is also steeper than LlamaIndex’s. The choice shifts because the bottleneck shifts.
At the simpler end, no framework may be necessary. A single-corpus application using one provider and standard chunking can often use a provider SDK plus a vector database client in under 50 lines of code. OpenAI and Anthropic SDKs provide native tool use, streaming tool calls, and prompt caching. For that situation, a framework can add abstraction and API churn without solving an unmet need.
Advanced retrieval techniques that matter regardless of framework choice
Sparse BM25 retrieval catches exact terminology that dense vectors can miss, while dense retrieval finds semantic similarity that keyword search can miss. A re-ranker then improves the ordering of retrieved candidates. Both headline frameworks support this pattern and re-rankers including Cohere Rerank 3.5, Jina Reranker v2, Voyage Rerank 2, and Sentence Transformers models. LlamaIndex generally requires less custom wiring to assemble them.
Query decomposition breaks a question into sub-queries, retrieves evidence for each, and synthesizes the results. LangGraph can make those retrieval steps traceable nodes. Microsoft’s GraphRAG research showed that the same model was more accurate at multi-hop reasoning when it was grounded in a knowledge graph. That supports a distinct architectural option.
Graph extraction takes roughly three to five times more LLM calls than standard ingestion, and how accurate entity recognition is depends on how specialized the domain is. That cost is easier to justify for large corpora with many relationships when multi-hop reasoning is the main task. Flat document Q&A rarely needs that machinery. Both frameworks can build a knowledge graph, so a need for GraphRAG does little to help teams choose between them.
Metadata filtering should restrict retrieval to documents the requesting user can see, while temporal filtering prevents stale policies or prices from outranking current material. Prompt instructions are not a substitute for that boundary. The knowledge base also needs an explicit threat model. Vector index poisoning, including HNSW poisoning, can change what retrieval finds by adding malicious content to the index.
Evaluation as a production requirement, not an afterthought
A pipeline can keep giving answers that read well even as retrieval gets worse. Corpus updates, chunking changes, and embedding model changes can all degrade quality without producing an obvious runtime failure. A successful request is not evidence of a correct answer. Evaluation needs to measure retrieval and generation on their own so engineers can find where the regression is.
Retrieval metrics include hit rate at top-k, recall, and mean reciprocal rank. They test whether the right evidence is found. Answer faithfulness tests whether the response sticks to that evidence, while answer relevance tests whether it answers the question. Citation accuracy checks whether the sources an answer cites were among those retrieved. These measurements answer different questions and should not be treated as interchangeable.
RAGAS computes faithfulness, answer relevance, context precision, and context recall from the query, context, and response. Galileo has a hosted service for evaluation and monitoring that uses RAG-specific metrics. LangSmith connects graph traces to saved evaluation datasets, while LlamaIndex’s core package includes response and retrieval evaluators. Haystack builds evaluation into its pipelines.
Evaluation should run as CI. It should run before launch and on every corpus update, chunking change, embedding model change, and prompt change. A drop of a few points in retrieval hit rate can signal an ingestion regression. Without that loop, users are left to find what has gone wrong.
What the framework decision looks like in practice: a decision framework by use case
Start with the constraint, then ask what execution must do autonomously. If the application answers questions over messy PDFs, tables, and policies, ingestion quality is likely the first problem to solve. LlamaIndex with LlamaParse, hierarchical chunking, hybrid search, and a re-ranker fits that situation. LangSmith or Langfuse can provide observability. Add LangGraph only when execution must branch, pause, or resume.
If the application already needs multi-step agents and human approval, stateful control is the constraint. LangGraph with LangSmith fits that requirement, with a LlamaIndex query engine exposed as a retrieval tool. If staging, evaluation evidence, compliance documentation, and support contracts dominate instead, Haystack deserves consideration. Its commercial support and built-in evaluation address that different workload. Teams coming from LangChain tutorials must weigh the smaller ecosystem and learning curve.
If the application is simple single-corpus Q&A, a provider SDK and vector database client may be sufficient. Complexity is a cost. Retrieval problems, insufficient governance, and missing evaluation can stop deployment regardless of the framework chosen. Adding orchestration does not repair those foundations. Get ingestion and retrieval right first, then add stateful control only when the workflow demands it.


