🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

LLM Orchestration: LangChain, LlamaIndex and Plain Code

🟢 Free Lesson

LLM Orchestration: LangChain, LlamaIndex and Plain Code

Every non-trivial language model application becomes a pipeline: fetch context, transform it, call a model, validate the output, maybe call another model, and stream something back. Orchestration is the name for how you express that pipeline and how much machinery you borrow to do it. The frameworks available today genuinely accelerate the first week — loaders for every document format, ready-made retrievers, built-in tracing — and equally genuinely become the thing you fight in month six, when a simple prompt change requires understanding three layers of abstraction. This lesson is about choosing deliberately: what orchestration is for, what good structure looks like in plain code, and how to keep the option to swap frameworks rather than inherit one.

What Orchestration Is Actually For

Strip the vocabulary away and orchestration solves five problems: connecting components, managing state between them, handling failure, exposing traces, and keeping prompts and models swappable. Any framework worth adopting must beat your own code at those five, not at hello-world brevity.

ProblemPlain code versionFramework value
Wiring stepsFunctions called in orderVisual chains, conditional edges
Shared stateA dict or dataclass you defineTyped state, checkpointing
Failure handlingTry/except per stepBuilt-in retry and fallback policies
TracingLogging you writeSpans, token counts, UI out of the box
Model swappingYour adapter interfaceDozens of prebuilt integrations
Document loadingParsers you assembleLarge catalogue of loaders and splitters

The honest assessment for most teams: document ingestion and tracing are where frameworks pull ahead, while prompt construction and business logic are where they add friction. Adopting a framework for the loaders while keeping prompts and orchestration logic in your own code is a common and defensible split.

Chains, State and the Shape of a Request

Whatever library you use, the shape of a well-structured pipeline is the same: explicit state flowing through small, named steps that each do one thing. State should be a plain record you can serialize, because every debugging session eventually becomes a question about what the state contained at step three.

python
from dataclasses import dataclass, field, asdict
from typing import Callable

@dataclass
class PipelineState:
    request_id: str
    question: str
    conversation: list = field(default_factory=list)
    documents: list = field(default_factory=list)
    draft: str = ""
    answer: str = ""
    citations: list = field(default_factory=list)
    steps: list = field(default_factory=list)

    def snapshot(self) -> dict:
        return asdict(self)

Step = Callable[[PipelineState], PipelineState]

def run(state: PipelineState, steps: list[tuple[str, Step]],
        tracer=None) -> PipelineState:
    for name, step in steps:
        started = __import__("time").perf_counter()
        try:
            state = step(state) or state
            state.steps.append({"name": name, "ok": True,
                                "ms": round((__import__("time").perf_counter() - started) * 1000, 1)})
        except Exception as exc:
            state.steps.append({"name": name, "ok": False, "error": str(exc)})
            if tracer:
                tracer.record_failure(state.request_id, name, str(exc))
            raise
        if tracer:
            tracer.record(state.request_id, name, state.snapshot())
    return state

def retrieve(state: PipelineState) -> PipelineState:
    state.documents = retriever.search(state.question, k=6)
    state.citations = [{"doc_id": d["id"], "score": d["score"]} for d in state.documents]
    return state

def compose(state: PipelineState) -> PipelineState:
    context = "\n\n".join(d["text"] for d in state.documents)
    state.answer = llm.complete(state.question, context=context)
    return state

final = run(PipelineState(request_id="r-1", question="What changed in the SLA?"),
            [("retrieve", retrieve), ("compose", compose)])
print(final.answer, [s["name"] for s in final.steps])

Two properties make this structure pay off. Steps are independently testable with a hand-built state, so a regression localizes immediately. And the snapshot at each step is a replay artifact — save it, and you can reproduce a user's complaint without re-running the whole pipeline against a corpus that has since changed.

Retries, Fallbacks and Streaming

Model calls fail in three ways, and each deserves different treatment. Rate limits and timeouts are transient: retry with exponential backoff and jitter, capped at a couple of attempts. Malformed structured output is a correctness issue: retry once with the validation error fed back, then fall back to a more constrained prompt or a smaller schema. Provider outages are capacity issues: fail over to a second provider or model family rather than burning your latency budget on retries.

python
import random
import time

