6. Agentic Loops

Observe, think, act, repeat

Everything we've covered so far — prompt engineering, structured output, tool use, context management, RAG — converges here. An agentic loop is a system where a language model repeatedly observes its environment, decides what to do, takes an action, and uses the result to inform its next decision. It's the pattern behind every AI coding assistant, every autonomous research agent, and every AI system that does more than answer a single question.

The jump from "model that answers questions" to "agent that completes tasks" is surprisingly small in terms of code. It's a while loop. But the engineering challenges — reliability, cost control, error recovery, safety — are where the real work happens.

The Basic Loop

At its simplest, an agentic loop is:

while task is not complete:
    observe  → gather information (read files, check state)
    think    → decide what to do next
    act      → execute a tool call
    evaluate → did it work? what changed?

In code:

async function agentLoop(task: string): Promise<string> {
  const messages: Message[] = [
    { role: "user", content: task }
  ];

  while (true) {
    const response = await llm.chat({
      messages,
      tools: TOOL_DEFINITIONS,
      system: SYSTEM_PROMPT
    });

    // If the model produced only text (no tool calls), it's done
    if (!response.toolCalls?.length) {
      return response.text;
    }

    // Execute tool calls
    messages.push({ role: "assistant", content: response.content });

    const results = await executeToolCalls(response.toolCalls);
    messages.push({ role: "user", content: results });
  }
}

That's the entire skeleton. The model decides when to use tools and when to stop. It decides what information to gather and what actions to take. The host application just executes the tool calls and feeds results back.

ReAct: Reasoning + Acting

The most influential agentic pattern is ReAct — Reasoning and Acting. Instead of letting the model silently decide what to do, you ask it to explicitly reason before each action:

Thought: The user wants me to fix the failing test. I should first read
         the test file to understand what's being tested.
Action: read_file("src/auth.test.ts")
Observation: [file contents...]

Thought: The test expects a 401 status but the handler returns 403. I need
         to check the auth middleware to understand why.
Action: read_file("src/middleware/auth.ts")
Observation: [file contents...]

Thought: I see — the middleware returns 403 for expired tokens but the test
         expects 401. The HTTP spec says 401 is correct for authentication
         failures. I should fix the middleware.
Action: edit_file("src/middleware/auth.ts", old="403", new="401")
Observation: File updated successfully.

Thought: Now I should run the tests to verify the fix.
Action: run_command("npm test -- --grep auth")
Observation: All tests passing.

Thought: The fix is complete. Let me summarize what I did.
Final Answer: Fixed the auth middleware to return 401 instead of 403...

The explicit reasoning step serves two purposes:

  1. Better decisions — chain-of-thought reasoning improves the model's action selection, just as it improves its answers to reasoning questions
  2. Observability — you (and the user) can see why the agent made each decision, which makes debugging and trust-building much easier

Most production systems implement ReAct implicitly by including instructions like "think through your approach before acting" in the system prompt, rather than parsing explicit Thought/Action/Observation labels.

Planning Strategies

For complex tasks, the agent needs a plan — not just a next action. There are several approaches:

Upfront planning

The agent creates a plan before taking any action:

System: Before starting work, create a numbered plan of steps.
        Execute each step, updating the plan if you discover new
        information that changes your approach.

Agent:
Plan:
1. Read the failing test to understand the expected behavior
2. Read the implementation to find the bug
3. Fix the bug
4. Run tests to verify
5. Check for similar issues in related files

Executing step 1...

This works well for well-defined tasks where the steps are predictable. It falls apart for exploratory tasks where you don't know what you'll find.

Iterative planning

The agent plans one or two steps ahead, then replans after seeing results:

Agent: I'll start by reading the test file to understand what's expected.
[reads file]
Agent: Now I see the test structure. The issue is in the token validation.
       I'll read the validator next.
[reads file]
Agent: The validator is correct, but it's being called with the wrong
       arguments. Let me trace back to where it's called from.

This is more robust to surprises but can lead to inefficient exploration if the agent doesn't maintain a clear goal.

Hierarchical planning

Break the task into sub-tasks, each with its own agent loop:

Main agent: This feature requires changes to the API, the database schema,
            and the frontend. I'll handle each separately.

Sub-agent 1: [modifies API routes and handlers]
Sub-agent 2: [generates migration and updates models]
Sub-agent 3: [updates frontend components]

Main agent: All sub-tasks complete. Running integration tests...

This is how some advanced coding assistants handle large tasks — spawning focused sub-agents that each operate in a smaller context with a clearer goal.

Error Recovery

Agents fail. Tools return errors, tests don't pass, the model makes wrong assumptions. How the agent recovers determines whether it's useful or frustrating.

Retry with feedback

The simplest pattern: when a tool call fails, show the error to the model and let it try again.

async function executeWithRetry(
  toolCall: ToolCall,
  maxRetries: number = 2
): Promise<ToolResult> {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    const result = await executeTool(toolCall);
    if (!result.error) return result;

    // Feed error back to the model for correction
    if (attempt < maxRetries) {
      toolCall = await llm.correctToolCall(toolCall, result.error);
    }
  }
  return { error: "Failed after retries", details: lastError };
}

Backtracking

When the agent realizes it went down the wrong path, it needs to undo its actions and try a different approach:

Agent: I edited src/auth.ts to fix the token validation...
       [runs tests]
       Tests still failing — my fix was wrong.
       Let me revert that change and look at this from a different angle.
       [reverts edit]
       [reads related files]
       Actually, the issue is in the middleware, not the validator...

