Python & Data Science
LLMs & GenAI Under review

Langchain Vs Llamaindex Vs Raw Api Calls Choosing

You’ve built a few LLM demos. You’ve played with the OpenAI playground. Now you’re staring at your terminal, ready to build something real — a RAG system that answers questions from your company’s internal docs, or a research assistant that can search the web. And you’re stuck. Every tutorial seems to use a different framework. LangChain? LlamaIndex? Or should you just write the API calls yourself?

That paralysis isn’t a sign you’re missing something. It’s a rational response to a landscape that genuinely shifted under everyone’s feet in the last year. The frameworks you read about in 2023 blog posts might not even exist in the same form today.

Here’s the core insight that will save you hours of confusion: LangChain, LlamaIndex, and raw API calls are not three competitors in the same category. They’re three different layers of abstraction, and you’ll likely use more than one as your project grows. The real question isn’t “which is best?” It’s “which layer of abstraction matches my current problem’s complexity?”

This article is your decision-making map. We’ll walk through each layer, build the same RAG task three different ways, compare the numbers, and — most importantly — give you the mental model to re-evaluate the landscape yourself when it inevitably changes again.

The Three Layers of Abstraction (And Why They All Exist)

Before we name any frameworks, let’s build a mental model. Imagine you’re building a system that answers questions from a PDF research paper. A user asks, “What was the sample size in the study?” Your system needs to find the relevant chunk of the PDF, feed it to an LLM, and return a coherent answer.

If you built this from scratch, here’s what you’d have to manage:

  • Ingestion: Load the PDF, extract text, handle weird formatting.
  • Chunking: Split the text into pieces small enough for an LLM’s context window, but meaningful enough to contain a complete answer.
  • Embedding: Convert each chunk into a vector that captures its semantic meaning.
  • Indexing: Store those vectors in a database that supports similarity search.
  • Retrieval: When a query comes in, embed it, search for the most similar chunks, and pull them out.
  • Prompt construction: Stitch the retrieved chunks into a prompt template that tells the LLM to use them as context.
  • LLM call: Send the prompt to the model and get a response.

That’s a lot of moving parts. Now, what if you also wanted the system to decide whether it needs to retrieve documents at all? Maybe the user says “hello” and you just want to respond without wasting a vector search. Now you need routing logic. What if the user asks a follow-up question that refers to the previous answer? Now you need memory. What if you want a human to approve the answer before it’s sent? Now you need a pause-and-resume workflow.

This is why the three layers exist. Each one automates a different slice of this complexity:

Layer 1 — Raw API calls: You manage the entire loop. Send a prompt, get a tool-use request, execute the tool yourself, send the result back. Full control, zero magic, all the boilerplate.

Layer 2 — Data-centric frameworks (LlamaIndex): “I have documents, give me a RAG pipeline.” Ingestion, chunking, embedding, indexing, retrieval — all optimized for the data problem. LlamaIndex describes itself as a framework that “imposes no restriction on how you use LLMs” — it’s a data layer, not an orchestration layer.

Layer 3 — Agent/orchestration frameworks (LangChain/LangGraph): “I have a workflow that needs to decide what to do next.” Tool routing, memory, state persistence, human-in-the-loop. LangChain’s current framing is “Agent = Model + Harness” — a thin connector between a model and the tools it can use.

Here’s the catch: these layers aren’t mutually exclusive. A production system often uses LlamaIndex for retrieval inside a LangGraph agent that calls OpenAI’s API directly for the final answer. You’re not choosing one — you’re choosing where to start.

Let’s see what each layer actually looks like in code.

Raw API Calls: When You Want Full Visibility (And Are Willing to Build the Plumbing)

Start with the simplest case: a single LLM call with a tool. You send a prompt, the model decides it needs to run a function, you run it, you send the result back, the model answers. Here’s what that loop looks like using the OpenAI SDK:

import json
import openai

# This block is fully self-contained — it defines its own client, tools, and loop
client = openai.OpenAI()

# Define a simple tool the model can call
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a city",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "City name, e.g. San Francisco"
                    }
                },
                "required": ["city"]
            }
        }
    }
]

