Agentic Loops and Scaffolding

An agentic loop is the repeated sense→reason→act cycle in which a language model (or other policy) autonomously invokes tools, observes results, updates its working context, and decides whether to continue or halt—without requiring a human in the loop at each step. Scaffolding is the surrounding software infrastructure—prompt templates, memory stores, tool registries, loop controllers, and error handlers—that converts a bare model into a functional agent. Together they matter because virtually every production AI system that solves multi-step tasks (coding assistants, research agents, autonomous data pipelines) is built on these primitives. The counterintuitive fact: the intelligence of an agentic system often resides more in the scaffolding design than in the model itself—a weaker model with well-designed scaffolding routinely outperforms a stronger model running naively.

The core insight

A single forward pass through a language model is a function, not a process—it maps tokens to tokens with no persistent state or ability to affect the world. An agentic loop turns that stateless function into a stateful process by wrapping it in an outer control structure that (1) maintains memory across steps, (2) lets the model emit structured actions, (3) executes those actions in the environment, and (4) feeds observations back as new context. The "aha moment" is recognizing that agency is not a property of the model weights at all—it is an emergent property of the loop architecture.

How It Works

The Agentic Loop as a Markov Decision Process

An agentic loop can be formalized as a partially observable Markov decision process (POMDP) where the agent policy πθ\pi_\theta is parameterized by a language model. At each discrete timestep tt, the agent maintains a belief state summarizing all information so far.

1
st=Concat ⁣(I, m1:t−1, o1:t−1, a1:t−1)\quad s_t = \text{Concat}\!\bigl(I,\, m_{1:t-1},\, o_{1:t-1},\, a_{1:t-1}\bigr)

Explanation: The agent's effective state at step tt is the concatenation of the system instruction II, all prior memory chunks mm, prior observations oo, and prior actions aa—this is the full prompt fed to the model.

Symbols:

  • sts_t — the prompt context (belief state) at step tt
  • II — the system prompt / task instruction
  • m1:t−1m_{1:t-1} — retrieved or summarized memory up to step t−1t-1
  • o1:t−1o_{1:t-1} — tool-call observations (environment responses) up to step t−1t-1
  • a1:t−1a_{1:t-1} — the agent's own prior actions (tool calls + reasoning traces)

The policy samples the next action from the model's conditional distribution:

2
at∼πθ ⁣(a∣st)=exp⁡ ⁣(fθ(st,a)/τ)∑a′exp⁡ ⁣(fθ(st,a′)/τ)\quad a_t \sim \pi_\theta\!\left(a \mid s_t\right) = \frac{\exp\!\bigl(f_\theta(s_t, a)/\tau\bigr)}{\sum_{a'} \exp\!\bigl(f_\theta(s_t, a')/\tau\bigr)}

Explanation: The model draws the next action token-by-token from a softmax distribution over the vocabulary, tempered by τ\tau, conditioned on the full accumulated context.

Symbols:

  • πθ\pi_\theta — the language model policy with weights θ\theta
  • fθ(st,a)f_\theta(s_t, a) — the unnormalized log-probability (logit) the model assigns to action aa given context sts_t
  • τ\tau — temperature controlling exploration vs. exploitation

After the scaffolding executes ata_t (e.g., calls a Python interpreter or a search API), the environment returns an observation:

3
ot=E(at)\quad o_t = \mathcal{E}(a_t)

Explanation: The environment function E\mathcal{E} deterministically or stochastically maps the agent's action to a structured observation string—the raw output of the tool.

Symbols:

  • E\mathcal{E} — environment / tool executor (Python REPL, web API, database, file system, etc.)
  • oto_t — the observation string returned and appended to context

The loop terminates when the policy emits a designated FINISH token or action, or when a scaffolding-enforced bound is reached:

4
T=min⁡ ⁣(inf⁡{t:at=FINISH},  Tmax⁡)\quad T = \min\!\Bigl(\inf\{t : a_t = \texttt{FINISH}\},\; T_{\max}\Bigr)

Explanation: The actual episode length is whichever comes first—the model deciding it is done, or the scaffolding's hard maximum step limit Tmax⁡T_{\max}, preventing infinite loops.

Symbols:

  • TT — actual episode termination step
  • Tmax⁡T_{\max} — scaffolding-enforced hard cap on loop iterations
  • FINISH\texttt{FINISH} — the special action token or function call signaling task completion

Context Budget and Memory Compression

Because ∣st∣|s_t| grows linearly with tt, practical scaffolds apply a compression operator to keep the prompt within the model's context window CC:

5
st′=K ⁣(st,  C),∣tokens(st′)∣≤C\quad s_t' = \mathcal{K}\!\left(s_t,\; C\right), \quad |\text{tokens}(s_t')| \leq C