This requires the agent to:

  1. Recognize that its approach isn't working (not just retry the same thing)
  2. Undo the failed changes cleanly
  3. Try a fundamentally different approach

Good system prompts explicitly instruct this: "If your first approach doesn't work after 2 attempts, step back and consider alternative explanations."

Graceful degradation

When the agent can't complete the task, it should fail informatively:

Agent: I've tried three approaches to fix this test but none worked.
       Here's what I found:
       - The test expects behavior X, but the code implements Y
       - Changing to X breaks two other tests
       - This might be a design issue that needs human input

       My recommendation is to update the test expectations rather than
       the implementation, but I wanted to check with you first.

An agent that admits its limitations and provides useful partial results is far more valuable than one that silently fails or loops forever.

Loops, Budgets, and Termination

An agentic loop without limits will run forever (and cost a fortune). Every production system needs termination conditions:

Turn limits

const MAX_TURNS = 50;
for (let turn = 0; turn < MAX_TURNS; turn++) {
  // ... agent loop
}

Token budgets

Track cumulative token usage and stop when the budget is exhausted:

let totalTokens = 0;
const TOKEN_BUDGET = 500_000;

while (totalTokens < TOKEN_BUDGET) {
  const response = await llm.chat({ messages, tools });
  totalTokens += response.usage.total_tokens;
  // ...
}

Stuck detection

If the agent repeats the same action more than N times, it's stuck:

const recentActions = new Map<string, number>();

function isStuck(action: string): boolean {
  const key = JSON.stringify(action);
  const count = (recentActions.get(key) ?? 0) + 1;
  recentActions.set(key, count);
  return count >= 3;
}

Goal completion

The cleanest termination: the agent declares the task complete and explains what it did. This happens naturally when the model produces a text response with no tool calls.

Multi-Agent Systems

Some tasks benefit from multiple agents with different roles:

Orchestrator + specialists

Orchestrator: Routes sub-tasks to specialists
├── Coder: Writes and edits code
├── Reviewer: Reviews changes for bugs and style
├── Tester: Writes and runs tests
└── Researcher: Searches docs and codebase for context

The orchestrator doesn't write code itself — it delegates to specialists and synthesizes their work. This mirrors how human teams operate and can produce higher-quality results than a single agent trying to do everything.

Debate / verification

Two agents with opposing roles:

Generator: Produces a solution
Verifier:  Tries to find flaws in the solution
Generator: Fixes the flaws
Verifier:  Checks again

This is expensive (2x the API calls) but catches errors that a single agent would miss. It's particularly valuable for safety-critical code or complex logic.

Pipeline agents

Each agent handles one stage of a pipeline:

Analyzer → Planner → Implementer → Tester → Reviewer

Each agent's output feeds into the next. This works well when the stages are distinct and sequential.

State Management

As the loop runs, state accumulates: files read, edits made, tests run, errors encountered. Managing this state is critical for long-running tasks.

Conversation history as state

The simplest approach: everything is in the message history. The model can look back at previous tool calls and results to understand what it's done.

Problem: conversation history grows without bound. After 30 tool calls, you've got 100K+ tokens of history, most of it irrelevant to the current step.

Structured state

Maintain an explicit state object alongside the conversation:

interface AgentState {
  plan: string[];
  currentStep: number;
  filesModified: string[];
  testsRun: { name: string; passed: boolean }[];
  errors: string[];
  summary: string;
}

Inject the current state into the system prompt on each turn. This gives the model a concise picture of where it stands without scrolling through hundreds of messages.

Checkpoints

For long tasks, save state at milestones so you can resume after failures:

async function agentLoopWithCheckpoints(task: string): Promise<string> {
  let state = loadCheckpoint() ?? initialState(task);

  while (!state.complete) {
    const response = await runStep(state);
    state = updateState(state, response);

    if (isMilestone(state)) {
      saveCheckpoint(state);
    }
  }

  return state.summary;
}

Observability

You can't debug what you can't see. Agentic systems need logging at every level:

  • Decisions: why the model chose this action over alternatives
  • Tool calls: what was called with what arguments
  • Tool results: what came back (truncated for large results)
  • State transitions: what changed after each step
  • Token usage: how much of the budget has been consumed
  • Timing: how long each step took

The best coding assistants stream this information to the user in real time. You can watch the agent read files, think through its approach, make edits, and run tests. This transparency is both a UX feature and a debugging tool.

Cost Optimization

Agentic loops are expensive. Every turn requires an API call, and long contexts amplify the cost. Practical optimizations:

Use cheaper models for simple steps. File search, formatting, and simple lookups don't need the most capable model. Route straightforward tool-selection steps to a faster, cheaper model and reserve the powerful model for reasoning and code generation.

Cache tool results. If the agent reads the same file twice in one session, serve it from cache instead of re-reading (assuming no modifications in between).

Summarize aggressively. After each milestone, compress the conversation history. The model doesn't need the full output of every git log it ran — just the conclusions it drew.

Batch tool calls. When the model needs to read three files, execute all three reads in parallel instead of sequentially. This doesn't reduce token cost but cuts wall-clock time significantly.

Try It — Agent Loop Simulator

Watch an agent work through a task step by step. Each step shows the agent's reasoning, tool calls, results, error recovery, and final output. The token budget bar tracks cumulative usage.

Tokens: 0
Turns: 0
Tool calls: 0

What's Next

This article covered the general architecture of agentic loops. The next article applies these patterns to the specific domain of code agents — the architecture of tools like Claude Code, Cursor, and Opencode that can read, understand, modify, and test entire codebases autonomously.