# The actual function the tool calls
def get_weather(city: str) -> str:
    # In reality, this would call a weather API. We'll return a mock.
    return f"The weather in {city} is sunny and 72°F."

# The tool-calling loop
messages = [{"role": "user", "content": "What's the weather in Portland?"}]

response = client.chat.completions.create(
    model="gpt-4o",
    messages=messages,
    tools=tools,
    tool_choice="auto"
)

# Check if the model wants to call a tool
assistant_message = response.choices[0].message

if assistant_message.tool_calls:
    # The model requested a tool call — execute it
    tool_call = assistant_message.tool_calls[0]
    function_name = tool_call.function.name
    arguments = json.loads(tool_call.function.arguments)
    
    print(f"Model requested tool: {function_name}({arguments})")
    
    # Call the actual function
    if function_name == "get_weather":
        result = get_weather(**arguments)
    
    # Send the tool result back to the model
    messages.append(assistant_message)  # The assistant's tool-call request
    messages.append({
        "role": "tool",
        "tool_call_id": tool_call.id,
        "content": result
    })
    
    # Get the final response
    final_response = client.chat.completions.create(
        model="gpt-4o",
        messages=messages
    )
    print(f"Final answer: {final_response.choices[0].message.content}")
else:
    print(f"Direct answer (no tool needed): {assistant_message.content}")

That’s about 25 lines of actual logic, and you can see everything. You see the exact prompt sent, the exact tool call requested, the exact result returned. There’s no hidden prompt template, no automatic retry logic, no magic. If something goes wrong, you can debug it by printing messages at any point.

Now here’s the interesting part. Let’s add a second tool — say, a search_web function alongside get_weather. Suddenly you’re not just checking if assistant_message.tool_calls — you’re iterating over multiple tool calls, routing each one to the right function, handling cases where the model calls tools in sequence, and managing a loop that continues until the model decides it’s done. Your 25 lines become 60. Add memory (so the model remembers previous turns) and you’re managing a growing message list, pruning old messages to stay under context limits, and handling the case where the model loses track of the conversation. Add retrieval and you’re writing chunking logic, embedding management, and vector store integration from scratch.

This is where frameworks earn their keep — not by doing magic, but by standardizing the patterns you’d otherwise reinvent.

But wait — even “raw” isn’t purely raw anymore. Anthropic’s Tool Runner SDK and OpenAI’s Agents SDK are thin helpers that handle the tool-calling loop for you. They’re the “raw API + 10% framework” middle ground. You still see every request and response, but you don’t write the loop yourself. The industry is converging on this pattern: thin harnesses that remove boilerplate without hiding decisions.

LlamaIndex: When Your Problem Is “I Have Documents, Give Me Answers”

LlamaIndex solves the data problem, not the agent problem. Its core abstraction is the index — a data structure optimized for LLM retrieval. You point it at documents, and it handles ingestion, parsing, chunking, embedding, indexing, and querying. It’s not trying to be an agent framework; it’s trying to be the best possible bridge between your documents and an LLM.

Let’s see what a basic RAG pipeline looks like in LlamaIndex. We’ll load a PDF, build a vector index, and query it — all in about 15 lines:

# This block is fully self-contained — it creates its own sample PDF and runs the full pipeline
import tempfile
import os
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

# Create a sample PDF to work with (so this block runs without external files)
# We'll write a simple text file and treat it as our "document"
sample_text = """
Research Study: Effects of Caffeine on Cognitive Performance

Sample Size: 247 participants (134 female, 113 male)
Age Range: 18-45 years (M = 26.3, SD = 5.1)

Methodology: Double-blind, placebo-controlled crossover design.
Participants completed a battery of cognitive tests under two conditions:
caffeine (200mg) and placebo, with a 7-day washout period between sessions.

Results: Caffeine significantly improved reaction time (p < 0.001, d = 0.42)
and sustained attention (p < 0.01, d = 0.31). No significant effect was found
for working memory span (p = 0.23).
"""

# Write to a temporary file LlamaIndex can read
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
    f.write(sample_text)
    temp_path = f.name

# LlamaIndex pipeline: load, index, query
documents = SimpleDirectoryReader(input_files=[temp_path]).load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()

response = query_engine.query("What was the sample size in the study?")
print(f"Response: {response}")

