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

# Agent cost control

> Wire PRYSM's AgentGuard into LangChain, CrewAI, AutoGen, and the OpenAI Agents SDK — hard spending ceilings enforced at the infrastructure layer.

PRYSM's **AgentGuard** gives autonomous agents a hard spending ceiling that cannot be
exceeded — not "+5% tolerance", not soft limits agents work around, but a hard cap
enforced before any model call is made.

## How AgentGuard works

Every agentic run through PRYSM's `/v1/agent/run` endpoint:

1. **Sets a hard ceiling** (`max_cost_usd`). The run stops immediately if spend would exceed it.
2. **Auto-downshifts** intensity (Laser → Halo → Foton) under budget pressure instead of overspending.
3. **Emits `X-Prysm-Budget-Remaining`** on every response — agents can read this to self-regulate.
4. **Returns a PrysmProof v2 trajectory** — a cryptographic receipt of every step, spend, and model used.

For single-request LLM calls (non-agentic), pass `X-Max-Cost-USD` as a request header
to cap individual completions.

***

## LangChain

### Per-request cap

```python theme={null}
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    base_url="https://api.prysm1.com/v1",
    api_key="prysm_sk_your_key",
    model="auto",
    default_headers={
        "X-Max-Cost-USD": "0.005",   # This call can never exceed $0.005
    },
)

response = llm.invoke("Summarize the quarterly report in 3 bullet points")
print(response.response_metadata)   # Includes prysm.routing, prysm.cost, prysm.proof
```

### Cap in a LangChain agent

```python theme={null}
from langchain_openai import ChatOpenAI
from langchain.agents import create_react_agent, AgentExecutor
from langchain.tools import Tool

llm = ChatOpenAI(
    base_url="https://api.prysm1.com/v1",
    api_key="prysm_sk_your_key",
    model="auto",
    default_headers={"X-Max-Cost-USD": "0.01"},
)

tools = [Tool(name="search", func=lambda q: "...", description="Web search")]
agent = create_react_agent(llm, tools, prompt=...)
executor = AgentExecutor(agent=agent, tools=tools, max_iterations=10)
result = executor.invoke({"input": "Research the top 5 AI companies"})
```

### Reading `X-Prysm-Budget-Remaining`

```python theme={null}
import httpx
from langchain_openai import ChatOpenAI

class BudgetCheckTransport(httpx.HTTPTransport):
    def handle_request(self, request):
        response = super().handle_request(request)
        remaining = response.headers.get("X-Prysm-Budget-Remaining")
        if remaining and float(remaining) < 0.01:
            print(f"[cost-guard] budget almost exhausted: ${remaining} remaining")
        return response

llm = ChatOpenAI(
    base_url="https://api.prysm1.com/v1",
    api_key="prysm_sk_your_key",
    model="auto",
    http_client=httpx.Client(transport=BudgetCheckTransport()),
)
```

***

## CrewAI

### Per-agent cost guard

```python theme={null}
from crewai import Agent, Task, Crew
from langchain_openai import ChatOpenAI

def make_agent(role, goal, backstory, max_cost_per_call=0.005):
    llm = ChatOpenAI(
        base_url="https://api.prysm1.com/v1",
        api_key="prysm_sk_your_key",
        model="auto",
        default_headers={"X-Max-Cost-USD": str(max_cost_per_call)},
    )
    return Agent(role=role, goal=goal, backstory=backstory, llm=llm)

researcher = make_agent("Researcher", "Find top AI startups", "...", max_cost_per_call=0.003)
writer     = make_agent("Writer",     "Write the report",      "...", max_cost_per_call=0.015)

crew = Crew(
    agents=[researcher, writer],
    tasks=[
        Task(description="Research AI startups", agent=researcher, expected_output="List of 5"),
        Task(description="Write report",          agent=writer,     expected_output="2-page report"),
    ],
)
result = crew.kickoff()
```

