Skip to main content
Documentation
Features

Agent Cost Control

Autonomous agent loops can spike costs unpredictably. Laghav tracks step-by-step agent costs in Redis and automatically blocks loops that exceed 50 steps in 2 hours.

Enabling agent tracking

agent.py
import uuid
from laghav import LaghavClient
client = LaghavClient()
agent_run_id = f"agent_{uuid.uuid4().hex[:8]}" # unique per agent run
def agent_step(prompt: str) -> str:
response = client.complete(
messages=[{"role": "user", "content": prompt}],
model="auto",
laghav_options={"agent_run_id": agent_run_id}
)
return response.choices[0].message.content
# Every call with same agent_run_id is tracked as one agent session
for step in range(100):
result = agent_step(f"Step {step}: continue research...")
# After step 50, Laghav returns 429 agent_loop_detected=True

Loop detection response

loop-429.json
{
error: "Agent loop limit exceeded",
code: "RATE_LIMIT_EXCEEDED",
agent_loop_detected: true,
agent_run_id: "agent_abc123",
steps_used: 51,
steps_max: 50,
window_hours: 2,
request_id: "lgh_req_xyz"
}

Agent run summary endpoint

bash
curl https://api.laghav.ai/api/agent/agent_abc123/summary \
-H "Authorization: Bearer lgh_live_xxx"
# Returns step-by-step log with cost per step
# {
# "agent_run_id": "agent_abc123",
# "total_steps": 23,
# "total_cost_usd": 0.184,
# "total_tokens_original": 18400,
# "total_tokens_compressed": 7200,
# "steps": [{ "step": 1, "tokens": 840, "cost_usd": 0.008, ... }, ...]
# }
Default limit: 50 steps / 2 hours
The loop guard applies per agent_run_id within a 2-hour sliding window. Contact support for higher limits on Business/Enterprise plans.