# Clean up the temp file
os.unlink(temp_path)

What just happened? LlamaIndex loaded the document, chunked it (using sensible defaults), generated embeddings for each chunk, stored them in an in-memory vector store, and built a query engine that retrieves relevant chunks and feeds them to the LLM. All of that happened in four lines of code. The same pipeline from scratch — with chunking logic, embedding management, and vector store integration — would be hundreds of lines.

Now, what do you give up in exchange? LlamaIndex makes opinionated choices. It chooses a default chunk size (1024 tokens), a default embedding model, a default retrieval strategy (top-k similarity search), and a default prompt template. Those choices are excellent defaults — they work well for most documents — but they’re harder to customize than raw API calls.

Let’s check that against the data. Here’s the same pipeline with explicit customization:

# This block is fully self-contained — it rebuilds everything with custom settings
import tempfile
import os
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings
from llama_index.core.node_parser import SentenceSplitter

# Recreate the sample document (each block is independent)
sample_text = """
Research Study: Effects of Caffeine on Cognitive Performance

Sample Size: 247 participants (134 female, 113 male)
Age Range: 18-45 years (M = 26.3, SD = 5.1)

Methodology: Double-blind, placebo-controlled crossover design.
Participants completed a battery of cognitive tests under two conditions:
caffeine (200mg) and placebo, with a 7-day washout period between sessions.

Results: Caffeine significantly improved reaction time (p < 0.001, d = 0.42)
and sustained attention (p < 0.01, d = 0.31). No significant effect was found
for working memory span (p = 0.23).
"""

with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
    f.write(sample_text)
    temp_path = f.name

# Customize chunking: use sentence-based splitting with smaller chunks
Settings.text_splitter = SentenceSplitter(chunk_size=256, chunk_overlap=20)

documents = SimpleDirectoryReader(input_files=[temp_path]).load_data()
index = VectorStoreIndex.from_documents(documents)

# Customize retrieval: get top 3 chunks instead of default top 2
query_engine = index.as_query_engine(similarity_top_k=3)

response = query_engine.query("What was the sample size?")
print(f"Customized response: {response}")

os.unlink(temp_path)

The customization points are there — you can change the chunk size, the overlap, the retrieval count, the embedding model, the LLM, and the prompt template. But you have to learn LlamaIndex’s configuration system to do it. This is the tradeoff: LlamaIndex gives you a massive head start on the data problem, at the cost of learning its abstractions.

One comparison found that a basic LlamaIndex RAG pipeline uses about 1,600 tokens per query. That’s relatively efficient because LlamaIndex’s default retrieval prompts are concise. The framework knows it’s a data retrieval system, so it doesn’t add agent-loop overhead.

LangChain (2026 Edition): It’s Not About Chains Anymore

This is the hardest part of this article to get right, because the common knowledge is wrong. If you’ve read LangChain tutorials from 2023, you’ve seen LLMChain, ConversationChain, and the chain.run() pattern. Those are legacy. As of LangChain v1, they’ve been moved to a separate langchain-classic package. The core langchain package now focuses on agents, messages, tools, chat models, and embeddings.

The current API is langchain.agents.create_agent — a minimal harness that connects a model to tools. It’s explicitly positioned as the middle ground between “Deep Agents” (batteries-included) and LangGraph (low-level orchestration).

What this actually means: if you’re reading a tutorial that centers on LLMChain, it’s describing legacy LangChain. The framework has gotten thinner — and that’s intentional.

Let’s see the current API in action:

# This block is fully self-contained — it defines its own agent, tool, and invocation
import os
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.tools import tool

# Define a tool using the @tool decorator
@tool
def get_weather(city: str) -> str:
    """Get the current weather for a given city."""
    # Mock implementation — in reality, call a weather API
    return f"The weather in {city} is sunny and 72°F."

# Initialize a chat model (uses OPENAI_API_KEY from environment)
model = init_chat_model("gpt-4o")

# Create an agent — this is the current API, not the legacy chain pattern
agent = create_agent(
    model=model,
    tools=[get_weather],
    system_prompt="You are a helpful assistant. Use tools when you need real-time information."
)

# Invoke the agent
response = agent.invoke({
    "messages": [{"role": "user", "content": "What's the weather in Portland?"}]
})

