Sub topic 15
Scheduling, logging and cost control
This chapter assumes you have read the agent loop chapter and can read basic Python and JSON. It covers how to run a reporting agent on a schedule, how to record what it did, and how to stop it from spending more than you planned.
Why unattended runs need guardrails
When you run an agent by hand, you watch it. On a schedule, nobody does. A loop that retries a failing tool, or a prompt that grows with every step, can run all night. Three controls keep an unattended agent safe: a scheduler that starts runs predictably, logs that explain each run afterwards, and budgets that stop a run early.
Scheduling
Use the simplest scheduler that fits. A cron entry, a cloud scheduler, or a CI job all work. Match the schedule to when the data is final, not just to when readers want the report. Ad platforms often revise yesterday's numbers, so a Monday 07:00 weekly report is safer than a 00:05 daily one.
0 7 * * 1 /usr/bin/python3 /opt/reports/weekly_report.pyThis cron line runs the script at 07:00 every Monday. Make the job safe to repeat. Write output to a file named by date, and skip the run if that file already exists. Then a retry never sends two reports.
Logging each run
Log one JSON object per step, all sharing a run ID. Useful fields are the step number, the tool called, token counts, elapsed seconds, and cost. Do not log raw customer data. Log identifiers and counts instead. Privacy rules still apply to log files.
Enforcing a budget
Cost per step is tokens multiplied by the provider's price. The class below logs each step and raises an error once the total passes a limit. The prices are examples. Replace them with your provider's current rates.
import json
PRICE_PER_1K = {"input": 0.003, "output": 0.015} # example prices in dollars
class BudgetExceeded(Exception):
pass
class RunLog:
def __init__(self, run_id, max_cost):
self.run_id = run_id
self.max_cost = max_cost
self.total_cost = 0.0
def record_step(self, step, tool, input_tokens, output_tokens, seconds):
cost = (input_tokens / 1000) * PRICE_PER_1K["input"] \
+ (output_tokens / 1000) * PRICE_PER_1K["output"]
self.total_cost += cost
print(json.dumps({
"run_id": self.run_id,
"step": step,
"tool": tool,
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"seconds": seconds,
"cost": round(cost, 4),
"total_cost": round(self.total_cost, 4),
}))
if self.total_cost > self.max_cost:
raise BudgetExceeded(f"run {self.run_id} passed ${self.max_cost}")
log = RunLog("2026-11-26-weekly", max_cost=0.05)
try:
log.record_step(1, "campaign_metrics", 2000, 300, 1.4)
log.record_step(2, "campaign_metrics", 6000, 800, 2.1)
log.record_step(3, "draft_report", 9000, 1500, 4.0)
except BudgetExceeded as err:
print("stopped:", err)The third step pushes the total above $0.05, so the run stops and prints a message. In a real job, the except branch would send an alert.
Common cost levers
| Lever | Effect |
|---|---|
| Step limit (`max_steps`) | Caps loops that never reach a final answer |
| Smaller model for simple steps | Cuts price per token on routine work |
| Pass tool results, not raw tables | Keeps the prompt from growing each step |
| Cache repeated tool calls | Avoids paying twice for the same data |
Watching over time
Review the logs weekly at first. Track cost per run, steps per run, and the share of runs that hit a limit. A rising step count often means a tool is returning errors the agent keeps retrying. These numbers also feed the next chapter, where you compare cost against the manual baseline.
Exercise
A weekly report agent runs every Monday at 07:00. A transient network error makes the job restart twice. Name one design choice that prevents three copies of the report being sent, and one log field that helps you diagnose the extra runs.
Show answer
Make the job idempotent: write the report to a file named by date and skip the run if it already exists, so retries do nothing. A shared run ID, or a timestamp on each log line, lets you see the three starts and tell the runs apart.