> ## Documentation Index
> Fetch the complete documentation index at: https://docs.prysm1.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Cost-capping autonomous agents with AgentGuard

> Autonomous agents can run indefinitely without a cost ceiling. AgentGuard enforces a hard spend cap on every agent run — no matter what the agent does next.

Autonomous agents are powerful because they can take many actions in sequence. They're dangerous
for the same reason: a runaway loop, an unexpectedly expensive model call, or a buggy tool
invocation can send API costs spiraling.

AgentGuard is PRYSM's built-in cost-safety layer for multi-step agent runs. It enforces a hard
spend ceiling that the agent cannot exceed, regardless of how many steps it takes or which models
it calls.

## The problem: uncapped agent runs

```python theme={null}
# Without a cost ceiling, this could run forever
from openai import OpenAI
client = OpenAI()

def run_agent(goal: str):
    messages = [{"role": "user", "content": goal}]
    while True:
        resp = client.chat.completions.create(
            model="gpt-5.2-pro",   # Frontier model, every step
            messages=messages,
            tools=[...],
        )
        msg = resp.choices[0].message
        if msg.finish_reason == "stop":
            return msg.content
        messages.append(msg.model_dump())
        # Execute tool calls and append results...
        # → Cost is unbounded; a loop bug or long plan can spend $10+
```

## AgentGuard: hard stop at your ceiling

```python theme={null}
from prysm import Prysm

client = Prysm()

result = client.agents.run(
    goal="Research the top 5 open-source LLM inference frameworks and compare latency",
    max_cost_usd=0.50,   # Hard stop — this run cannot spend more than $0.50
    max_steps=20,        # Also cap the step count
)

print(result["output"])
print(f"Steps: {result['steps_taken']}")
print(f"Cost:  ${result['cost_usd']:.4f}")
print(f"Proof: {result['proof']['proof_hash']}")
# Steps: 9
# Cost:  $0.1234
# Proof: sha256:a1b2c3d4e5f67890
```

AgentGuard tracks the cumulative spend across every LLM call in the run. Before each new step,
it checks whether the remaining budget is enough to make a minimum-cost call. If not, it stops
the agent cleanly and returns what it has so far.

## The budget envelope

AgentGuard uses a conservative dual-budget strategy:

1. **Soft cap (80% of `max_cost_usd`)** — the router switches to the cheapest eligible model
   when spend crosses this threshold. This squeezes the last few steps into the cheapest
   possible tokens.

2. **Hard cap (100% of `max_cost_usd`)** — the run stops immediately. No more LLM calls are made.
   The agent returns a partial result with a `stopped_reason: "budget_exceeded"` flag.

```python theme={null}
result = client.agents.run(
    goal="Write and execute a full market analysis for EV batteries",
    max_cost_usd=1.00,
)

if result.get("stopped_reason") == "budget_exceeded":
    print("Agent hit the budget ceiling — partial result:")
    print(result["output"])
    print(f"Spent ${result['cost_usd']:.4f} of ${result['budget_usd']:.2f}")
else:
    print("Agent completed normally:")
    print(result["output"])
```

## Trajectory: see every step

```python theme={null}
result = client.agents.run(
    goal="Find and summarize the latest research on multi-agent systems",
    max_cost_usd=0.25,
)

for step in result["trajectory"]:
    print(f"Step {step['step']:2d} | {step['model']:25s} | ${step['cost_usd']:.5f} | {step['action'][:60]}")

# Step  1 | claude-sonnet-4.5         | $0.00120 | Plan: search for recent papers on multi-agent...
# Step  2 | sonar                     | $0.00080 | Web search: "multi-agent systems 2026"
# Step  3 | mistral-nemo              | $0.00002 | Classify relevance of 12 results
# Step  4 | claude-sonnet-4.5         | $0.00340 | Read and summarize top 3 papers
# ...
```

## BRAIN.md integration: repo-level cost ceiling

Set a default `max_cost_per_request` in `BRAIN.md` and AgentGuard picks it up automatically:

```yaml theme={null}
# BRAIN.md
max_cost_per_request: 0.05   # Each individual call capped at $0.05
```

```python theme={null}
# Agents also respect the BRAIN.md ceiling
result = client.agents.run(
    goal="Debug this failing test suite",
    max_cost_usd=0.50,        # Total run ceiling
    # Per-call ceiling comes from BRAIN.md: $0.05
)
```

## Verifiable proof of every run

AgentGuard produces a PrysmProof v2 receipt for the entire run, covering every step:

```python theme={null}
proof = result["proof"]
print(proof["models_used"])      # All models that ran in any step
print(proof["total_cost_usd"])   # Total spend (matches cost_usd in the result)
print(proof["steps_taken"])      # Number of steps executed
print(proof["proof_hash"])       # sha256:... — verifiable offline
```

Store this receipt in your audit log. You can verify it later via
`GET /v1/proof/{request_id}` (no API key required) or reconstruct the hash offline.