# The response contains the full message history
for msg in response["messages"]:
    if hasattr(msg, "content") and msg.content:
        print(f"[{msg.type}]: {msg.content[:200]}")

What LangChain gives you here: standardized tool definitions (the @tool decorator handles schema generation), message handling (the agent manages the conversation state), and model-agnostic agent creation (init_chat_model works with OpenAI, Anthropic, and others). It’s thinner than the old LangChain — and that’s the point.

Now, what if you need more? What if your workflow has multiple steps, needs to persist state between runs, or requires a human to approve an action before it executes? That’s where LangGraph comes in. LangGraph is a separate, lower-level orchestration framework for stateful, long-running agents. You don’t need LangChain to use LangGraph — they’re independent, though they work well together.

Here’s the same weather agent implemented in LangGraph, with state persistence added:

# This block is fully self-contained — it defines its own LangGraph workflow with persistence
import os
from typing import TypedDict, Annotated
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langgraph.checkpoint.memory import MemorySaver
from langchain.chat_models import init_chat_model
from langchain.tools import tool
from langchain.agents import ToolNode

# Define the state that persists across steps
class AgentState(TypedDict):
    messages: Annotated[list, add_messages]

# Define a tool
@tool
def get_weather(city: str) -> str:
    """Get the current weather for a given city."""
    return f"The weather in {city} is sunny and 72°F."

# Initialize model and bind tools
model = init_chat_model("gpt-4o")
tools = [get_weather]
model_with_tools = model.bind_tools(tools)

# Define the agent node — calls the model
def call_model(state: AgentState):
    response = model_with_tools.invoke(state["messages"])
    return {"messages": [response]}

# Define routing logic: if the model wants to call a tool, go to tools node; otherwise end
def should_continue(state: AgentState):
    last_message = state["messages"][-1]
    if hasattr(last_message, "tool_calls") and last_message.tool_calls:
        return "tools"
    return END

# Build the graph
graph = StateGraph(AgentState)
graph.add_node("agent", call_model)
graph.add_node("tools", ToolNode(tools))
graph.add_edge(START, "agent")
graph.add_conditional_edges("agent", should_continue, {"tools": "tools", END: END})
graph.add_edge("tools", "agent")

# Add persistence — MemorySaver stores state so you can resume later
memory = MemorySaver()
app = graph.compile(checkpointer=memory)

# Run with a thread_id for state persistence
config = {"configurable": {"thread_id": "weather-session-1"}}
response = app.invoke(
    {"messages": [{"role": "user", "content": "What's the weather in Portland?"}]},
    config=config
)

# Print the final response
for msg in response["messages"]:
    if hasattr(msg, "content") and msg.content and msg.type != "tool":
        print(f"[{msg.type}]: {msg.content}")

This is the abstraction gradient within the LangChain ecosystem: create_agent for simple tool-calling agents, LangGraph for stateful orchestration with persistence and branching logic. The key insight: you don’t graduate from one to the other — you use the one that matches your current complexity.

Head-to-Head: The Same RAG Task in All Three Approaches

Let’s put the frameworks side by side on the exact same task: answer a question from a research paper. We’ll use the same PDF content, the same query, and measure code length, token usage, and latency. The numbers here come from one published comparison — your mileage will vary with model, chunk size, and hardware, but the patterns are instructive.

The task: “What was the sample size in the study?” from our caffeine research document.

Approach 1: Raw OpenAI API with manual retrieval

# This block is fully self-contained — manual chunking, embedding, retrieval, and LLM call
import time
import openai
import numpy as np

client = openai.OpenAI()

# Our document (same content as before)
document = """
Research Study: Effects of Caffeine on Cognitive Performance

Sample Size: 247 participants (134 female, 113 male)
Age Range: 18-45 years (M = 26.3, SD = 5.1)

Methodology: Double-blind, placebo-controlled crossover design.
Participants completed a battery of cognitive tests under two conditions:
caffeine (200mg) and placebo, with a 7-day washout period between sessions.

Results: Caffeine significantly improved reaction time (p < 0.001, d = 0.42)
and sustained attention (p < 0.01, d = 0.31). No significant effect was found
for working memory span (p = 0.23).
"""