class ResilientCaller:
    def __init__(self, chain, max_attempts=3, base_delay=0.5):
        self.chain = chain
        self.max_attempts = max_attempts
        self.base_delay = base_delay

    def _backoff(self, attempt: int) -> float:
        return min(self.base_delay * (2 ** attempt), 8.0) + random.uniform(0, 0.25)

    def complete(self, prompt: str, schema=None, **kwargs):
        last = None
        for provider in self.chain:
            for attempt in range(self.max_attempts):
                try:
                    raw = provider.generate(prompt, **kwargs)
                    if schema is None:
                        return raw
                    parsed = schema.parse(raw)
                    return parsed
                except schema.ValidationError as exc:
                    last = exc
                    prompt = prompt + f"\nPrevious output was invalid: {exc}. Fix it."
                except provider.RateLimit:
                    time.sleep(self._backoff(attempt))
                except provider.Unavailable as exc:
                    last = exc
                    break
        raise RuntimeError(f"all providers exhausted: {last}")

caller = ResilientCaller([primary, backup])

Streaming deserves early attention because it changes perceived performance more than any optimization. Emitting the first token within a few hundred milliseconds makes a two-second answer feel fast; buffering the whole response makes the same answer feel broken. Stream to the client, validate in the background, and be ready to retract — a streamed answer that fails validation mid-flight is the price you accept for the latency win.

Choosing a Framework, or Declining One

The major options occupy different points on the abstraction curve. LangChain offers the broadest integration surface and has matured into a composable set of packages, which means you can take its loaders and expression layer without adopting its agent abstractions. LlamaIndex grew up around retrieval and remains strong at indexing strategies, query engines and document structure. DSPy takes a different angle entirely, treating prompts as optimizable parameters and compiling them against evaluation sets — powerful when you have metrics, awkward when you do not. Haystack and similar pipeline libraries sit closer to explicit graphs of nodes, which reads more like infrastructure code than like model magic.

Decide with a spike rather than a comparison table. Take your real workload — your documents, your latency target, your error handling — and build a thin slice in two options plus plain code. The winner is usually obvious within a day, and the exercise leaves you with interfaces you would have needed anyway.

Watch for three warning signs during the spike. If a small behavior change requires reading framework source, the abstraction is leaking. If your prompts live in library-managed configuration instead of your repository, you have lost versioning. If swapping models means touching many files, the integration layer has become your application.

Tracing Across the Stack

Orchestration without tracing is guessing. A useful trace records, per request: the prompt and its version, the model and its parameters, retrieved documents with scores, token usage and latency for each call, validation outcomes, and the final answer with citations. That record answers the three questions you will actually be asked — why did it say that, why was it slow, why did it cost that much — and it is the raw material for evaluation sets, because production examples with outcomes attached are the best training data you will ever have.

Attach the same trace id across every hop, including calls that cross service boundaries through headers. Keep sampling rates high enough during investigations to catch the rare failure, and reduce them for steady state so storage stays affordable. When a provider degrades, traces distinguish "our prompt broke" from "the model changed underneath us," and that distinction decides whether you ship a fix or wait.

Evolving Without a Rewrite

Applications outlive frameworks. The defense is a small set of interfaces you own: a model adapter that takes a prompt and returns text with usage metadata, a retriever that returns documents with scores, a prompt store that versions templates alongside their evaluation sets, and a trace sink writing to storage you control. Frameworks can power the inside of those interfaces freely, because replacing a framework then becomes an implementation detail rather than a migration.

This also keeps team onboarding sane. New engineers read your four interfaces and the pipeline that calls them; they do not need to internalize a library's class hierarchy before shipping a change. And when a framework's direction stops matching yours, the honest move is to delete it from the internal slots one at a time, keeping the parts that still earn their place — usually loaders and trace exporters — until the rest is gone.

Best Practices

  • Keep prompts as versioned files in your repository, not framework configuration
  • Make pipeline state a serializable record and snapshot it at every step
  • Separate transient failures from validation failures in retry logic
  • Stream to users early while validating in the background
  • Own four thin interfaces — model, retriever, prompts, traces — and let frameworks sit behind them

Key Takeaways

  • Orchestration exists for wiring, state, failure, tracing and swappability
  • Spikes on your real workload beat feature-matrix comparisons every time
  • Structured retries: backoff for transient errors, feedback for validation, failover for outages
  • Traces with prompt and model versions are what make regressions diagnosable
  • Interfaces you own are what make a future framework swap cheap
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-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement