# Build an agent

An agent combines model requests with application-controlled tools, state and stopping conditions.

Source: https://zrelay.net/docs/agents/build/

## The loop

```
1. Send the user task and your allowed tool schemas.
2. If the model returns text, present the result.
3. If it requests a tool, validate the name and arguments.
4. Check permissions and obtain approval for external effects.
5. Execute the permitted action and append the tool result.
6. Continue until completion or a time, step or spend limit.
```

## Keep reliable state

Record tool call identifiers and confirmed effects outside the model context. Avoid executing the same non-idempotent action twice after a timeout. Distinguish an incomplete inference response from a completed tool operation.

## Use the correct protocol

Start with [Tool calling](https://zrelay.net/docs/md/capabilities/tool-calling.md) and [Streaming](https://zrelay.net/docs/md/capabilities/streaming.md). Keep Messages, Chat Completions and Responses tool formats separate.

## Observe cost and failures

Keep `x-zrelay-request-id`, bound retries, and inspect [request history](https://zrelay.net/docs/md/api/credits.md) when the outcome or charge is unclear.