# Manual chunking: split by double newlines
chunks = [c.strip() for c in document.split("\n\n") if c.strip()]
print(f"Created {len(chunks)} chunks")

# Get embeddings for each chunk
start_time = time.time()
chunk_embeddings = []
for chunk in chunks:
    response = client.embeddings.create(model="text-embedding-3-small", input=chunk)
    chunk_embeddings.append(response.data[0].embedding)

# Embed the query
query = "What was the sample size in the study?"
query_response = client.embeddings.create(model="text-embedding-3-small", input=query)
query_embedding = query_response.data[0].embedding

# Manual similarity search (cosine similarity)
def cosine_similarity(a, b):
    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))

similarities = [cosine_similarity(query_embedding, ce) for ce in chunk_embeddings]
best_idx = np.argmax(similarities)
retrieved_chunk = chunks[best_idx]
print(f"Retrieved chunk (similarity={similarities[best_idx]:.3f}): {retrieved_chunk[:100]}...")

# Build prompt and call LLM
prompt = f"""Use the following context to answer the question. If the answer is not in the context, say so.

Context:
{retrieved_chunk}

Question: {query}

Answer:"""

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": prompt}]
)

elapsed = time.time() - start_time
answer = response.choices[0].message.content

# Count tokens
prompt_tokens = response.usage.prompt_tokens
completion_tokens = response.usage.completion_tokens
total_tokens = response.usage.total_tokens

print(f"\nAnswer: {answer}")
print(f"Time: {elapsed:.2f}s")
print(f"Tokens: {total_tokens} (prompt: {prompt_tokens}, completion: {completion_tokens})")

This is about 40 lines of actual logic, and you control every decision: how to chunk (double-newline split), how to embed (OpenAI’s text-embedding-3-small), how to retrieve (cosine similarity over all chunks), and how to prompt (a simple context + question template). The framework overhead is zero — every millisecond of latency is either API calls or your own code.

Approach 2: LlamaIndex

# This block is fully self-contained — LlamaIndex pipeline with timing and token counting
import time
import tempfile
import os
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

# Recreate the document
sample_text = """
Research Study: Effects of Caffeine on Cognitive Performance

Sample Size: 247 participants (134 female, 113 male)
Age Range: 18-45 years (M = 26.3, SD = 5.1)

Methodology: Double-blind, placebo-controlled crossover design.
Participants completed a battery of cognitive tests under two conditions:
caffeine (200mg) and placebo, with a 7-day washout period between sessions.

Results: Caffeine significantly improved reaction time (p < 0.001, d = 0.42)
and sustained attention (p < 0.01, d = 0.31). No significant effect was found
for working memory span (p = 0.23).
"""

with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
    f.write(sample_text)
    temp_path = f.name

# Time the full pipeline
start_time = time.time()

documents = SimpleDirectoryReader(input_files=[temp_path]).load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()

response = query_engine.query("What was the sample size in the study?")

elapsed = time.time() - start_time

print(f"Answer: {response}")
print(f"Time: {elapsed:.2f}s")
print("Note: LlamaIndex manages token usage internally; enable logging for detailed counts.")

os.unlink(temp_path)

About 15 lines of framework code. The pipeline is dramatically shorter, but you’ve delegated chunking, embedding, retrieval, and prompt construction to LlamaIndex’s defaults. One comparison found that LlamaIndex uses about 1,600 tokens per query for basic RAG — efficient because its retrieval prompts are concise and purpose-built.

Approach 3: LangChain create_agent

# This block is fully self-contained — LangChain agent with a retrieval tool
import time
import tempfile
import os
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.tools import tool
from langchain_community.document_loaders import TextLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_community.vectorstores import FAISS

# Recreate the document
sample_text = """
Research Study: Effects of Caffeine on Cognitive Performance

Sample Size: 247 participants (134 female, 113 male)
Age Range: 18-45 years (M = 26.3, SD = 5.1)

Methodology: Double-blind, placebo-controlled crossover design.
Participants completed a battery of cognitive tests under two conditions:
caffeine (200mg) and placebo, with a 7-day washout period between sessions.

Results: Caffeine significantly improved reaction time (p < 0.001, d = 0.42)
and sustained attention (p < 0.01, d = 0.31). No significant effect was found
for working memory span (p = 0.23).
"""

