# AI Agent

> The AI Agent is a system where a language model works in a loop, choosing and using tools to complete multi-step tasks.

## What is an AI agent and how does it work?

The system where an LLM pursues a goal in a loop: it decides the next step, calls a tool such as search, a terminal or an API, reads the result and repeats until the task is done or a limit on steps or cost is reached. Used for coding, research and automation.

- Topic: AI Agents
- Type: concept

## Example

Wrong:

```js
while (true) {
  const res = await llm.generate({ messages, tools });
  if (!res.toolCalls.length) return res.text;
  messages.push(res.message, ...(await runTools(res.toolCalls)));
}
```

Right:

```js
for (let step = 0; step < MAX_STEPS; step++) {
  const res = await llm.generate({ messages, tools });
  if (!res.toolCalls.length) return res.text;
  messages.push(res.message, ...(await runTools(res.toolCalls)));
}
throw new Error(`Agent stopped after ${MAX_STEPS} steps`);
```

A step limit turns a possible endless tool loop into a clear, handled failure.

## Common mistakes

- An infinite loop that calls the same tool again and again.
- Giving an agent broad credentials and it deletes or changes real data.
- The context grows each step until it hits the limit.

## Key points

- The loop has a maximum number of steps and a time or cost limit, and stops on a clear condition.
- Tool errors are returned to the model as results, not thrown and lost.
- Actions that change or delete data require approval or run in a sandbox.
- Long tool outputs are trimmed before being added back to the context.

## Interview questions

### What is the difference between an AI agent and a chatbot?

A chatbot replies to messages. An agent runs in a loop, calling tools and acting on their results until the task is done.

### When should I not use an AI agent?

When the steps are known in advance. A fixed workflow is cheaper, faster and easier to test.

### How do I stop an agent from doing damage?

Give it minimal permissions, run risky actions in a sandbox, and require human approval for changes that are hard to undo.

## Related cards

- [Tool Calling](https://wonderium.dev/ai/tool-calling.md)
- [ReAct Pattern](https://wonderium.dev/ai/react-pattern.md)
- [Agentic Workflow](https://wonderium.dev/ai/agentic-workflow.md)
- [Agent Permissions](https://wonderium.dev/ai/agent-permissions.md)
- [Context Compaction](https://wonderium.dev/ai/context-compaction.md)

---

- Level: [Artificial Intelligence](https://wonderium.dev/ai.md)
- HTML version: https://wonderium.dev/ai/ai-agent
- Last updated: 2026-11-25
