What Is an AI Agent? The Agent Loop Explained

A
Author
09 Oct, 2026 2 min read 1.34K views

"Agent" is used for many things, but the core idea is simple: an AI agent is an LLM that decides which tools to call, sees the results, and keeps going until the task is done. Your code runs the tools; the model chooses what to do next.

The loop

  1. Send the user's goal and a list of available tools to the model.
  2. The model replies with either a final answer or one or more tool calls (name + JSON arguments).
  3. Your code executes the tool calls and sends the results back.
  4. Repeat until the model stops asking for tools.

A minimal agent in TypeScript

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

const client = new Anthropic();

const tools: Anthropic.Tool[] = [
  {
    name: 'get_order_status',
    description: 'Look up the shipping status of an order by its order id.',
    input_schema: {
      type: 'object',
      properties: { order_id: { type: 'string', description: 'e.g. ORD-1042' } },
      required: ['order_id'],
    },
  },
];

async function runTool(name: string, input: any) {
  if (name === 'get_order_status') return JSON.stringify(await db.orderStatus(input.order_id));
  throw new Error(`Unknown tool ${name}`);
}

const messages: Anthropic.MessageParam[] = [{ role: 'user', content: 'Where is order ORD-1042?' }];

while (true) {
  const response = await client.messages.create({ model: 'claude-opus-5-5', max_tokens: 16000, tools, messages });
  messages.push({ role: 'assistant', content: response.content });

  if (response.stop_reason !== 'tool_use') break; // final answer (or another terminal stop)

  const results: Anthropic.ToolResultBlockParam[] = [];
  for (const block of response.content) {
    if (block.type !== 'tool_use') continue;
    try {
      results.push({ type: 'tool_result', tool_use_id: block.id, content: await runTool(block.name, block.input) });
    } catch (err) {
      results.push({ type: 'tool_result', tool_use_id: block.id, content: String(err), is_error: true });
    }
  }
  messages.push({ role: 'user', content: results });
}

What makes it an agent

  • The model controls the flow. You don't hard-code "first call A, then B".
  • It reacts to results. If a lookup fails, it can try a different approach or ask the user.
  • It stops on its own when it judges the goal is met.

That flexibility is powerful but harder to predict and test than fixed code. Use an agent when the steps genuinely can't be known in advance.

Was this article helpful?

Comments

No comments yet. Have a question or a tip? Be the first to share it.

Leave a comment

Comments are reviewed before they appear.