# 7. Agents

What an AI agent is, how the agent loop works, the main architectures (function calling, ReAct, plan-and-execute), tool design, limits, failure modes, and when not to use an agent.

Source: https://glamorous-boar.cloudvent.net/learn/agents/

---

## What an agent is

An **agent** is a system where a model **decides what to do next** in a loop: it looks at the goal and what it has learned so far, chooses an action (usually a tool call), observes the result, and repeats until it can answer or gives up. The defining property is that the **control flow is chosen by the model at run time**, not fixed by the developer.

<Diagram caption="The agent loop.">

```
flowchart LR
  G[Goal + context] --> M{Model decides}
  M -- tool call --> T[Execute tool]
  T -- observation --> M
  M -- final answer --> A[Answer]
  M -- limit reached --> P[Stop: fail or partial answer]
```

</Diagram>

### Workflows vs agents

A useful distinction (popularised by Anthropic's *Building effective agents*, 2024):

- **Workflows**: models and tools orchestrated through **predefined paths** (prompt chains, routing, parallel steps). Predictable, cheaper, easier to test.
- **Agents**: models **dynamically direct** their own process and tool use. Flexible for open-ended tasks, but costlier, slower and less predictable.

Most production systems are mostly workflows with an agent where flexibility is genuinely needed. AgenticMind lets you mix both on one canvas: a fixed pipeline with an Agent node in the middle.

## The agent loop in detail

1. Send the model: system instructions, the task, any history, and the **tool definitions**.
2. The model replies with either a **final answer** or one or more **tool calls**.
3. For each tool call: check the tool exists, **validate arguments** against its schema, check **permissions**, run it with a **timeout**, capture the result or error.
4. Append the tool results to the conversation and go to step 2.
5. Stop at a final answer, or when a **limit** is hit (turns, tool calls, tokens, cost, time).

Errors from tools are returned to the model as observations, not thrown: a good model reads *city must not be empty* and retries correctly.

## Architectures

### Native function calling

The model uses the provider's tool-calling API (chapter 3) and may request several calls in one turn, which run in parallel. The default for capable models: fast, reliable and structured.

### ReAct (Reason + Act)

**ReAct** (Yao et al., 2022) has the model write its reasoning and actions as text:

<CodeBlock language="text" filename="A ReAct trace" showCopy={false}>

```
Thought: I need the leave policy, then multiply by 3.
Action: search_documents
Action Input: {"query": "annual leave days per employee"}
Observation: [1] Every full-time employee receives 25 days of paid annual leave...
Thought: 25 days each. Now compute 25 * 3.
Action: calculator
Action Input: {"expression": "25 * 3"}
Observation: 75
Final Answer: Three full-time employees get 75 days of annual leave in total [1].
```

</CodeBlock>

Benefits: works with models without native tool calling; the reasoning is visible and auditable. Costs: parsing free text is fragile (the runtime must handle malformed replies), and it is usually slower than native calling.

### Plan-and-execute

First write a **plan** (a short list of steps), then **execute** each step (often with its own small tool loop) feeding earlier results forward, then **compose** the final answer. Plans make long tasks more coherent and let cheaper models execute steps. The risk is a bad plan; some variants re-plan after each step.

### Others you will hear about

- **Reflexion / self-correction loops**: the agent evaluates its own attempt and retries with lessons (chapter 9).
- **Tree search over actions**: explore several action sequences (LATS, combining MCTS with agents).
- **Multi-agent**: several specialised agents (chapter 8).

## Limits are not optional

Unbounded agents loop, overspend and run away. Every production agent needs:

| Limit | Why |
|---|---|
| Max turns | Stops endless reasoning loops |
| Max tool calls | Stops tool spam |
| Token budget | Bounds context growth and cost |
| Cost budget | Hard money ceiling |
| Per-tool timeout | One slow API cannot hang the run |
| Behaviour at the limit | Fail loudly, or return a partial answer with the reason |

Plus: tools with **least privilege** (allow-listed domains, read-only SQL, sandboxed code), **no automatic retry** of the agent as a whole (tools may have side effects), and **human approval** before irreversible actions.

## Designing tools for agents

The agent is only as good as its tools (see chapter 3): clear names and descriptions, small typed arguments, compact outputs, actionable errors, and marking **permanent** failures so the agent stops retrying a site that blocks bots. Fewer, well-described tools beat many overlapping ones.

## Common failure modes

| Failure | What it looks like | Fix |
|---|---|---|
| Tool avoidance | Answers from memory instead of searching or checking the date | Instructions to use tools; clearer descriptions; avoid very low reasoning effort |
| Tool thrashing | Calls the same failing tool repeatedly | Permanent-failure tracking; better errors; limits |
| Hallucinated tool results | Claims a tool said something it did not | Show raw results; ground the final answer; evaluate |
| Wrong arguments | Invalid JSON, wrong types | Schema validation with errors returned to the model |
| Context bloat | Huge tool outputs fill the window | Truncate and summarise tool results |
| Goal drift | Wanders off-task in long runs | Plans, critics, tighter instructions, fewer turns |
| Prompt injection via tools | A fetched page says *ignore your instructions* | Treat tool output as data; guardrails; least privilege |

## When not to use an agent

If you can draw the flowchart, build the flowchart. Use a fixed pipeline, a Router or a Tool Chain when the steps are known. Reach for an agent when the number and order of steps genuinely depend on what is found along the way.

## Try it in AgenticMind

- **Agent** node with `architecture`: `function_calling`, `react` or `plan_and_execute`; limits `max_turns`, `max_tool_calls`, `token_budget`, `cost_budget_usd`, `on_limit`.
- Tools: Knowledge Search, Calculator, Date & Time, Web Fetch, Memory, Code Interpreter, SQL, MCP Server, Subagent.
- **Tool Router** and **Tool Chain** for the cases that do not need a full loop.
- Template *Agent with tools*; expand *Used N tool calls* in Chat, or read `agent_turn` and `tool_call` events in the Trace.

See [Agents and tools](/agents/).

<Alert variant="tip" title="Key takeaways" text="An agent is a model choosing actions in a loop. Native function calling is the default architecture; ReAct makes reasoning visible; plan-and-execute adds structure for long tasks. Every agent needs hard limits, validated tool calls, least-privilege tools and a defined behaviour at the limit. If you can draw the flowchart, build a workflow instead."/>
