Skip to main content

How to Build Your First AI Marketing Agent

How to build an AI marketing agent safely: a read-only budget-pacing monitor with the full tested script, least privilege, idempotent runs and a rollback test.

Robbie Jack

Founder · 10 min read

Share
Published
Updated
Last verified

The safest way to build your first AI marketing agent is to give it one job it can only read and recommend on. It shouldn’t pause campaigns, move budgets or publish creative; it should read synthetic data, produce a recommendation for a person to review, and prove its controls work before it ever touches a live account.

This tutorial builds a read-only budget-pacing monitor in a sandbox, with the complete, tested script to download in step 5 and a bounded model step in step 6. You get the operating pattern without putting a live ad-account credential anywhere near it. Keep the same boundaries if the workflow later connects to a vendor API.

Safe Tutorial: A Read-Only Budget-Pacing Monitor

The monitor has one job:

Given approved test rows for one account and one day, identify campaigns pacing outside their configured range and write a proposal for human review.

It may read a local test fixture and write a local proposal log. It may not call an ad platform, change a campaign, send a message, or read any other directory.

The OpenAI agent-building guide describes agents as models running workflows through tools and instructions, and recommends layered guardrails plus human intervention for high-risk actions. This tutorial applies those patterns, but I’m reasoning from how the architecture is built rather than from a test in your environment, so verify the safety claims below where you actually run them.

1. Create a Sandbox and Test Data

Create a disposable project with no production credentials and no customer data:

budget-monitor/
├── fixtures/
│   └── pacing.json
├── output/
│   └── proposals.jsonl
├── policy.json
└── run-monitor.ts

Use synthetic fixture data in fixtures/pacing.json:

[
  {
    "accountId": "sandbox-account",
    "campaignId": "campaign-a",
    "date": "2026-07-27",
    "dailyBudget": 10000,
    "spendToNow": 6200,
    "dayElapsed": 0.5,
    "dataFreshAt": "2026-07-27T12:00:00-06:00"
  },
  {
    "accountId": "sandbox-account",
    "campaignId": "campaign-b",
    "date": "2026-07-27",
    "dailyBudget": 8000,
    "spendToNow": 4160,
    "dayElapsed": 0.5,
    "dataFreshAt": "2026-07-27T12:00:00-06:00"
  }
]

Store money in the smallest currency unit, keep timestamps explicit, and make freshness part of the input. Halfway through this synthetic day, campaign-a should have spent 5,000 units and has spent 6,200, which is 24% above linear pacing. Campaign-b should be at 4,000 and is at 4,160, 4% above. The monitor can flag the first gap. It can’t tell you overspending caused poor performance, and it shouldn’t pretend to.

Before you add a model, write deterministic tests:

  • valid rows produce the expected pacing calculation
  • unknown account IDs are rejected
  • stale or future-dated data stops the run
  • missing fields fail closed
  • the fixture cannot name a production account
  • no output is written when validation fails

A fixed rule handles the calculation. Bring in a model only to explain the evidence in plain language, or to classify an exception you’ve already bounded.

2. Grant Least Privilege

Define an explicit policy in policy.json:

{
  "version": 1,
  "allowedAccounts": ["sandbox-account"],
  "allowedReadPaths": ["fixtures/pacing.json", "policy.json"],
  "allowedWritePaths": ["output/proposals.jsonl"],
  "maxRowsPerRun": 100,
  "maxToolCalls": 3,
  "maxDataAgeMinutes": 60,
  "pacingTolerance": 0.15,
  "writeActionsEnabled": false
}

pacingTolerance is the agreed range: 0.15 flags anything more than 15% off linear pacing. maxDataAgeMinutes makes stale data a stop, not a warning. maxToolCalls caps the model step in step 6; the script itself never calls a model.

Enforce the policy in code outside the model. Resolve paths before access, reject anything outside the allowlist, and never load environment files into model context.

