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.
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 is parameterized by a language model. At each discrete timestep , the agent maintains a belief state summarizing all information so far.
Explanation: The agent's effective state at step is the concatenation of the system instruction , all prior memory chunks , prior observations , and prior actions —this is the full prompt fed to the model.
Symbols:
- — the prompt context (belief state) at step
- — the system prompt / task instruction
- — retrieved or summarized memory up to step
- — tool-call observations (environment responses) up to step
- — the agent's own prior actions (tool calls + reasoning traces)
The policy samples the next action from the model's conditional distribution:
Explanation: The model draws the next action token-by-token from a softmax distribution over the vocabulary, tempered by , conditioned on the full accumulated context.
Symbols:
- — the language model policy with weights
- — the unnormalized log-probability (logit) the model assigns to action given context
- — temperature controlling exploration vs. exploitation
After the scaffolding executes (e.g., calls a Python interpreter or a search API), the environment returns an observation:
Explanation: The environment function deterministically or stochastically maps the agent's action to a structured observation string—the raw output of the tool.
Symbols:
- — environment / tool executor (Python REPL, web API, database, file system, etc.)
- — 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:
Explanation: The actual episode length is whichever comes first—the model deciding it is done, or the scaffolding's hard maximum step limit , preventing infinite loops.
Symbols:
- — actual episode termination step
- — scaffolding-enforced hard cap on loop iterations
- — the special action token or function call signaling task completion
Context Budget and Memory Compression
Because grows linearly with , practical scaffolds apply a compression operator to keep the prompt within the model's context window :
Explanation: The scaffolding's context manager trims or summarizes to fit within the model's window —the design of (summarize oldest, evict least-relevant, or RAG-retrieve) is one of the most consequential scaffolding decisions.
Symbols:
- — the compressed/managed context actually sent to the model
- — the context management operator (summarizer, sliding window, RAG retriever)
- — 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. ---
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.
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.
Intuition
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
Why It Matters
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