### Total crew budget via PRYSM agentic run

```python theme={null}
import openai

client = openai.OpenAI(base_url="https://api.prysm1.com/v1", api_key="prysm_sk_your_key")

run = client.chat.completions.create(
    model="auto",
    messages=[{"role": "user", "content": "Research AI startups and write a report"}],
    extra_body={
        "agent": True,
        "max_cost_usd": 0.10,   # Hard ceiling for the entire crew run
        "max_steps": 20,
    },
)
prysm = run.model_extra.get("prysm", {})
print(f"Spent: ${prysm.get('cost', {}).get('total_usd', 0):.4f}")
print(f"Trajectory proof: {prysm.get('trajectory_proof')}")
```

***

## AutoGen

### Cost-limited agent

```python theme={null}
import autogen

config = {
    "model": "auto",
    "api_key": "prysm_sk_your_key",
    "base_url": "https://api.prysm1.com/v1",
    "default_headers": {"X-Max-Cost-USD": "0.01"},
}

assistant = autogen.AssistantAgent("assistant", llm_config={"config_list": [config]})
user_proxy = autogen.UserProxyAgent(
    "user", human_input_mode="NEVER", max_consecutive_auto_reply=5, code_execution_config=False
)
user_proxy.initiate_chat(assistant, message="What are the main AI routing strategies?")
```

### Multi-agent setup with per-role budgets

```python theme={null}
import autogen

def make_config(max_cost: float) -> dict:
    return {"config_list": [{
        "model": "auto",
        "api_key": "prysm_sk_your_key",
        "base_url": "https://api.prysm1.com/v1",
        "default_headers": {"X-Max-Cost-USD": str(max_cost)},
    }]}

planner  = autogen.AssistantAgent("planner",  llm_config=make_config(0.002))
coder    = autogen.AssistantAgent("coder",    llm_config=make_config(0.015))
reviewer = autogen.AssistantAgent("reviewer", llm_config=make_config(0.010))
```

***

## OpenAI Agents SDK

```python theme={null}
from openai import OpenAI
from agents import Agent, Runner

client = OpenAI(
    base_url="https://api.prysm1.com/v1",
    api_key="prysm_sk_your_key",
    default_headers={"X-Max-Cost-USD": "0.02"},
)

agent = Agent(name="assistant", instructions="Be helpful and concise.", model="auto", client=client)
result = Runner.run_sync(agent, "Explain quantum computing in 3 sentences")
print(result.final_output)
```

***

## Recommended patterns

| Pattern                | When to use                          | Mechanism                                  |
| ---------------------- | ------------------------------------ | ------------------------------------------ |
| Per-request cap        | Simple chain — one LLM call per step | `X-Max-Cost-USD` header                    |
| Per-run cap            | Multi-step autonomous run            | `max_cost_usd` in request body             |
| Budget-remaining guard | Agent loop that should self-stop     | `X-Prysm-Budget-Remaining` response header |
| BRAIN.md routing lock  | Cost ceiling by intent class         | `max_cost_per_request` in BRAIN.md         |

### Safe default BRAIN.md for agents

```yaml theme={null}
max_cost_per_request: 0.005
rules:
  - when: "code"
    model: "deepseek-v3.2"
  - when: "analysis"
    model: "gpt-5-mini"
fallback: "deepseek-v3.2"
```

Set `auto_downgrade: true` in your plan settings so PRYSM falls to the next cheaper tier
rather than failing the request when a model would exceed the cap.

***

## See also

* [AgentGuard concept](/concepts/agentguard) — how cap enforcement works at the infrastructure layer
* [PrysmProof v2](/concepts/prysmproof#trajectory-proof-v2) — cryptographic trajectory receipts for agentic runs
* [BRAIN.md reference](/concepts/brain-md) — declarative cost and routing configuration
* [POST /v1/agent/run](/api-reference/agents) — full agentic run API reference
