Skip to main content

The Minimal Agent Loop — Build Your First Agent

[ ABORT TO HUD ]
SEQ. 1
SEQ. 2
SEQ. 3

The Minimal Agent Loop

🛠️ Build Your First Agent⏱ 12 min⭐ 100 BASE XP⌨ HANDS-ON LAB

Your First Agent in 50 Lines

Forget frameworks. Build one from scratch to truly understand agents.

The Architecture

┌────────────────────────────────────┐
│       THE MINIMAL AGENT LOOP       │
├────────────────────────────────────┤
│  1. Send messages + tools to LLM   │
│  2. Get response                   │
│  3. If response has tool_use:      │
│     a. Execute the tool             │
│     b. Add result to messages       │
│     c. GOTO step 1                  │
│  4. If response has text:           │
│     a. Return the text (DONE)       │
└────────────────────────────────────┘

Complete Implementation (TypeScript)

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();
const tools = [{
  name: "get_weather",
  description: "Get current weather for a city",
  input_schema: {
    type: "object",
    properties: {
      city: { type: "string", description: "City name" }
    },
    required: ["city"]
  }
}];

async function runAgent(userMessage: string) {
  const messages = [{ role: "user", content: userMessage }];
  
  while (true) {
    const response = await client.messages.create({
      model: "claude-sonnet-5-5",
      max_tokens: 1024,
      tools,
      messages
    });
    
    if (response.stop_reason === "tool_use") {
      const toolBlock = response.content.find(b => b.type === "tool_use");
      const result = executeWeather(toolBlock.input.city);
      messages.push({ role: "assistant", content: response.content });
      messages.push({
        role: "user",
        content: [{ type: "tool_result", tool_use_id: toolBlock.id,
                     content: JSON.stringify(result) }]
      });
    } else {
      return response.content[0].text; // Done!
    }
  }
}

Production Shortcut: Anthropic Claude Agent SDK

Once you understand the raw while loop, Anthropic's official Claude Agent SDK (pip install claude-agent-sdk in Python and npm install @anthropic-ai/claude-agent-sdk in TypeScript - renamed from claude-code-sdk / @anthropic-ai/claude-code) packages this exact loop with built-in file/bash/MCP tools, context compaction, and permission gates:

from claude_agent_sdk import query, ClaudeAgentOptions

async for message in query(
    prompt="Inspect src/ and summarize potential race conditions.",
    options=ClaudeAgentOptions(
        allowed_tools=["Read", "Grep", "Glob"],
        permission_mode="default",
        max_turns=6,
    ),
):
    print(message)
🎉 That's It! Every framework (Claude Agent SDK, OpenAI Agents SDK, CrewAI, LangGraph) is fundamentally this loop with extra guardrails, memory, and observability. Master this pattern first.
⌨ HANDS-ON LABRun Your First Agent Loop
⭐ +200 XP

Time to ship. Install the client library, export your key, and execute the minimal while-loop agent you just studied.

1Install the OpenAI Python library with pip (the agent loop uses it as the LLM client).
2Export an API key so the loop can authenticate (any value works in the sandbox).
3Run the agent script: python agent.py
lab-sandbox — simulated environment
INFINITY LAB SANDBOX v2.6 — simulated shell
Type the command for the current objective. Helpers: "hint", "solution", "clear".
$
OBJECTIVE 1 / 3 — type "hint" if stuck
SYNAPSE VERIFICATION
QUERY 1 // 2
What determines whether the agent loop continues or stops?
A timer
The stop_reason - 'tool_use' means continue, 'end_turn' means done
Random
Message count