Sub topic 2
The Agent Loop: Plan, Act, Observe, Stop
Assume you know basic marketing metrics, Python, JSON, APIs, and the general role of a large language model (LLM). An AI agent is an LLM connected to tools. It repeats a controlled cycle until it has enough evidence to answer.
Plan, act, observe, stop
The model first plans the next useful action. It might decide to fetch campaign data or retrieve a product brief. It then acts by calling a tool. The system returns an observation, such as JSON from an advertising API. The model uses that observation to choose its next action or produce a final answer.
A stop condition prevents endless or expensive work. Common conditions include a final response, a maximum number of steps, or a failed tool call that requires human review.
Prompts and structured outputs
Give the model a narrow role, the available tools, required evidence, and a response schema. A structured output is data with a fixed shape, such as:
summaryfindingsriskssourcesnext_actions
Require the model to return valid JSON when another program will process the result. Also require each finding to include a source identifier. This makes missing evidence easier to detect.
Grounding findings in retrieved sources
Grounding means tying a response to retrieved, current information. Pass the tool result, source name, date range, and filters into the model context. Instruct the model to say “insufficient data” when a claim cannot be supported. Do not let it fill gaps with general knowledge.
Calculating metrics with code
Use deterministic code for arithmetic. The model can select the tool and interpret its result, but it should not calculate rates from memory.
def campaign_metrics(rows):
impressions = sum(r["impressions"] for r in rows)
clicks = sum(r["clicks"] for r in rows)
spend = sum(r["spend"] for r in rows)
conversions = sum(r["conversions"] for r in rows)
return {
"impressions": impressions,
"clicks": clicks,
"spend": round(spend, 2),
"conversions": conversions,
"ctr": round(clicks / impressions, 4) if impressions else None,
"cpc": round(spend / clicks, 2) if clicks else None,
"cpa": round(spend / conversions, 2) if conversions else None,
}
print(campaign_metrics([
{"impressions": 10000, "clicks": 200, "spend": 150.0, "conversions": 10}
]))Turning findings into a report
A report generator should receive verified metrics and sourced findings. Ask it to separate observations from recommendations. Before publishing, check every number against tool output and route unsupported claims to a person.
Exercise
Why should the model call a metrics tool instead of calculating CPA itself?
Show answer
Code gives repeatable arithmetic, handles zero denominators, and produces evidence that can be checked.