Sub topic 15
Scheduling, logging and cost control
A report agent that only runs when someone remembers to start it saves little effort. This chapter covers three things that let an agent run unattended: a schedule that triggers it safely, logs that show what it did, and cost limits that stop a bad run from becoming an expensive one.
It assumes you have read the chapters on the agent loop and on verification. You should be comfortable reading Python, JSON lines, and a basic cron expression.
Scheduling an agent run
A schedule is a trigger. It starts the same job at a set time, such as every Monday at 06:00. The usual tools are cron on a server, a managed scheduler in your cloud provider, or a workflow tool. The agent code does not change with the tool. Three rules matter more than the tool.
- Pass the time window in as an argument. A job that computes "last week" from the current clock gives a different answer when you rerun it on Wednesday. A job given
--week-ending 2026-11-22gives the same answer every time. - Make runs idempotent. An idempotent job can run twice and leave the same result. Write the report to a path that contains the window, such as
reports/2026-11-22.md, instead of appending to a shared file. Retries and manual reruns then replace output instead of duplicating it. - Prevent overlapping runs. If Monday's run is still going when a retry starts, both may publish. Take a lock before starting, for example by creating a lock file that fails if it already exists, and release it when the run ends.
A cron entry that follows these rules looks like this:
0 6 * * 1 cd /srv/reports && python weekly_report.py --week-ending 2026-11-22 >> logs/cron.out 2>&1In practice a wrapper script computes the date and passes it in. Cron uses the server's time zone, which may differ from the time zone of your ad platform's reporting day. Ad platforms often finalize the previous day's numbers late, so schedule the run after that point and state the data cutoff inside the report.
Logging what the agent did
A report that turns out wrong is only fixable if you can reconstruct the run. A chat transcript is not enough. Write one structured record per event as JSON lines (one JSON object per line), so you can filter them with ordinary tools.
Each record should carry these fields:
| Field | Purpose |
|---|---|
| `run_id` | Ties every event in one run together |
| `ts` | UTC timestamp, so you can order events and measure delays |
| `kind` | The event type: `tool`, `usage`, `aborted`, `final` |
| `name`, `ok`, `ms` | Which tool ran, whether it succeeded, and how long it took |
| `input_tokens`, `output_tokens`, `cost` | What each model call consumed |
Log which tools were called and with which argument names. Avoid logging full argument values or raw tool results when they contain customer data. The privacy chapter's rules apply to logs too. A log file often has weaker access control than the CRM it came from, so a copied email address in a log is a leak. Store a row count or a content hash instead of the rows.
Also log the model name and prompt version. When quality changes between two weeks, these are the first things to compare.
Controlling cost
Hosted models charge per token, separately for input and output. An agent loop resends the growing message history on every step, so input cost grows with each step. A loop that wanders through ten steps costs far more than ten times a single call.
Four controls work together:
- Step limit. The loop already has
max_steps. It is the first guard against runaway loops. - Budget per run. Add up the cost after each model call and abort when the total passes a fixed cap. This catches a run that stays under the step limit but sends huge inputs.
- Smaller inputs. Have tools return summaries such as the output of
campaign_metrics, not raw rows. Fewer tokens go in, and the model has fewer numbers to misquote. - Cheaper models for easy steps. Extraction and formatting often work on a smaller model. Reserve the larger model for the analysis narrative, and confirm on your own evaluation set that quality holds.
The sketch below combines the log and the budget. The prices are placeholders. Take real ones from your provider's price list.
import json
import time
import uuid
from datetime import datetime, timezone
PRICE_PER_1K = {"input": 0.003, "output": 0.015} # placeholder prices
class BudgetExceeded(RuntimeError):
pass
class RunLog:
def __init__(self, path, max_cost):
self.path = path
self.run_id = uuid.uuid4().hex[:8]
self.max_cost = max_cost
self.cost = 0.0
def event(self, kind, **fields):
record = {
"ts": datetime.now(timezone.utc).isoformat(),
"run_id": self.run_id,
"kind": kind,
**fields,
}
with open(self.path, "a", encoding="utf-8") as f:
f.write(json.dumps(record) + "\n")
def add_usage(self, input_tokens, output_tokens):
step_cost = (
input_tokens / 1000 * PRICE_PER_1K["input"]
+ output_tokens / 1000 * PRICE_PER_1K["output"]
)
self.cost += step_cost
self.event(
"usage",
input_tokens=input_tokens,
output_tokens=output_tokens,
cost=round(step_cost, 5),
total_cost=round(self.cost, 5),
)
if self.cost > self.max_cost:
raise BudgetExceeded(
f"run cost {self.cost:.3f} exceeds budget {self.max_cost:.2f}"
)
def logged_tool(log, name, fn):
"""Wrap a tool so each call is logged without recording argument values."""
def wrapper(**kwargs):
start = time.monotonic()
try:
result = fn(**kwargs)
except Exception as exc:
log.event("tool", name=name, ok=False, error=type(exc).__name__,
arg_keys=sorted(kwargs))
raise
log.event("tool", name=name, ok=True, arg_keys=sorted(kwargs),
ms=round((time.monotonic() - start) * 1000, 1))
return result
return wrapper
log = RunLog("agent_runs.jsonl", max_cost=0.20)
tool = logged_tool(
log, "campaign_metrics",
lambda rows: {"clicks": sum(r["clicks"] for r in rows)},
)
try:
for step in range(1, 6):
tool(rows=[{"clicks": 200}, {"clicks": 50}])
log.add_usage(input_tokens=20000, output_tokens=1000)
except BudgetExceeded as exc:
log.event("aborted", reason=str(exc))
print("stopped:", exc)Each simulated step costs 0.075, so the third step brings the total to 0.225. That passes the 0.20 cap, and the script prints stopped: run cost 0.225 exceeds budget 0.20. The file agent_runs.jsonl then holds the tool events, the usage events and the aborted event, all sharing one run_id.
The check runs after the spend, so a run can overshoot by one call. For a stricter cap, estimate the next call's cost before making it.
The shape of a scheduled run
Release the lock in every branch, including failures. A stale lock silently blocks all future runs, so give it an expiry or check its age.
What to monitor
Logs are only useful if something reads them. Turn them into a few numbers and alerts:
- Run did not happen. The most common failure is silence. Alert when no
finalevent arrives by the expected time. - Cost per run. Track the median and alert on a run above twice the median.
- Steps per run. A rising average often means a tool is returning errors the model keeps retrying.
- Tool error rate. A burst of failures from one tool usually means an expired API token or a changed schema.
- Verification flags. Count unsupported numbers per report. A sudden rise points to a prompt or data change.
Send alerts to a channel a person watches, and include the run_id so they can find the log lines.
Common mistakes
- Computing the date window inside the job, so reruns produce different reports.
- Retrying automatically with no cap. A failing job that retries every five minutes can spend a full day's budget.
- Logging full prompts that contain customer records.
- Setting one budget for all runs. A monthly summary legitimately costs more than a daily check, so budget per job type.
- Letting a scheduled run publish directly. Scheduling removes the person who would notice a problem, so keep the human review step from the previous chapters.
Exercise
A weekly report job fails at 06:00 because an API token expired. The scheduler retries every 5 minutes with no limit, and each attempt calls the model before the failing tool. Name two controls from this chapter that would limit the damage, and say what each one does.
Show answer
A per-run budget and a step limit stop one attempt from running long or sending large inputs. A retry cap (for example three attempts with growing delays) stops the job from repeating forever. Tool error logging and a "no final event by expected time" alert also tell a person about the expired token quickly. Any two of these controls, with their effects, answer the question. Checking the token before the first model call would also avoid paying for doomed attempts.
Exercise
Why does the sketch log arg_keys instead of the argument values, and what would you log if you needed to know how much data a tool call handled?
Show answer
Argument values may contain customer data, and log files usually have weaker access control than the source systems. Logging only the key names records which tool was called and how, without copying the data. To measure data volume, log a row count or a hash of the content instead of the rows themselves.