> ## 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.

# Building with AI agents

> How PRYSM keeps autonomous agents cost-safe, auditable, and easy to configure — from a single BRAIN.md to verifiable multi-step trajectories.

Building autonomous agents with PRYSM gives you three things that are hard to bolt on
after the fact: a **hard spend ceiling** that the model cannot talk its way around, a
**tamper-evident audit trail** of every step, and a **declarative config file** that
version-controls your routing preferences.

This guide walks through each, with patterns you can drop into any agent framework.

## The problem: agents call models you didn't expect

A single-prompt call is easy to reason about. An autonomous agent is not. One mis-routed
batch — a frontier model on a task that a budget model handles just as well — can dwarf
a month of ordinary usage. And you usually find out on the bill, not in the logs.

PRYSM solves this at three levels:

1. **Per-request cost caps** (AgentGuard) — PRYSM downgrades requests that would exceed
   your cap instead of running them at full price.
2. **Model blocks** — frontier models you never want an agent to touch are blocked
   server-side and routed around automatically.
3. **Verifiable trajectory** — every step is hashed into a chain; a tamper-evident
   `trajectory_proof` proves what ran, in what order, at what cost.

***

## 1 — Configure once in BRAIN.md

A [`BRAIN.md`](/concepts/brain-md) in your project root sets the routing preferences,
spend caps, and blocked models for every request from that context. It's checked into
version control and reviewed in pull requests — the spending policy is code, not a
checkbox buried in a dashboard.

```yaml BRAIN.md theme={null}
# Prefer cheap-but-great models, never exceed a cent per call,
# and keep frontier models off the table entirely.
max_cost_per_request: 0.01
monthly_budget: 100.00

rules:
  - when: "code"
    model: "deepseek-v3.2"
  - when: "writing"
    model: "claude-haiku-4.5"

blocked:
  - gpt-5.2-pro
  - claude-opus-4.6
  - grok-4.1-heavy

fallback:
  - deepseek-v3.2
  - claude-haiku-4.5
```

Scaffold a starter file from the terminal:

```bash theme={null}
prysm init
```

Validate it any time — works great in CI:

```bash theme={null}
prysm brain validate || exit 1
```

See [AgentGuard](/concepts/agentguard) for the full cap and block reference.

***

## 2 — Hard spend ceiling on agent runs

The [`/v1/agent/run`](/api-reference/agents) endpoint executes a goal as a bounded,
multi-step trajectory. Pass `max_cost_usd` and the run **provably cannot exceed it** —
not "+5%", at most that amount.

Before each step, [AgentGuard](/concepts/agentguard) binds the step's worst-case cost
against the remaining budget and only runs it if it fits, downshifting intensity
(Laser → Halo → Foton) under pressure rather than overspending.

<CodeGroup>
  ```python Python theme={null}
  from prysm import Prysm

  client = Prysm()
  run = client.agents.run(
      "Research the top 3 AI gateways, compare pricing, and draft a one-page brief.",
      max_cost_usd=1.00,
      policy="balanced",
  )
  print(run["status"])              # "complete" | "budget_exhausted" | "max_steps_reached"
  print(run["cost_consumed_usd"])   # always ≤ max_cost_usd
  print(run["trajectory_proof"])    # "sha256:..."
  print(run["output"])              # the consolidated result
  ```

  ```typescript Node theme={null}
  import { Prysm } from "@prysmai/sdk";

  const client = new Prysm();
  const run = await client.agents.run({
    goal: "Research the top 3 AI gateways, compare pricing, and draft a one-page brief.",
    maxCostUsd: 1.00,
    policy: "balanced",
  });
  console.log(run.status);             // "complete" | "budget_exhausted" | "max_steps_reached"
  console.log(run.cost_consumed_usd);  // always ≤ maxCostUsd
  console.log(run.trajectory_proof);   // "sha256:..."
  console.log(run.output);             // the consolidated result
  ```

  ```bash cURL theme={null}
  curl https://api.prysm1.com/v1/agent/run \
    -H "Authorization: Bearer $PRYSM_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "goal": "Research the top 3 AI gateways, compare pricing, and draft a one-page brief.",
      "max_cost_usd": 1.00,
      "policy": "balanced"
    }'
  ```
