🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

LangChain vs LlamaIndex vs DSPy: Choosing an Orchestrator

Advanced LLMOpsLLM Orchestration FrameworksđŸŸĸ Free Lesson

Orchestration frameworks promise to turn scattered API calls into maintainable applications: typed chains instead of ad-hoc string concatenation, managed retrieval instead of hand-rolled vector search, compiled prompts instead of prompt files multiplied by hope. They deliver on that promise often enough to be worth learning — and they add abstraction layers that have burned enough production teams that knowing when to skip them is equally important.

This lesson looks at what the three most influential frameworks actually provide under the hood: LangChain-style chains and composition, LlamaIndex-style retrieval pipelines, and DSPy-style programmatic prompt optimization. Understanding the mechanisms, not just the marketing, is what lets you pick the right tool — or write the forty lines of glue that replace it.

What an orchestration layer buys you

At minimum, a framework gives you four things: composable steps with a shared state dictionary, adapters for model providers so switching vendors is a config change, memory and retrieval primitives, and a tracing story for debugging multi-step calls. For prototypes, those conveniences collapse weeks into days. For production, the same conveniences can hide the exact behavior you need to control — retry semantics, streaming boundaries, token accounting, and error propagation.

The honest engineering framing is that frameworks are highest leverage when your application genuinely resembles the framework's native abstraction: a retrieval-heavy question-answering system looks like LlamaIndex, a tool-using agent looks like LangChain, a prompt pipeline with a measurable metric looks like DSPy. When your application does not resemble the abstraction, you spend more time fighting the framework than you saved, and plain SDK calls win.

ConcernRaw SDKLangChain-styleLlamaIndex-styleDSPy-style
Time to first prototypeSlowFastFastest for RAGSlow
DebuggabilityExcellentModerateModerateCompile-time oriented
Provider portabilityManualBuilt inBuilt inBuilt in
Prompt iterationCopy-pastePrompt templatesNode postprocessorsDeclared, compiled
Lock-in riskNoneModerateModerateHigh
Production overheadLowestModerateModerateHighest

Chain composition: the LangChain idea, from first principles

The core LangChain abstraction is a chain: an ordered sequence of steps, each taking a named input from a shared state dictionary and writing a named output back. Prompt templates fill variables, the model call emits text, and output parsers turn prose into structured data. Agents are chains that loop — the model's output decides which step runs next — and tools are just callable steps exposed to the model via schemas.

python
import json
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List


@dataclass
class Step:
    name: str
    fn: Callable[[Dict[str, Any]], Any]
    reads: str
    writes: str


class Chain:
    def __init__(self, name: str):
        self.name = name
        self.steps: List[Step] = []
        self.memory: Dict[str, Any] = {}

    def add(self, name: str, fn: Callable, reads: str, writes: str) -> "Chain":
        self.steps.append(Step(name, fn, reads, writes))
        return self

    def run(self, inputs: Dict[str, Any]) -> Dict[str, Any]:
        state = {**self.memory, **inputs}
        for step in self.steps:
            try:
                state[step.writes] = step.fn(state[step.reads])
            except Exception as exc:
                state["error"] = f"{step.name}: {type(exc).__name__}: {exc}"
                state["failed_step"] = step.name
                break
        return state


class PromptTemplate:
    def __init__(self, template: str, variables: List[str]):
        self.template = template
        self.variables = variables

    def render(self, **kwargs) -> str:
        missing = [v for v in self.variables if v not in kwargs]
        if missing:
            raise KeyError(f"missing template variables: {missing}")
        out = self.template
        for key, value in kwargs.items():
            out = out.replace("{" + key + "}", str(value))
        return out


class OutputParser:
    @staticmethod
    def as_json(text: str) -> Dict[str, Any]:
        start, end = text.find("{"), text.rfind("}")
        if start == -1 or end == -1:
            return {"_parse_error": True, "raw": text[:200]}
        try:
            return json.loads(text[start:end + 1])
        except json.JSONDecodeError:
            return {"_parse_error": True, "raw": text[:200]}

    @staticmethod
    def as_list(text: str) -> List[str]:
        lines = [ln.strip(" -*0123456789.").strip()
                 for ln in text.strip().splitlines()]
        return [ln for ln in lines if ln]


qa_chain = (Chain("document-qa")
            .add("retrieve", lambda q: [f"passage about {q}"], "question", "docs")
            .add("compose", lambda docs: f"Context: {'; '.join(docs)}", "docs", "prompt")
            .add("generate", lambda p: f"Answer based on: {p}", "prompt", "answer"))
