> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.alfa.boosted.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.alfa.boosted.ai/_mcp/server.

# Agent usage monitoring

Monitor your agent's token consumption to understand usage patterns and optimize costs. Alfa provides two ways to track token usage: per-run token counts and historical usage data.

## Getting token usage from agent output

When you retrieve an agent's output, you'll also receive the token count for that specific run.

```python
import requests

BASE_URL = "https://alfa.boosted.ai/client"
API_KEY = "YOUR_API_KEY_HERE"

headers = {"x-api-key": API_KEY, "Content-Type": "application/json"}

def get_agent_output_with_usage(agent_id):
    """Retrieve agent results along with token usage information."""
    url = f"{BASE_URL}/get-agent-output/{agent_id}"
    
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        data = response.json()
        token_count = data.get("token_count")
        outputs = data.get("outputs", [])
        
        print(f"Agent run used {token_count} tokens")
        print(f"Generated {len(outputs)} outputs")
        
        return data
    else:
        print(f"Error: {response.status_code}, {response.text}")
        return None

# Get results and token usage for a completed agent
agent_id = "your-agent-id-here"
results = get_agent_output_with_usage(agent_id)
```

## Tracking historical usage

View your agent's token consumption over time to identify usage patterns and trends.

```python
from datetime import datetime, timedelta

def get_agent_usage_history(agent_id, from_date):
    """Get daily token usage history for an agent."""
    url = f"{BASE_URL}/get-agent-usage-history/{agent_id}/{from_date}"
    
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        data = response.json()
        usage_history = data.get("usage_history", [])
        total_runs = data.get("total_runs", 0)
        
        print(f"Total runs in period: {total_runs}")
        print("\nDaily usage breakdown:")
        
        for entry in usage_history:
            date = entry["date"]
            tokens = entry["tokens"]
            runs = entry["run_count"]
            print(f"{date}: {tokens} tokens across {runs} runs")
        
        return data
    else:
        print(f"Error: {response.status_code}, {response.text}")
        return None

# Get usage for the last 7 days
seven_days_ago = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d")
usage_data = get_agent_usage_history(agent_id, seven_days_ago)
```

### Example: Analyzing usage patterns

#### Collect usage data

Retrieve historical usage for analysis:

```python
# Get 30 days of usage data
thirty_days_ago = (datetime.now() - timedelta(days=30)).strftime("%Y-%m-%d")
usage = get_agent_usage_history(agent_id, thirty_days_ago)
```

#### Calculate averages

Analyze consumption patterns:

```python
if usage and "usage_history" in usage:
    history = usage["usage_history"]
    
    # Calculate daily averages
    total_tokens = sum(entry["tokens"] for entry in history)
    total_days = len(history)
    avg_tokens_per_day = total_tokens / total_days if total_days > 0 else 0
    
    print(f"Average daily usage: {avg_tokens_per_day:.0f} tokens")
    
    # Find peak usage day
    peak_day = max(history, key=lambda x: x["tokens"])
    print(f"Peak usage: {peak_day['tokens']} tokens on {peak_day['date']}")
```

> **Tip**
>
> Use the usage history data to identify optimal scheduling patterns and budget for token consumption in automated agents.