DEV Community

Cover image for What an AI Agent Actually Is, With a Working TypeScript Loop
Zahid Hasan Tonmoy
Zahid Hasan Tonmoy

Posted on Originally published at zahidhasantonmoy.vercel.app

What an AI Agent Actually Is, With a Working TypeScript Loop

When people say “AI agent”, they usually mean one specific thing: a language model that can act, look at what happened, and decide what to do next. Everything else is packaging.

This post is the short version, plus a loop you can run in a few minutes.

The definition I actually use

An AI agent is a software system that uses a language model to work toward a goal on its own. It decides the next step, uses tools such as APIs, databases or a code runner, checks the result, and repeats until the job is done or it needs a human.

A chatbot answers once. An agent keeps going.

The loop

  1. The user gives a goal.
  2. The model reads the goal and the history so far, then picks the next step.
  3. If it needs a tool, your code runs it.
  4. The result goes back to the model as new information.
  5. Back to step 2, until the model returns a final answer.

A runnable version

The example below uses the Anthropic SDK and a fake in-memory order lookup, so an API key is all you need.

// agent/loop.ts
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic();

const orders: Record<string, { status: string; eta: string }> = {
  'BD-1042': { status: 'out for delivery', eta: 'today' },
  'BD-1043': { status: 'processing', eta: '5 days' },
};

const tools: Anthropic.Tool[] = [
  {
    name: 'get_order_status',
    description: 'Look up the status and delivery estimate of an order by its ID',
    input_schema: {
      type: 'object',
      properties: { order_id: { type: 'string' } },
      required: ['order_id'],
    },
  },
];

function runTool(name: string, input: { order_id: string }) {
  if (name === 'get_order_status') {
    return orders[input.order_id] ?? { error: 'order not found' };
  }
  return { error: 'unknown tool' };
}

async function runAgent(goal: string) {
  const messages: Anthropic.MessageParam[] = [{ role: 'user', content: goal }];

  for (let step = 0; step < 5; step++) {
    const response = await client.messages.create({
      model: 'claude-sonnet-5',
      max_tokens: 1024,
      tools,
      messages,
    });

    messages.push({ role: 'assistant', content: response.content });

    if (response.stop_reason !== 'tool_use') {
      const block = response.content.find((b): b is Anthropic.TextBlock => b.type === 'text');
      return block?.text ?? '';
    }

    const results: Anthropic.ToolResultBlockParam[] = response.content
      .filter((b): b is Anthropic.ToolUseBlock => b.type === 'tool_use')
      .map((b) => ({
        type: 'tool_result',
        tool_use_id: b.id,
        content: JSON.stringify(runTool(b.name, b.input as { order_id: string })),
      }));

    messages.push({ role: 'user', content: results });
  }

  return 'Stopped: step limit reached';
}

runAgent('Where is my order BD-1042?').then(console.log);
Enter fullscreen mode Exit fullscreen mode

Install the SDK with npm install @anthropic-ai/sdk, set ANTHROPIC_API_KEY and run npx tsx agent/loop.ts. Three parts carry the idea: the tools array (what the model may do), the loop (how real results flow back), and the step cap (so a confused model cannot circle forever).

Why people are suddenly talking about agents

The idea is decades old. What changed is that the pieces became dependable:

  • Tool calls got reliable. Models now produce structured calls that code can execute, and they read error messages to try again.
  • Loops became affordable. A job can take ten model calls, and lower prices plus faster models made that practical.
  • Shared plumbing. Function calling is everywhere, and open protocols like MCP (introduced by Anthropic in late 2024) let one agent talk to many tools.
  • Visible results. Coding agents that edit files, run tests and fix their own failures showed developers finished work instead of suggestions.

Agents still fail: the wrong tool, repeated steps, a confident answer to the wrong task. That is why limits, logging and human approval are part of the job.

The mistake I made first

My first support-style assistant kept inventing delivery dates when I tested it. I blamed the system prompt and kept rewriting it. The real problem was that the model had no way to look anything up. One lookup tool fixed what no amount of prompt rewriting had.

Three things I watch for now:

  • Calling every fixed script an agent. A fixed sequence of model and function calls is a workflow. It is often the better design, but it debugs differently.
  • No step limit. A stuck model can loop and spend your API budget while you sleep.
  • Write access too early. Start read-only and add human approval before anything irreversible.

What's next

This is the first post in a series where I build agents step by step, from how they are put together to running one in production. I write each post in English and Bangla, and the original lives on my blog: What Is an AI Agent, Really?

What was the first thing you tried to make an agent do?

Top comments (0)