The more autonomy you give an agent swarm, the more you need to bound it. A manager agent that plans its own work, a reviewer that can send work back indefinitely, or a self-improving swarm that writes new skills is powerful, and it is also how teams end up with a surprise LLM bill or an agent that emailed a customer something it should not have.

This guide covers the five guardrails every production agent swarm needs, with Java code for each using SwarmAI:

  1. A hard budget on tokens and cost
  2. Limits on loops and turns
  3. Least-privilege tool permissions
  4. Tool hooks that can inspect and block actions
  5. Human approval at the points that matter

New to agent swarms? Start with What Are Agentic Swarms?.

1. Cap tokens and cost with a budget policy

Autonomous agents decide how many model calls to make. Without a ceiling, a review loop that never converges or a manager that keeps creating work can spend far more than you expect.

A BudgetPolicy sets a token limit, a cost limit in US dollars, a warning threshold and what to do when the limit is reached:

BudgetPolicy budgetPolicy = BudgetPolicy.builder()
        .maxTotalTokens(1_000_000)
        .maxCostUsd(10.00)
        .onExceeded(BudgetPolicy.BudgetAction.HARD_STOP)
        .warningThresholdPercent(75.0)
        .build();

Swarm swarm = Swarm.builder()
        .agents(List.of(researcher, writer))
        .tasks(List.of(research, report))
        .process(ProcessType.SEQUENTIAL)
        .budgetTracker(new InMemoryBudgetTracker(budgetPolicy))
        .budgetPolicy(budgetPolicy)
        .build();

There are two actions:

  • HARD_STOP aborts the run with a BudgetExceededException when a limit is hit. Use it in production.
  • WARN logs and continues. Use it while you are still learning what a normal run costs.

The same policy can be declared in the YAML DSL:

budget:
  maxTokens: 300000
  maxCostUsd: 5.0
  onExceeded: WARN

After a run, SwarmOutput.getTotalTokens() and estimateCostUsd(model) tell you what it actually cost, which is the data you need to set realistic limits.

2. Bound every loop

Every loop in an autonomous system needs an exit that does not depend on the model agreeing to stop.

  • Agent turns. Agent.builder().maxTurns(3) caps how many reasoning and tool-calling turns one agent takes on a task.
  • Rate. maxRpm(20) on an agent or a swarm caps requests per minute, which protects you from provider rate limits as well as cost.
  • Wall-clock time. maxExecutionTime(...) on an agent sets a time limit in milliseconds. Tasks accept a maxExecutionTime too.
  • Review cycles. Iterative and self-improving processes take config("maxIterations", n). The self-improving process also has a hard ceiling of 20 iterations whatever you configure.
  • Fan-out. The swarm process takes config("maxParallelAgents", n), and the parallel process takes maxConcurrentLlmCalls.
Agent writer = Agent.builder()
    .role("Content Writer")
    .goal("Write clear, accurate reports")
    .backstory("Turns research into well-structured articles.")
    .chatClient(chatClient)
    .maxTurns(3)
    .maxRpm(20)
    .build();

3. Give each agent the least privilege it needs

Tools are where agents touch the real world, so tools are where most risk lives. In SwarmAI every tool declares a PermissionLevel. The levels are ordered from least to most privileged, and an agent's permission mode is the highest level of tool it may call:

Permission levelMeaningTypical tools
READ_ONLYSearch, query and fetch onlyWikipedia, arXiv, web fetch, database reads
WORKSPACE_WRITECan modify files, databases or workspace stateFile writers, repository updates
DANGEROUSPotentially destructive or irreversibleShell commands, network calls, deletions
REQUIRES_APPROVALNeeds approval through governance gates before executionProduction deployments, external calls with side effects

A research agent should never be able to write anything:

Agent researcher = Agent.builder()
    .role("Research Analyst")
    .goal("Find accurate, up-to-date information")
    .backstory("Experienced researcher who verifies facts.")
    .chatClient(chatClient)
    .tool(wikipediaTool)
    .permissionMode(PermissionLevel.READ_ONLY)
    .build();

Set the permission mode explicitly on every agent. An agent built without one can use every tool you assign to it, and tools above its mode are dropped (with a warning in the log) only when a mode is set.

Splitting a swarm into agents with narrow roles is itself a security measure: the agent that reads untrusted web content is not the agent that can write to your database.

4. Inspect and block tool calls with hooks