print(qa_chain.run({"question": "How does sharding reduce memory?"})["answer"])

Writing a minimal chain yourself takes an afternoon and teaches you exactly where the real framework earns its keep: provider fallbacks, async execution, streaming, and community integrations. It also shows where the abstraction gets leaky — chains that need branching, cycles, or partial retries outgrow the linear model quickly, which is why modern agent frameworks moved to graph-based execution.

Retrieval pipelines: the LlamaIndex model

LlamaIndex's contribution was treating document ingestion and query handling as a single pipeline with explicit stages: load, split, embed, index, retrieve, then synthesize. Each stage is replaceable, which matters in production because ingestion quality dominates answer quality. A well-tuned retrieve step with reranking routinely beats a bigger model with sloppy retrieval.

python
import math
from dataclasses import dataclass, field
from typing import Dict, List, Optional


@dataclass
class Doc:
    text: str
    metadata: Dict[str, str] = field(default_factory=dict)
    vector: Optional[List[float]] = None


class MiniIndex:
    def __init__(self, embedder):
        self.embed = embedder
        self.docs: List[Doc] = []

    def insert(self, chunks: List[str],
               metadata: Optional[Dict[str, str]] = None) -> None:
        for chunk in chunks:
            doc = Doc(text=chunk, metadata=metadata or {})
            doc.vector = self.embed(chunk)
            self.docs.append(doc)

    @staticmethod
    def _cosine(a: List[float], b: List[float]) -> float:
        dot = sum(x * y for x, y in zip(a, b))
        na = math.sqrt(sum(x * x for x in a))
        nb = math.sqrt(sum(y * y for y in b))
        return dot / (na * nb) if na and nb else 0.0

    def search(self, query: str, top_k: int = 4,
               filter_fn=None) -> List[Dict[str, object]]:
        qv = self.embed(query)
        candidates = [d for d in self.docs if filter_fn is None or filter_fn(d)]
        scored = sorted(
            ((self._cosine(qv, d.vector), d) for d in candidates),
            key=lambda pair: pair[0], reverse=True,
        )
        return [{"score": round(score, 4), "text": doc.text,
                 "metadata": doc.metadata} for score, doc in scored[:top_k]]


class QueryEngine:
    def __init__(self, index: MiniIndex, llm):
        self.index = index
        self.llm = llm

    def query(self, question: str, top_k: int = 4) -> str:
        hits = self.index.search(question, top_k=top_k)
        context = "\n---\n".join(h["text"] for h in hits)
        return self.llm(
            "Answer only from context.\n\nContext:\n"
            f"{context}\n\nQuestion: {question}"
        )

The parts people skip and later regret: chunk sizing with overlap tuned to your content, metadata filters that carry source and freshness, and a reranker that reorders the top retriever hits with a stronger cross-encoder. In production, index freshness is an operations problem — a stale index is worse than no index because answers look authoritative.

Programmatic prompting: the DSPy bet

DSPy's premise is that hand-tuned prompt strings do not scale, and that prompts should be declared as typed modules with signatures — inputs, outputs, instructions — and then compiled against a metric, much like a model is trained. The compiler generates few-shot demonstrations, searches prompt variations, and optimizes traces, replacing manual prompt iteration with an automated loop.

python
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List


@dataclass
class Signature:
    inputs: List[str]
    outputs: List[str]
    instruction: str


class Module:
    def __init__(self, signature: Signature):
        self.signature = signature
        self.demonstrations: List[Dict[str, Any]] = []

    def format_prompt(self, inputs: Dict[str, Any]) -> str:
        parts = [self.signature.instruction, ""]
        for demo in self.demonstrations[:3]:
            parts.append("Example input: " + str(demo.get("input")))
            parts.append("Example output: " + str(demo.get("output")))
            parts.append("")
        for key, value in inputs.items():
            parts.append(f"{key}: {value}")
        return "\n".join(parts)

    def compile(self, trainset: List[Dict[str, Any]],
                metric: Callable[[Dict, Dict], float]) -> float:
        best_score, best_demo = -1.0, None
        for candidate in trainset:
            self.demonstrations = [candidate]
            score = sum(
                metric(candidate, candidate) for _ in range(1)
            ) / max(len(trainset), 1)
            if score > best_score:
                best_score, best_demo = score, candidate
        if best_demo:
            self.demonstrations = [best_demo]
        return best_score