Explanation: The scaffolding's context manager K\mathcal{K} trims or summarizes sts_t to fit within the model's window CC—the design of K\mathcal{K} (summarize oldest, evict least-relevant, or RAG-retrieve) is one of the most consequential scaffolding decisions.

Symbols:

  • st′s_t' — the compressed/managed context actually sent to the model
  • K\mathcal{K} — the context management operator (summarizer, sliding window, RAG retriever)
  • CC — the model's maximum context length in tokens

---

PyTorch / Implementation Sketch

```python import json from typing import Callable def agentic_loop( model_call: Callable[[str], str], # π_θ: prompt → raw action string tools: dict[str, Callable], # environment ε system_prompt: str, task: str, max_steps: int = 20, # T_max context_manager: Callable = None, # K compression operator ) -> str: history = [] # stores (action, observation) pairs context = system_prompt + "\n\nTask: " + task for step in range(max_steps):

# Apply context compression if provided (eq [5]) prompt = context_manager(context, history) if context_manager else ( context + "\n" + format_history(history) )

# Sample action from policy (eq [2]) raw_action = model_call(prompt)

# Parse structured action (tool name + arguments) action = parse_action(raw_action) # e.g. {"tool": "python", "code": "..."} if action["tool"] == "FINISH": # termination check (eq [4]) return action.get("answer", raw_action)

# Execute tool — environment step (eq [3]) tool_fn = tools.get(action["tool"]) if tool_fn is None: observation = f"ERROR: unknown tool '{action['tool']}'" else: try: observation = str(tool_fn(**action.get("args", {}))) except Exception as e: observation = f"ERROR: {e}" # defensive scaffolding history.append({"action": raw_action, "observation": observation}) return "MAX_STEPS_REACHED" # hard cap — never infinite loop

def format_history(history): return "\n".join( f"Action: {h['action']}\nObservation: {h['observation']}" for h in history ) ``` This sketch deliberately keeps `context_manager` pluggable—swapping in a RAG retriever versus a sliding-window summarizer changes the agent's effective memory without touching the loop logic. ---

researcher · Yann LeCun | b. 1960 | Autonomous Machine Intelligence and World Models

LeCun developed foundational convolutional architectures and has been the chief scientific officer at Meta AI since 2013. His 2022 position paper A Path Towards Autonomous Machine Intelligence directly influenced the agentic-systems community by articulating the need for persistent world models and hierarchical planning loops as prerequisites for genuine autonomy—ideas now central to scaffolding design. He famously predicted that pure auto-regressive LLM loops would hit a ceiling without model-based planning, a view that has catalyzed a wave of hybrid agentic architectures.

researcher · Shunyu Yao | b. 1997 | ReAct and Chain-of-Thought Tool Use

Yao, a Princeton and Stanford-affiliated researcher, co-authored the landmark 2022 ReAct paper that first systematically demonstrated interleaving chain-of-thought reasoning traces with tool-call actions inside an LLM loop—the direct intellectual ancestor of most modern agentic scaffolds. The key insight was that allowing the model to reason before acting (and to observe before reasoning again) dramatically reduced compounding errors versus pure action-only loops. Remarkably, the original ReAct experiments used GPT-3-class models (175 B parameters) yet outperformed much more complex RL-trained agents on multi-hop QA benchmarks.

Figure
Agentic Loop and Scaffolding Architecture
Agentic Loop & Scaffolding Architecture SCAFFOLDING Loop Controller step / termination Context Manager compress / retrieve (K) Memory Store episodic / semantic LLM Policy π_θ a_t ~ π_θ(a | s_t) reason + act tokens (CoT + tool call) Tool Registry search / code / APIs Env Executor ε o_t = ε(a_t) Obs. Parser validate + format s_t a_t o_t → history loop
Figure
ReAct Trace: Interleaved Thought–Action–Observation
ReAct Trace — Interleaved Reasoning & Acting STEP TYPE CONTENT t=1 THOUGHT "I need to find the population of Lagos. Let me search." t=1 ACTION search("Lagos population 2024") t=1 OBSERVE ε → "Lagos: ~16.1M city proper, ~24M metro (2024 UN est.)" t=2 THOUGHT "I have the number. The answer is 16.1M city / 24M metro. I can finish." t=2 FINISH answer("Lagos has ~16.1M people in city proper (24M metro).") T_max = 20 steps — loop terminated at t=2 by FINISH action

Intuition

The Mental Model