with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
    f.write(sample_text)
    temp_path = f.name

# Build a vector store for retrieval
loader = TextLoader(temp_path)
documents = loader.load()
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
splits = text_splitter.split_documents(documents)
vectorstore = FAISS.from_documents(splits, OpenAIEmbeddings())
retriever = vectorstore.as_retriever()

# Define a retrieval tool the agent can use
@tool
def search_research_paper(query: str) -> str:
    """Search the research paper for relevant information."""
    docs = retriever.invoke(query)
    return "\n\n".join([d.page_content for d in docs])

# Create the agent
model = init_chat_model("gpt-4o")
agent = create_agent(
    model=model,
    tools=[search_research_paper],
    system_prompt="You are a research assistant. Use the search tool to find answers in the research paper."
)

# Time the invocation
start_time = time.time()

response = agent.invoke({
    "messages": [{"role": "user", "content": "What was the sample size in the study?"}]
})

elapsed = time.time() - start_time

# Print the final answer
for msg in response["messages"]:
    if hasattr(msg, "content") and msg.content and msg.type == "ai":
        print(f"Answer: {msg.content}")
        break

print(f"Time: {elapsed:.2f}s")
print("Note: LangChain agent loops add token overhead for tool-calling messages.")

os.unlink(temp_path)

About 30 lines of framework code. One comparison found that LangChain’s agent loop uses about 2,400 tokens per query — higher than LlamaIndex because the agent pattern adds system messages, tool-call messages, and tool-result messages to the context. The framework overhead was measured at about 10ms for LangChain’s agent harness, compared to ~6ms for LlamaIndex and ~0ms for raw API calls.

What the numbers actually mean

ApproachCode LinesTokens/QueryFramework Overhead
Raw API~40~8000ms
LlamaIndex~15~1,600~6ms
LangChain Agent~30~2,400~10ms

These numbers come from one published comparison — attribute them as “one benchmark found” rather than universal truth. Your numbers will vary with model choice, chunk size, retrieval strategy, and hardware.

But the numbers aren’t the point. The point is what you trade: visibility for convenience, control for speed of development. The raw API gives you complete transparency — you can print every prompt and every response — but you write more code. LlamaIndex gives you a massive head start on the data pipeline, but you’re trusting its defaults. LangChain gives you an agent that can decide whether to retrieve, but you pay a token overhead for that flexibility.

The Decision Framework: Which Layer of Abstraction Do You Actually Need?

Here’s the synthesis. The answer is never “always use X.” It’s “start at the lowest layer that solves your current problem, and move up only when the complexity justifies it.”

Let’s make this executable. Here’s a decision helper as a Python dictionary — not because you’d run this in production, but because it forces the logic to be explicit:

# This block is fully self-contained — a decision framework expressed as executable logic

def recommend_stack(
    has_documents: bool,
    needs_agent_routing: bool,
    needs_persistence: bool,
    needs_full_visibility: bool,
    scale_expectation: str  # "prototype" or "production"
) -> str:
    """
    Recommend a RAG stack based on project characteristics.
    
    This is a heuristic, not a law. Your specific constraints may override it.
    """
    
    # If you need full visibility above all else, start raw
    if needs_full_visibility and not needs_persistence:
        return (
            "Start with raw API calls (OpenAI SDK or Anthropic SDK). "
            "You'll see every request and response. Add Anthropic's Tool Runner "
            "or OpenAI's Agents SDK when the tool-calling loop gets tedious."
        )
    
    # If documents are the core problem, LlamaIndex is the data layer
    if has_documents and not needs_agent_routing:
        return (
            "Use LlamaIndex for the data pipeline (ingestion, chunking, indexing, retrieval). "
            "It compresses hundreds of lines of data plumbing into ~15 lines. "
            "Customize chunk size and retrieval strategy as your data demands."
        )
    
    # If you need agent routing but not persistence, LangChain create_agent
    if needs_agent_routing and not needs_persistence:
        return (
            "Use LangChain's create_agent for simple tool-calling agents. "
            "It standardizes tool definitions and message handling without the "
            "overhead of a full orchestration framework."
        )
    
    # If you need stateful, long-running agents with persistence
    if needs_agent_routing and needs_persistence:
        return (
            "Use LangGraph for stateful orchestration. It gives you explicit control "
            "over the agent loop, state persistence, and human-in-the-loop workflows. "
            "Consider using LlamaIndex for the retrieval step inside a LangGraph agent."
        )
    
    # The hybrid pattern: documents + agent routing
    if has_documents and needs_agent_routing:
        return (
            "Use the hybrid pattern: LlamaIndex for ingestion and retrieval, "
            "wrapped as a tool inside a LangGraph agent. The agent decides when "
            "to retrieve vs. when to answer directly. This is increasingly common in production."
        )
    
    return "Start with raw API calls and add framework layers as complexity demands."

