[ ABORT TO HUD ]
SEQ. 1
SEQ. 2
SEQ. 3
The Minimal Agent Loop
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",
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!
}
}
}
🎉 That's It! Every framework (LangChain, CrewAI, LangGraph) is fundamentally just this loop with extra features. Master this pattern first.
⌨ HANDS-ON LABRun Your First Agent Loop
⭐ +200 XPTime 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
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