</CodeGroup>

The run never errors from budget pressure — it stops gracefully and returns the best
partial result so far. Check `status` to distinguish clean completion from a budget stop.

### Idempotency for retries

Pass `idempotency_key` to make a run retry-safe: a second request with the same key
returns the original result without spending again.

<CodeGroup>
  ```python Python theme={null}
  run = client.agents.run(
      "Draft a product changelog from the last 10 commits.",
      max_cost_usd=0.50,
      idempotency_key="changelog-v1.2.3",
  )
  ```

  ```typescript Node theme={null}
  const run = await client.agents.run({
    goal: "Draft a product changelog from the last 10 commits.",
    maxCostUsd: 0.50,
    idempotencyKey: "changelog-v1.2.3",
  });
  ```
</CodeGroup>

***

## 3 — Verify the trajectory

Every step is hashed into a chain. The run returns a `trajectory_proof` that commits to
every step — model, cost, intensity, input hash, output hash — in a tamper-evident bundle.
Reorder, drop, or edit any step and verification fails.

You can verify a trajectory **without a PRYSM account** — the verify endpoint is public:

<CodeGroup>
  ```python Python theme={null}
  from prysm.agent import Agents

  # Fetch the full audit trail:
  traj = client.agents.trajectory(run["run_id"])

  # Verify locally — no network call, no account needed:
  is_valid = Agents.verify(traj)
  print(is_valid)                    # True
  print(traj["trajectory_proof"])    # matches what was returned by the run
  ```

  ```bash cURL theme={null}
  # Grab the full trajectory:
  curl "https://api.prysm1.com/v1/agent/$RUN_ID/trajectory?full=true" \
    -H "Authorization: Bearer $PRYSM_API_KEY" | tee traj.json

  # Verify it (no auth required):
  curl https://api.prysm1.com/v1/agent/verify \
    -H "Content-Type: application/json" \
    -d "$(jq '.verify_request' traj.json)"
  ```
</CodeGroup>

See [PrysmProof](/concepts/prysmproof) for how the chain-of-custody is constructed.

***

## 4 — Preview costs before the agent runs

Use a dry-run route call to estimate what any prompt would cost before committing:

```python Python theme={null}
preview = client.route("draft a contract clause for a SaaS agreement", mode="quality")
print(preview["routing"]["model"])       # which model would run
print(preview["estimated_cost"]["total_usd_per_1k_tokens"])
```

Or from the CLI:

```bash theme={null}
prysm route "draft a contract clause for a SaaS agreement" --mode quality
```

This is especially useful for testing that a new `max_cost_per_request` cap behaves the
way you expect before deploying an agent.

***

## 5 — AI-to-AI distribution via MCP

If your agent is Claude Desktop, Cursor, or Windsurf, give it cost-aware routing as a
native tool — no API calls in application code required. Install the PRYSM MCP server and
the agent calls `prysm_route`, `prysm_usage`, and `prysm_savings` as tools with its own
key.

```json claude_desktop_config.json theme={null}
{
  "mcpServers": {
    "prysm": {
      "command": "npx",
      "args": ["-y", "@prysmai/mcp"],
      "env": { "PRYSM_API_KEY": "prysm_sk_your_key" }
    }
  }
}
```

See [MCP Server](/sdks/mcp) for the full tool list and Cursor/Windsurf setup.

***

## Reference

<CardGroup cols={2}>
  <Card title="AgentGuard" icon="shield-halved" href="/concepts/agentguard">
    Per-request caps, monthly budgets, and model blocks — enforced server-side.
  </Card>

  <Card title="Agent API" icon="code" href="/api-reference/agents">
    `/v1/agent/run`, trajectory retrieval, and the public verify endpoint.
  </Card>

  <Card title="PrysmProof" icon="fingerprint" href="/concepts/prysmproof">
    How every step is hashed into a tamper-evident chain.
  </Card>

  <Card title="BRAIN.md" icon="file-code" href="/concepts/brain-md">
    Version-controlled routing config — rules, blocks, caps, and fallback chains.
  </Card>
</CardGroup>