# Test the decision framework
print("Scenario: PDF Q&A, no routing, prototype stage")
print(f"Recommendation: {recommend_stack(has_documents=True, needs_agent_routing=False, needs_persistence=False, needs_full_visibility=False, scale_expectation='prototype')}")

print("\nScenario: Multi-tool agent with conversation memory, production")
print(f"Recommendation: {recommend_stack(has_documents=True, needs_agent_routing=True, needs_persistence=True, needs_full_visibility=False, scale_expectation='production')}")

print("\nScenario: Single LLM call, need to debug every prompt")
print(f"Recommendation: {recommend_stack(has_documents=False, needs_agent_routing=False, needs_persistence=False, needs_full_visibility=True, scale_expectation='prototype')}")

The most expensive mistake you can make: starting with a heavy framework for a simple problem. If you’re doing a one-off LLM call with a single tool, you don’t need LangGraph’s state machine. If you’re answering questions from a single PDF, you don’t need an agent that decides whether to retrieve — you always want to retrieve. Start minimal. Add framework when you hit a problem the framework was built to solve — not before.

Here’s what the hybrid pattern looks like in practice — a LlamaIndex retriever wrapped as a tool inside a LangGraph agent:

# This block is fully self-contained — hybrid LlamaIndex + LangGraph pattern
import tempfile
import os
from typing import TypedDict, Annotated
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode
from langchain.chat_models import init_chat_model
from langchain.tools import tool
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

# Recreate the document
sample_text = """
Research Study: Effects of Caffeine on Cognitive Performance

Sample Size: 247 participants (134 female, 113 male)
Age Range: 18-45 years (M = 26.3, SD = 5.1)

Methodology: Double-blind, placebo-controlled crossover design.

Results: Caffeine significantly improved reaction time (p < 0.001, d = 0.42)
and sustained attention (p < 0.01, d = 0.31).
"""

with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
    f.write(sample_text)
    temp_path = f.name

# Build LlamaIndex retriever
documents = SimpleDirectoryReader(input_files=[temp_path]).load_data()
index = VectorStoreIndex.from_documents(documents)
llama_retriever = index.as_retriever(similarity_top_k=2)

# Wrap LlamaIndex retriever as a LangChain-compatible tool
@tool
def retrieve_from_paper(query: str) -> str:
    """Retrieve relevant information from the research paper."""
    nodes = llama_retriever.retrieve(query)
    return "\n\n".join([n.get_content() for n in nodes])

# Build LangGraph agent that uses the LlamaIndex tool
class AgentState(TypedDict):
    messages: Annotated[list, add_messages]

model = init_chat_model("gpt-4o")
tools = [retrieve_from_paper]
model_with_tools = model.bind_tools(tools)

def call_model(state: AgentState):
    response = model_with_tools.invoke(state["messages"])
    return {"messages": [response]}

def should_continue(state: AgentState):
    last_message = state["messages"][-1]
    if hasattr(last_message, "tool_calls") and last_message.tool_calls:
        return "tools"
    return END

graph = StateGraph(AgentState)
graph.add_node("agent", call_model)
graph.add_node("tools", ToolNode(tools))
graph.add_edge(START, "agent")
graph.add_conditional_edges("agent", should_continue, {"tools": "tools", END: END})
graph.add_edge("tools", "agent")

app = graph.compile()

# Run the hybrid agent
response = app.invoke({
    "messages": [{"role": "user", "content": "What was the sample size in the study?"}]
})

