Chapter 6: Frameworks, Scaffolding, and Durable Execution — DSPy vs. LangGraph & Temporal
Agent frameworks solve fundamentally different layers of the stack. Choosing the wrong abstraction incurs the 'Harness Tax'—hidden prompt bloat, debugging opacity, and rigid scaffolding that breaks as foundation models evolve. DSPy treats LLM pipelines as declarative computational graphs whose instructions and demonstrations are automatically compiled against a metric; LangGraph models explicit cyclic state machines with checkpointers and human-in-the-loop interrupts; and Temporal provides durable event-sourced execution so long-horizon agent workflows survive crashes, timeouts, and retries without duplicating side effects.
The Agent Scaffolding Spectrum & “The Harness Tax”
Every production agent needs infrastructure around the LLM: prompt formatting, structured output validation, tool dispatch, retries, state persistence, and tracing. A central engineering debate in CS329Z is how thick that harness should be—ranging from a 100-line raw while loop directly over a provider SDK to full-featured orchestration frameworks.
Understanding the Harness Tax
Many agent frameworks were designed around limitations of earlier models (2023-era instruction drift, weak JSON adherence, short context windows) and baked elaborate implicit prompts, hidden retry chains, and rigid state wrappers inside library internals. Adopting a heavy framework blindly incurs The Harness Tax:
- Prompt Opacity & Context Bloat: High-level abstractions silently inject hundreds of hidden system-prompt tokens, XML delimiters, or chain templates. When an agent fails, engineers struggle to inspect the exact raw string sent to the model.
- Abstraction-Model Mismatch: Scaffolding tuned to compensate for weak models often hurts stronger frontier models—over-constraining reasoning or overriding native tool-calling priors. As foundation models improve every quarter, custom workarounds quickly turn into dead weight.
- Debugging & Latency Overhead: Deep class hierarchies (
AgentExecutor → Chain → CallbackManager → Parser) obscure stack traces, add serialization latency, and make custom context-engineering tricks (like KV-cache prefix stabilization or observation masking) awkward to implement.
Engineering Rule of Thumb: Start with the simplest possible loop (provider SDK + Pydantic validation + structured logging). Introduce a specialized framework only when you hit a specific, concrete bottleneck that the framework natively solves: prompt optimization across models (DSPy), cyclic stateful human-in-the-loop orchestration (LangGraph), or crash-proof distributed durability (Temporal).
DSPy: Declarative Compilation Over Manual Prompting
DSPy (Khattab et al., 2023) challenges the premise that engineers should hand-craft brittle prompt strings. Just as PyTorch replaced manual gradient derivations with declarative tensor graphs and optimizers, DSPy separates program logic from prompt parameters.
Core Abstractions: Signatures, Modules, and Optimizers
- Signatures (What, not How): Typed input/output contracts declaring task semantics without prescribing wording:
- Inline:
"context, question -> answer" - Class-based: typed fields (
dspy.InputField,dspy.OutputField) with brief semantic docstrings.
- Inline:
- Modules (Parameterized Cognitive Blocks): Reusable architectural strategies—such as
dspy.Predict,dspy.ChainOfThought,dspy.ReAct, ordspy.ProgramOfThought—whose underlying instructions and few-shot demonstrations are treatable as learnable parameters . - Teleprompters / Optimizers (Compilation): Given a multi-stage DSPy program , a small training set , and an evaluation metric , a DSPy optimizer compiles the discrete prompt strings and demonstrations across every module jointly to maximize validation performance:
Key Compilation Algorithms
- BootstrapFewShot: Runs the program on (optionally using a stronger teacher model), keeps only end-to-end execution traces where passes, and injects those verified intermediate reasoning traces as few-shot demonstrations into every module.
- MIPROv2 (Multiprompt Instruction Proposal Optimizer): Jointly searches over both data-aware natural-language instructions and bootstrapped few-shot demonstration sets using Bayesian optimization / surrogate modeling to allocate evaluation budget efficiently across large multi-module pipelines.
- BootstrapFinetune: Compiles verified trajectories from a large frontier teacher program into fine-tuning weights for smaller, cheaper open-weight models—bridging prompt optimization and weight distillation.
When DSPy Shines (and When It Doesn’t)
- Best For: Compound multi-hop pipelines (Query Rewriter Retriever Reranker Synthesizer), model migrations (re-compiling a pipeline when switching from GPT/Claude to Gemini or Llama without rewriting prompts by hand), and tasks with an automated evaluation metric .
- Limitations: Compilation requires a representative validation set and reliable metric; DSPy focuses on cognitive program optimization rather than long-running distributed state machines, pause/resume interrupts, or infrastructure durability.
LangGraph: Explicit Cyclic State Machines
Early DAG-based chains (like legacy SequentialChain) could not represent autonomous agents natively because agents are inherently cyclic: Reason → Act → Observe → Retry/Reason loops until a stopping condition holds. LangGraph models agent workflows explicitly as a typed, cyclic directed graph inspired by Google’s Pregel / Bulk Synchronous Parallel (BSP) computation model.
Architectural Primitives
- Typed Shared State () & Reducers: Every node reads from and writes partial updates to a shared state schema (typically a
TypedDictor Pydantic model). Fields declare reducers determining how concurrent or sequential updates merge—for example,Annotated[list[Message], add_messages]appends messages while scalar fields likeretry_countoverwrite. - Nodes () & Conditional Edges (): Nodes are ordinary Python/JS functions executing LLM calls, tool invocations, or deterministic validation. Conditional edges inspect after each node to route dynamically (
continue_to_tools,retry_with_reflection, orEND). - Super-Step Checkpointing: After every discrete super-step , a Checkpointer (SQLite, Postgres, Redis) persists a full snapshot of keyed by
thread_id. This enables:- Time-Travel Debugging: Inspecting exact state transitions or forking execution from step with modified state.
- Fault Recovery: Resuming a thread from the last committed super-step rather than restarting from scratch.
- First-Class Human-in-the-Loop (
interrupt): A node can callinterrupt(payload)to halt execution cleanly before a sensitive action (e.g., sending an email or runningDROP TABLE), persist the graph state to disk, wait hours or days for human approval, and resume seamlessly with the user’s decision.
Trade-Offs of LangGraph
- Strengths: Explicit, inspectable control over loops, parallel fan-out/fan-in branches, token-level streaming, and multi-turn conversational persistence.
- Costs: Introduces schema boilerplate and state-reducer coupling; if your workflow is mostly linear or a simple 1-node ReAct loop, maintaining graph definitions can feel heavier than plain async Python.
Temporal: Durable Execution for Production Reliability
Checkpointing at graph super-step boundaries helps within a single healthy service, but production agents routinely run for minutes, hours, or days across unreliable networks and ephemeral containers. Consider what goes wrong in an ordinary Python asyncio agent loop or lightweight checkpointer:
- A Kubernetes pod receives
SIGTERMor OOM-kills midway through a 40-step deep research job. - An external MCP server times out after 90 seconds, or an LLM API returns intermittent
503/429errors. - A crashed worker restarts and accidentally re-executes a non-idempotent side effect (sending a duplicate invoice or opening two identical PRs).
Temporal solves these distributed systems failures through Durable Execution—separating orchestration logic from side-effectful work via an append-only Event History.
Workflows vs. Activities
| Concept | Role in Temporal | Determinism Requirement | Examples in AI Agents |
|---|---|---|---|
| Workflow | Orchestrates the control flow (while loop, branching, timers, human approvals) |
Strictly deterministic (same inputs + Event History must produce identical decisions) | Agent control loop, multi-agent coordinator, approval state machine |
| Activity | Performs actual I/O and non-deterministic work | Non-deterministic (retried automatically with configurable backoff & timeouts) | LLM inference calls, MCP tool execution, database writes, sandbox code runs |
How Deterministic Replay Guarantees Crash-Proof Agents
When a Temporal Workflow invokes an Activity (such as call_llm or run_sandbox_code), the Temporal Server records an ActivityTaskScheduled event and, upon completion, an ActivityTaskCompleted(result) event in a durable Event History.
If the worker container crashes at step 14:
- Another healthy worker picks up the workflow thread and replays the Workflow function from line 1.
- Whenever the replayed code reaches an Activity from steps , Temporal sees the matching
ActivityTaskCompletedrecord in the Event History and returns the recorded payload in without re-running the LLM call or repeating the side effect. - Execution seamlessly resumes at step 14—preserving local Python loop variables, call stacks, and multi-day
workflow.sleep()timers without manual state serialization boilerplate. - External Signals and Updates inject human-in-the-loop approvals or user follow-up messages directly into a running Workflow at any time.
Combining Patterns in Production
Notice that DSPy, LangGraph, and Temporal are not mutually exclusive—they address orthogonal engineering layers:
- Raw Loop + Temporal: Ideal for backend/async engineering agents (coding agents, incident responders, data pipelines). Write clean, idiomatic Python control flow inside a Temporal Workflow, wrapping LLM calls and sandbox tools as retriable Activities.
- DSPy Inside Nodes/Activities: Use DSPy to compile and optimize complex cognitive sub-steps (e.g., query decomposition or structured extraction) inside either a LangGraph node or a Temporal Activity.
- LangGraph + Checkpointer: Ideal for interactive, multi-turn conversational copilots requiring explicit visualizable state transitions, streaming UI updates, and thread-level time travel.
Framework Decision Matrix
| Criterion | Raw Python Loop | DSPy | LangGraph | Temporal |
|---|---|---|---|---|
| Primary Problem Solved | Zero-overhead execution | Automated prompt & demo compilation | Explicit cyclic state & UI streaming | Crash-proof distributed durability |
| Harness Tax | Minimal (full transparency) | Low–Medium (module signatures) | Medium–High (graph & reducer boilerplate) | Medium (determinism rules in Workflows) |
| Optimization Target | Developer speed & debuggability | Task accuracy / metric | Complex branching & HITL interrupts | Long-horizon SLA, retries, idempotency |
| Native Persistence / Replay | Manual | Stateless (artifact save/load) | Super-step Checkpointers | Event-sourced deterministic replay |
| Best Default Starting Point? | Yes (for single-agent MVPs) | When prompts break across models/data | When building stateful interactive flows | When jobs run or mutate prod state |