Least privilege means the workflow gets only the capability its current job needs. A prompt that says "do not change budgets" is a request rather than a permission boundary, so in this tutorial there’s no campaign-mutation tool and no platform token, and the model has no way to make that change.

If you later connect an ad API, create a separate read-only integration identity scoped to the approved test account wherever the vendor supports it. Don’t reuse an administrator’s credential. Vendor permission models and review requirements change, so check the current official docs before you connect anything.

3. Make Every Run Idempotent

Schedulers retry, networks time out after the work has already succeeded, and people click twice, so the monitor has to handle the same input more than once without producing contradictory proposals.

Build an operation key from stable inputs:

budget-pacing:{accountId}:{campaignId}:{date}:{dataFreshAt}:{policyVersion}

Before you append a proposal, check whether that key already completed. If it did, return the recorded result instead of writing a second one. The script below records the operation key, the input checksum, the policy version, a timestamp, the review status and the evidence fields. As the workflow grows, also record:

  • started and completed timestamps for the whole run
  • the disposition of every row: no issue, proposed, rejected, or failed
  • the model and instruction version, once a model runs
  • an error category for every failed run

Idempotency protects you from duplicate execution. It doesn’t make a bad proposal correct, which is why validation and approval still matter.

4. Add Monitoring and Approval

Emit structured events for run start, validation, tool call, proposal, approval state, and run end. Alert when:

  • data is stale or missing
  • an unknown account appears
  • a tool or row limit is reached
  • output cannot be written
  • a run remains incomplete
  • a proposal lacks required evidence

The proposal schema should make review easy:

{
  "operationKey": "budget-pacing:sandbox-account:campaign-a:2026-07-27:...",
  "status": "awaiting-human-review",
  "observation": "Spend is 24% above linear pacing at the fixture timestamp.",
  "proposedAction": "Investigate tracking, schedule, and campaign delivery.",
  "requestedMutation": null,
  "evidence": ["dailyBudget", "spendToNow", "dayElapsed", "dataFreshAt"]
}

The reviewer accepts the observation, rejects it, or asks for more evidence. Approval here means the proposal enters the decision log. It doesn’t unlock a campaign change, because nothing in this build can change a campaign. When a later version can change spend, the same review grows into a propose-then-approve gate, with the spend limits agreed before the first change.

NIST’s AI RMF core calls for defined human-AI roles, testing, production monitoring, and documented oversight. Make the reviewer a named owner with real authority, not a shared inbox.

5. Wire It Together: run-monitor.ts

The whole monitor is one file, run-monitor.ts, and it’s the exact file the tests run against. It reads the policy, refuses to run unless writeActionsEnabled is false, checks both file paths against the allowlist, validates every row before it writes anything, computes pacing with a fixed rule, skips any operation key it has already recorded, and appends one proposal per campaign outside the agreed range. It has no network code and no campaign-mutation path. It uses only Node’s standard library, so Node 24 runs the TypeScript file directly with no build step.

Run it from the project folder. Pass --as-of so the sandbox clock matches the fixture; without it, the run uses the current time:

$ node run-monitor.ts --as-of 2026-07-27T12:30:00-06:00
campaign-a: proposed (Spend is 24% above linear pacing at the fixture timestamp.)
campaign-b: within tolerance (4% above)

output/proposals.jsonl now holds one line, shown here formatted:

{
  "operationKey": "budget-pacing:sandbox-account:campaign-a:2026-07-27:2026-07-27T12:00:00-06:00:1",
  "status": "awaiting-human-review",
  "observation": "Spend is 24% above linear pacing at the fixture timestamp.",
  "proposedAction": "Investigate tracking, schedule, and campaign delivery.",
  "requestedMutation": null,
  "evidence": ["dailyBudget", "spendToNow", "dayElapsed", "dataFreshAt"],
  "inputChecksum": "ae1998fa45b120ea767aa566055d262b863cfec9fb3a998f55f8e22bc091e312",
  "policyVersion": 1,
  "recordedAt": "2026-10-13T00:54:13.917Z"
}