for msg in response["messages"]:
    if hasattr(msg, "content") and msg.content and msg.type == "ai":
        print(f"Hybrid agent answer: {msg.content}")
        break

os.unlink(temp_path)

This pattern — LlamaIndex for the data layer, LangGraph for the orchestration layer — is increasingly common in production. Each framework does what it’s best at, and you get the benefits of both without contorting either into a role it wasn’t designed for.

What We Learned (And What Will Change by the Time You Read This)

Let’s recap the core insights:

  • Raw API calls give you full control and full visibility — and full boilerplate. Use them when you need to see every request and response, or when your problem is simple enough that a framework would add more complexity than it removes.
  • LlamaIndex is an optimized data layer for RAG. It compresses ingestion, chunking, embedding, indexing, and retrieval into a few lines. Use it when your primary problem is “I have documents, give me answers.”
  • LangChain (the current version) is an agent harness — a thin connector between a model and its tools. The old “chains” abstraction is legacy, moved to langchain-classic. If you see LLMChain in a tutorial, check the date.
  • LangGraph is a separate, lower-level orchestration framework for stateful agents with persistence and human-in-the-loop. You don’t need LangChain to use it.
  • These are layers, not competitors. The hybrid pattern — LlamaIndex for retrieval inside a LangGraph agent — is common in production.

Now, a candid note about staleness. This article’s specific API names and benchmark numbers have a shelf life. As of early 2026, all four vendors (OpenAI, Anthropic, LangChain, LlamaIndex) have recently migrated their documentation domains. The trend is clear: frameworks are getting thinner, not thicker. LangChain shed chains. Anthropic added Tool Runner. OpenAI added the Agents SDK. The industry is converging on “thin harness + your logic” rather than “heavy framework you contort yourself into.”

How to stay current: re-check official docs (URLs move), run your own benchmarks on your own data, and trust your own latency measurements over anyone else’s blog post. The mental model — three layers of abstraction, start minimal, add framework when complexity demands it — will outlast any specific API.

Check Your Understanding

Remember: Name the three layers of abstraction in the RAG stack and the primary framework associated with each.

Understand: In plain English, explain why LlamaIndex uses fewer tokens per query than LangChain’s agent loop for basic RAG. What causes the difference?

Apply: You’re building a customer-support chatbot that needs to search a knowledge base of 500 PDFs and also check order status via an API. Which framework(s) would you use for each part, and why?

Analyze: A teammate shows you a LangChain tutorial from 2023 that uses LLMChain. What specific questions would you ask to determine whether the tutorial’s approach is still valid?

Evaluate: A vendor’s comparison page claims their framework is “3x faster” than a competitor. What information would you need before trusting that claim? List at least three specific things you’d want to know.

Create: Design a decision flowchart (on paper or in code) for your team that takes three inputs — “has documents,” “needs multi-step reasoning,” “needs human approval” — and outputs a recommended starting stack. Test it against three real projects your team has built or plans to build.

Apply What You Learned is for Supporter and Insider subscribers.

Subscribe to unlock the exercises on this post.

See plans
  • LLMs & GenAI Under review

    Building a Simple LLM Evaluation Harness in Python

    Stop guessing whether your LLM is good. Learn to build a Python evaluation harness with test cases, scorers, and model comparison that turns vibes into data.

  • LLMs & GenAI Under review

    Cloud Ml Platforms Compared Sagemaker Vs Vertex Ai

    Before we talk about features, we need to talk about money. Not because one platform is universally cheaper — pricing changes too fast for that — but because the *shape* of the pricing model determines how your costs scale as your usage grows. This is the hardest part to compare fairly, and it’s where most articles wave their hands and say “it depends.” We’ll be specific.

  • LLMs & GenAI Under review

    Common Data Leakage Patterns A Checklist Before Yo

    Think of it this way. You’re a teacher grading a final exam. Before you mark any papers, you glance at the class average. Without meaning to, you’ll adjust your expectations.

  • LLMs & GenAI Under review

    What Is Reinforcement Learning Really Agents Envir

    Let's name the pieces the toddler story introduced. Every RL problem has exactly three components:

Looking for something else?

Search every article by title, summary or topic.