Imagine a very capable but amnesiac consultant who can only read what's written on a single whiteboard. Each time you need them to do something complex, you write the task on the board, they read it, write down their plan and a specific next action, then step out of the room while an assistant executes that action and writes the result back on the board. The consultant re-enters, reads the whole board (task + plan + result), updates the plan, writes the next action, and so on. The consultant is the language model. The whiteboard is the context window. The assistant who executes actions is the environment executor. The person who decides how much history to erase when the board fills up—that is the context manager, and their erasing policy is the most important design decision in the whole system. Scaffolding is the rulebook governing the consultant, the assistant, and the whiteboard—it doesn't make the consultant smarter, but it makes the whole system far more capable than any single conversation.

Historical Development

Origins · 1 minhow this was discovered
History
1950: Alan Turing's Computing Machinery and Intelligence introduces the imitation game and the concept of a machine that acts intelligently in an open-ended interactive loop—an early conceptual ancestor of agency.
1987: Rodney Brooks publishes Intelligence Without Representation, arguing that intelligence emerges from reactive sense-act loops grounded in the environment, not from symbolic planning—directly prefiguring agentic loop design philosophy.
1992: John Laird, Allen Newell, and Paul Rosenbloom's SOAR architecture establishes the cognitive cycle (perception → decision → action) as a formal computational substrate for general intelligent agents, influencing later LLM agent frameworks.
2022 (March): Chain-of-Thought Prompting Elicits Reasoning in Large Language Models (Wei et al., Google) demonstrates that intermediate reasoning steps improve LLM performance—establishing the "thought" component of agentic traces.
2022 (October): ReAct: Synergizing Reasoning and Acting in Language Models (Yao et al.) introduces the interleaved Thought–Action–Observation loop for LLMs, becoming the canonical scaffolding pattern for agentic systems.
2023 (March): OpenAI releases the ChatGPT Plugins system and later the Assistants API with Code Interpreter—the first mainstream productized agentic scaffold, bringing tool-calling loops to millions of users.
2023 (April): AutoGPT is open-sourced and reaches 100 k GitHub stars in five days, demonstrating explosive practitioner interest in fully autonomous agentic loops and surfacing the failure modes of under-constrained scaffolding.
2023 (July): AgentBench (Liu et al.) provides the first systematic benchmark for LLM agents across diverse environments, establishing rigorous evaluation methodology for agentic loop performance.
2024: Multi-agent frameworks—LangGraph, AutoGen (Microsoft), CrewAI—achieve widespread adoption, extending single-agent loops to networks of cooperating agents with shared memory and message-passing scaffolding.

Why It Matters

Real-World Impact
OpenAI Operator / GPT-4 Assistants with Code InterpreterUses a scaffolded loop where GPT-4 can emit Python code blocks, which the platform executes in a sandboxed kernel; observations (stdout, plots, errors) are injected back as tool results. The scaffolding enforces file-size limits, timeout caps, and output sanitization—none of which are model-level controls.
GitHub Copilot WorkspaceImplements a multi-step agentic loop over an entire repository: the model reads file trees, proposes edits, runs tests, observes CI output, and re-plans. The scaffolding manages git-diff context, test result truncation, and a structured "plan → implement → verify" loop phase controller.
Devin (Cognition AI)A software engineering agent that maintains a persistent shell session, browser, and code editor as environment tools; the scaffolding tracks a structured task graph and re-invokes planning when sub-tasks fail, demonstrating that loop architecture (not just model capability) enables sustained autonomous coding.
LangGraph / LangChain LCELOpen-source scaffolding framework explicitly modeling agent state as a typed graph; each node is a model call or tool call, edges represent conditional transitions (including loops), and the library handles serialization, checkpointing, and human-in-the-loop interruption points.
Perplexity.aiUses a retrieval-augmented agentic loop where each user query triggers multiple rounds of web search, result re-ranking, and iterative synthesis—the "search → read → reason → search again" pattern is a constrained agentic loop with a maximum of ~4 iterations per query to bound latency.
AutoGen (Microsoft Research)Multi-agent scaffolding framework where specialized sub-agents (coder, critic, executor) communicate via a shared message bus; the orchestrator scaffold routes messages, enforces turn-taking, and injects error observations from code execution back into the conversation loop.
AlphaCode 2 / AlphaProof (DeepMind)Employs a generate-execute-reflect loop in which a language model generates candidate programs or proofs, a symbolic executor verifies them, and failing observations are fed back to guide resampling—the scaffolding's retry budget and diversity-enforcement heuristics are central to its superhuman performance on competition math.

Prerequisites

What This Leads To

See Also

ReAct Framework · Chain-of-Thought Prompting · Retrieval-Augmented Generation · Tool Use and Function Calling · Multi-Agent Systems · AutoGPT and Open-Ended Agents · LangChain and LangGraph

Before this

Where this leads