Run the same command again and the key is already there, so nothing new is written. Run it with no --as-of and the fixture is months old, so the run stops before it reads a single number:

$ node run-monitor.ts --as-of 2026-07-27T12:30:00-06:00
campaign-a: already recorded
campaign-b: within tolerance (4% above)
$ node run-monitor.ts
run stopped: row 0: stale data

That output is copied from running this exact file. The six tests from step 1 run against it, along with the duplicate run and the read-only refusal. Write yours before you change a line.

6. Add the Model Step

The script is deterministic on purpose, because a fixed rule should do the arithmetic. The model earns its place one step later, turning a proposal into the plain-language note a reviewer reads, and it should get exactly as much room as that job needs. Hand it the proposal and its evidence fields and nothing else: no file access, no other tools, and a hard cap on calls from the policy’s maxToolCalls. Ask for one short explanation in a fixed schema, then check what comes back in code before anyone sees it:

  • every number in the note matches a number the script computed
  • it names only evidence fields the proposal lists
  • it suggests no action the proposal didn’t
  • it fits the schema and the length limit

If any check fails, drop the note, show the script’s own observation instead, and log the failure so it becomes a case in the evaluation set below. That keeps the model where it’s useful, explaining evidence it didn’t compute, and out of the decision about what to propose. Any model provider works here, as long as the call sits behind the same allowlist as the rest of the run.

7. Prove Rollback Before Write Access

I don’t give a workflow write access until this drill has run clean. In the sandbox it means:

  1. preserve the fixture and policy version used by the run.
  2. copy the proposal log to a test backup.
  3. remove the latest test proposal.
  4. restore the backup.
  5. verify its checksum and idempotency index.
  6. record the drill result.

Run that drill before every material schema change. Test the kill switch too. In the script above it is the first check: unless writeActionsEnabled is false, the run stops before it reads the fixture. Once a workflow has a mutation path, any attempt to use it with the switch off has to fail before it makes an external call.

Don’t consider a live write tool until the read-only workflow has all of it: reliable evaluation evidence, clear ownership, a restricted test account, deterministic limits, approval for every proposed mutation, state verification, and a vendor-supported reversal path.

When you get to a budget mutation, the approval record names the exact campaign, the prior value, the new value, the expiry, and the reverse operation. Verification reads the platform state after the write. And you test rollback against the sandbox account, because inventing it during an incident is how the incident gets worse.

Evaluate Before Expanding

Build a small evaluation set with normal pacing, genuine anomalies, stale data, conversion lag, scheduled promotions, and malformed rows. Score:

  • calculation correctness
  • false alerts and missed alerts
  • evidence completeness
  • correct refusal on invalid scope
  • duplicate-run behavior
  • escalation when limits are reached

Review the failures and add cases before you add tools, and decide which work can run unattended only once the evaluation set gives you evidence for it. Don’t measure success by how often the agent acts: a read-only system that correctly refuses uncertain work is doing its job.

What Comes Next?

The next safe capability is usually another read tool, not a write tool: pull a second report, reconcile a first-party outcome, attach context from a running experiment. Every addition needs its own permission, fixture, evaluation, monitoring, and failure boundary.

What you’ve built is a small marketing harness: context, bounded tools, executable checks and a feedback record around one job. The broader agent architecture is in AI Agents Are Changing Growth Marketing, and as the workflow grows, keep the human responsibility split explicit.

Before an agent watches your Meta and Google acquisition, want to know what is holding it back? Get your free growth review.

Robbie Jack

Founder of GrowthMarketer. He co-founded TrueCoach, built its growth system and sold the company in 2020.

Skip the pitch. Get your free growth review.

Answer seven questions. Within two business days you get a written review of your ads, landing pages and tracking, with the first changes we’d make.