Permission levels are coarse. For finer control, attach a ToolHook to an agent. It runs before and after every tool call, sees the tool name, parameters, output and the agent that made the call, and can allow, warn, block or rewrite:

// databaseTool stands for any SQL tool whose input parameter is "query".
ToolHook blockDeletes = new ToolHook() {
    @Override
    public ToolHookResult beforeToolUse(ToolHookContext ctx) {
        String sql = String.valueOf(ctx.inputParams().get("query"));
        if (sql.toUpperCase().contains("DELETE")) {
            return ToolHookResult.deny("DELETE statements are not allowed for this agent");
        }
        return ToolHookResult.allow();
    }
};

Agent analyst = Agent.builder()
    .role("Data Analyst")
    .goal("Answer questions from the sales database")
    .backstory("You write careful, read-only SQL.")
    .chatClient(chatClient)
    .tool(databaseTool)
    .toolHook(blockDeletes)
    .build();

Hooks are also the right place for audit logging (record every call with ctx.agentId() and ctx.toolName()), for redacting sensitive data from tool output with ToolHookResult.withModifiedOutput(...), and for rate limiting expensive APIs. In the YAML DSL the built-in hook types are audit, sanitize, rate-limit and deny.

5. Put a human in the loop where it matters

Some decisions should not be made by a model alone: publishing, spending money, changing production systems, contacting customers. SwarmAI has two mechanisms for human approval, at different granularities.

Approval gates on a swarm

An ApprovalGate blocks the workflow until it is approved, rejected or times out. It has a trigger, a timeout and an ApprovalPolicy that says how many approvals are needed, from which roles, and whether a timeout counts as approval:

ApprovalGate signOff = new ApprovalGate(
        "final-sign-off",
        "Editorial sign-off",
        "An editor must approve the report before it is released",
        GateTrigger.AFTER_TASK,
        Duration.ofMinutes(30),
        new ApprovalPolicy(1, List.of("editor"), false));

WorkflowGovernanceEngine governance =
        new WorkflowGovernanceEngine(new ConsoleApprovalGateHandler(), eventPublisher);

Swarm swarm = Swarm.builder()
        .agents(List.of(researcher, writer))
        .tasks(List.of(research, report))
        .process(ProcessType.SEQUENTIAL)
        .governance(governance)
        .approvalGate(signOff)
        .build();

A rejection or a timeout (with autoApproveOnTimeout set to false) throws a GovernanceException, so the result is never used without approval. ConsoleApprovalGateHandler asks for approval in the terminal, which is useful during development. In production you implement ApprovalGateHandler to route the request to your own system, such as a Slack message, a ticket or an internal approval page.

Be precise about when swarm-level gates fire. BEFORE_TASK gates are checked for each task before the swarm starts running, so they act as an approval to start. AFTER_TASK gates are checked once the run has finished, so they act as a sign-off before the result is used. They do not pause the swarm between two tasks.

Pausing between steps with a graph

When a human needs to review an intermediate result, for example a draft before it is published, use the graph API. SwarmGraph supports checkpoints and interruptBefore("publish"), which saves the workflow state and stops before the named node. The workflow resumes from the checkpoint once a person has reviewed it, so nothing that ran before the pause is repeated.

The human approval gate example shows a graph workflow with a review step in the middle.

Observe everything

Guardrails only help if you can see when they trigger. SwarmAI publishes events for each step of a swarm through Spring's ApplicationEventPublisher, exports metrics through Micrometer with the swarm prefix, and can trace tool calls and agent decisions and record runs for replay. These are switched on with the swarmai.observability properties, for example tool-tracing-enabled and decision-tracing-enabled.

At a minimum, log token usage per run, budget warnings, every tool call made by an agent with write permissions, and every approval decision.

A production checklist

Before an autonomous swarm goes live, check that:

  • Every swarm has a BudgetPolicy with HARD_STOP and limits based on measured runs
  • Every agent has maxTurns, and every review loop has maxIterations
  • Every agent has the lowest PermissionLevel its role needs
  • Agents that read untrusted content cannot use write tools
  • Irreversible actions (publish, pay, send, deploy) sit behind an approval gate or a graph interrupt
  • Tool calls by write-capable agents are audit-logged through a hook
  • Token usage and cost per run are monitored and alerted on

Learn more

SwarmAI is open source under the Apache 2.0 licence. Star SwarmAI on GitHub if you are building governed agent systems on the JVM.