---
title: Cost Optimization
description: Budget management and image retention for cost optimization
---

# Cost Optimization Callbacks

Optimize agent costs with budget management and image retention callbacks.

## Budget Manager Callbacks Example

```python
from agent.callbacks import BudgetManagerCallback

agent = ComputerAgent(
    model="anthropic/claude-3-5-sonnet-20241022",
    tools=[computer],
    callbacks=[
        BudgetManagerCallback(
            max_budget=5.0,  # $5 limit
            reset_after_each_run=False,
            raise_error=True
        )
    ]
)
```

## Budget Manager Shorthand

```python
# Simple budget limit
agent = ComputerAgent(
    model="anthropic/claude-3-5-sonnet-20241022",
    max_trajectory_budget=5.0  # $5 limit
)
```

**Or with options:**

```python
# Advanced budget configuration
agent = ComputerAgent(
    model="anthropic/claude-3-5-sonnet-20241022",
    max_trajectory_budget={
        "max_budget": 10.0,
        "raise_error": True,  # Raise error when exceeded
        "reset_after_each_run": False  # Persistent across runs
    }
)
```

## Image Retention Callbacks Example

```python
from agent.callbacks import ImageRetentionCallback

agent = ComputerAgent(
    model="anthropic/claude-3-5-sonnet-20241022",
    tools=[computer],
    callbacks=[
        ImageRetentionCallback(only_n_most_recent_images=3)
    ]
)
```

## Image Retention Shorthand

```python
agent = ComputerAgent(
    model="anthropic/claude-3-5-sonnet-20241022",
    tools=[computer],
    only_n_most_recent_images=3  # Auto-adds ImageRetentionCallback
)
```

## Combined Cost Optimization

```python
agent = ComputerAgent(
    model="anthropic/claude-3-5-sonnet-20241022",
    tools=[computer],
    max_trajectory_budget=5.0,        # Budget limit
    only_n_most_recent_images=3,      # Image retention
    trajectory_dir="trajectories"     # Track spending
)
```

## Budget Manager Options

- `max_budget`: Dollar limit for trajectory
- `reset_after_each_run`: Reset budget per run (default: True)
- `raise_error`: Raise exception vs. graceful stop (default: False)