signature = Signature(
    inputs=["context", "question"],
    outputs=["answer"],
    instruction="Answer the question using only the context.",
)
module = Module(signature)
final = module.compile(
    trainset=[{"input": "ctx+q", "output": "a"}, {"input": "ctx+q2", "output": "b2"}],
    metric=lambda ex, pred: 1.0,
)
print(f"compiled with score {final:.2f} and "
      f"{len(module.demonstrations)} demonstration(s)")

The real DSPy compiler is far richer — it searches over demonstrations and instructions with backpropagation through the prompt structure — but the shape is the same: declare the program, define the metric, compile. This pays off when you have a few hundred evaluation examples and find yourself editing prompts weekly; it does not pay off for a single-purpose feature with one prompt that never changes.

Tracing, streaming, and the production layer frameworks add

The abstractions above get you a working application; the production layer is where frameworks either justify their footprint or become dead weight. Tracing is the first requirement: multi-step chains fail in the middle, and without per-step records of inputs, outputs, token counts, and latency you are reduced to printf debugging against a live model. Most frameworks now ship callbacks or middleware that emit structured spans, but the teams that stay debuggable wire those spans into their existing observability stack rather than relying on a separate vendor UI nobody checks during incidents.

Streaming is the second requirement, and it interacts badly with naive chain design. If each step waits for the previous step's complete output, the user stares at a spinner while three sequential model calls finish. Token-level streaming needs the chain to propagate partial results through to the response writer, and streaming through an output parser means parsers must accept incomplete input and emit results incrementally. Frameworks that handle this well are worth their abstraction tax for chat products; frameworks that do not will push you back toward hand-rolled streaming eventually. Token accounting is the third requirement: aggregate cost per request across every step, attribute it to a feature and a customer, and alert on regressions. A chain that quietly doubles its model calls in a minor version should show up on a cost dashboard before it shows up on an invoice.

Choosing, and escaping gracefully

Pick by dominant workload. Retrieval-heavy knowledge assistants get the most from LlamaIndex. Tool-using agents and multi-step workflows get the most from LangChain. Teams with real evaluation sets chasing incremental prompt quality get the most from DSPy. Many production systems use one or two of these for specific subsystems while keeping the model client itself as a thin internal wrapper.

The escape hatch matters as much as the choice. Wrap framework objects behind your own interfaces, keep prompts and schemas in versioned files you control, and make sure removing the framework later means swapping one adapter, not rewriting application logic. Teams that treat frameworks as replaceable infrastructure keep the velocity benefits without the lock-in tax.

Common Mistakes

Adopting a full framework for a single model call with one prompt

Fix: Plain SDK calls with a small internal wrapper are simpler, faster, and trivially debuggable.

Letting framework defaults define production behavior silently

Fix: Pin retry, timeout, and parsing behavior explicitly; defaults change between major versions.

Skipping ingestion quality work because LlamaIndex indexes documents in three lines

Fix: Chunking, metadata, and freshness dominate answer quality; invest there, not in more abstraction.

Treating compiled DSPy prompts as immutable artifacts

Fix: Re-compile and re-evaluate on a schedule; data drift invalidates compiled prompts as surely as model drift.

Spreading framework imports across every module

Fix: Confine them to adapter layers so a migration is a bounded refactor, not a rewrite.

Best Practices

  • Benchmark framework overhead against a raw SDK baseline early; the gap is measurable and sometimes surprising.
  • Keep provider-agnostic interfaces for chat, embedding, and retrieval so model or vendor swaps stay cheap.
  • Version prompts and tool schemas in git, not in database rows, to keep review and rollback ordinary.
  • Trace every chain step with one correlation ID; framework-level tracing alone rarely ties into your existing observability.
  • Write contract tests around parsers and retrieval quality, since those are where framework abstractions leak first.

Key Takeaways

  • Orchestration frameworks earn their keep when your app matches their native abstraction: chains for agents, retrieval pipelines for RAG, compiled modules for prompt iteration.
  • Chains are shared-state step sequences; agents are chains that loop, and tools are schema-exposed steps.
  • Retrieval quality — chunking, metadata, reranking, freshness — matters far more than the index library you chose.
  • DSPy-style compilation replaces manual prompt tuning with metric-driven search, and pays off only when you have real evaluation data.
  • Confine frameworks to adapter layers with versioned prompts and schemas, so lock-in stays a configuration problem instead of a rewrite.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert AI Ops & LLM Ops Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement