2026-05-04 · 10 min read

How I Use AI to Optimize Meta Ads Campaigns

An autonomous Python agent manages my Meta Ads: monitoring spend, adjusting budgets, generating creative briefs, and reporting results via Telegram. Here is how it works.

Meta AdsAIadvertising

TL;DR: Bartosz Cruz built a 3,000-line Python agent that manages Meta Ads every 15 minutes - cutting manual work by 90%. It outperforms Meta's native tools by integrating Supabase business data. Full architecture and results below.

I built an autonomous Python agent that manages my Meta Ads campaigns across multiple accounts without daily manual involvement. It monitors performance every 15 minutes, adjusts budgets based on ROAS and CPA thresholds, generates creative briefs twice per week, tracks competitor ads in the Meta Ad Library, and sends structured daily reports to Telegram at 7:00 AM. The system runs on a Hetzner VPS via PM2 and connects directly to the Meta Marketing API - not through Meta's built-in Advantage+ tools, but through a custom optimization layer with business-specific rules that platform automation cannot replicate. As of May 2026, the agent operates across multiple client accounts managed through AI Business Lab LLC, the Dover, DE company behind this work.

The core motivation for building a custom agent rather than relying on Meta's native automation was control and cross-system intelligence. Meta's built-in tools optimize within the platform's own data - they have no visibility into which customer segments generate the highest lifetime value, which acquisition sources produce the lowest churn, or how campaign performance correlates with downstream business outcomes stored in a separate database. A custom agent connected to both the Meta API and Supabase business data makes budget allocation decisions that reflect actual business economics, not just on-platform conversion cost.

This approach also addresses a structural problem with platform-native automation: it is designed to maximize Meta's revenue, not the advertiser's margin. A custom agent with explicit business rules - ROAS floors, CPA ceilings, lifetime value weighting - optimizes for the metrics that determine whether a campaign is actually profitable for the business, not just whether it generates volume. That distinction produces meaningfully different budget allocation decisions at scale, particularly for businesses with wide variance in customer lifetime value across acquisition segments.

According to Meta's 2026 Marketing API documentation, advertisers using automated optimization tools see an average 27% improvement in cost per result compared to manual management. A WordStream study from November 2025 found that custom AI agents outperform Meta's built-in automation by 18% on average, particularly for businesses running multiple campaigns with complex optimization rules. My agent goes beyond Meta's built-in tools by adding custom logic, cross-campaign analysis, and direct integration with business outcome data that lives outside the Meta ecosystem entirely.

What the agent does

The agent operates across six distinct functions, each on its own schedule calibrated to the commercial rhythm of the task. Performance monitoring runs every 15 minutes because advertising performance can shift rapidly within a single day - a creative that performs well in the morning can exhaust its audience by afternoon, and a 15-minute polling interval catches these shifts before significant budget is wasted. Budget optimization runs twice daily to capture the morning and afternoon performance windows that reflect different audience behavior patterns across the day.

Creative brief generation runs twice per week rather than daily because creative testing requires a minimum data accumulation window to produce statistically meaningful signals. The agent analyzes top-performing ads over the preceding period, identifies patterns in hook structure, offer framing, visual format, and audience response, and produces a structured brief that Bartosz Cruz uses to direct the next round of creative production. This means creative strategy is data-driven at every cycle rather than based on intuition or competitor imitation alone.

The weekly competitor monitoring function adds a layer of market intelligence that most lean advertising operations skip entirely due to the manual effort required. By automating this scan, the agent delivers systematic competitive visibility at no additional time cost - a capability that previously required a dedicated analyst or simply went undone. Combined with the anomaly detection layer built into the daily reporting function, the agent provides both offensive intelligence (what competitors are testing) and defensive alerting (when something in active campaigns breaks or spikes unexpectedly).

FunctionFrequencyHow it works
Performance monitoringEvery 15 minutesPulls spend, impressions, clicks, and conversions from Meta API into local analysis pipeline
Budget optimization2x dailyShifts daily budget from underperforming ad sets to top performers based on ROAS thresholds
Underperformer detection2x dailyPauses ads below CPA threshold after minimum spend floor is crossed
Creative brief generation2x weeklyAnalyzes top performer patterns across hook, format, and offer angle - generates structured brief via Claude API
Competitor monitoringWeeklyScans Meta Ad Library for competitor creative activity and flags new formats or offers
Daily report7:00 AMSpend, ROAS, CPA, top ads summary, and anomaly alerts delivered to Telegram

Custom agent vs. Meta Advantage+: a direct comparison

The decision to build a custom agent rather than rely on Meta's Advantage+ tools is not obvious at first glance - Advantage+ requires no engineering investment and is available to any advertiser immediately. The trade-off becomes clear when you examine what each system can and cannot optimize for. The table below captures the practical differences that matter for a multi-account operation with complex business rules.

CapabilityCustom Python AgentMeta Advantage+
Optimization data sourceMeta API + Supabase business data (LTV, churn, margins)Meta platform data only
Budget rebalancing logicCustom ROAS thresholds per campaign, dynamic CPA floorsFixed platform rules, no business-specific parameters
Underperformer spend floorDynamic - calculated from campaign historical CPAFixed - applied uniformly regardless of campaign context
Creative intelligenceStructured briefs generated via Claude API, pattern analysis across all accountsAutomatic creative combination testing within Meta
Competitor monitoringWeekly Meta Ad Library scan with Telegram alertsNot available
ReportingDaily Telegram briefing + anomaly alerts + web dashboardMeta Business Manager dashboard only
Cross-account analysisFull - agent operates across all accounts simultaneouslyLimited - per-account only
Engineering cost~1 week build with Claude CodeZero - available out of the box

The competitor monitoring function deserves specific attention because it handles a task that most advertisers either skip or perform infrequently due to the manual effort involved. The agent scrapes the Meta Ad Library for a defined list of competitor pages every week, identifies ads that were not present in the previous scan, and flags new creatives with a Telegram notification that includes the ad format, copy angle, and estimated run duration. This gives a systematic view of competitor creative strategy that would take a human analyst several hours per week to replicate manually - and which realistically would not happen weekly in a lean operation without the agent.

The tech behind it

The agent is a Python application running on a Hetzner VPS via PM2 and cron jobs. It connects to the Meta Marketing API using a long-lived access token, pulls performance data into a local analysis pipeline, and uses the Claude API for natural language report generation and creative brief writing. A web dashboard updates every 15 minutes and provides a visual summary of current campaign status across all active accounts. All campaign history and optimization decisions are logged to a Supabase database, which creates an auditable record of every budget change and the performance signal that triggered it.

The entire agent - approximately 3,000 lines of Python - was built using Claude Code in about one week of focused sessions. Each feature was described in natural language, Claude Code wrote the implementation, and the output was tested and iterated against live campaign data until it worked correctly in production. This build approach is the same methodology applied across every product in the stack: precise specification of business logic, structured Claude Code sessions, and iterative refinement with real data. No manual coding was involved at any stage. The build was completed in April 2026 using the current Claude Code release available at that time, and the agent has operated in continuous production since without requiring structural changes to the codebase.

The Supabase integration is the architectural decision that separates this agent from simpler Meta API wrappers. Instead of treating Meta conversion events as the final source of truth, the agent joins Meta campaign data with customer records stored in Supabase - including subscription duration, refund history, and segment-level lifetime value. This means an ad set that generates high conversion volume but attracts high-churn customers gets penalized in the budget allocation model, while an ad set with lower raw conversion volume but superior downstream retention receives proportionally more budget. That adjustment is impossible inside Meta's native optimization layer, which has no visibility beyond the conversion event itself.

According to Meta AI Research published in December 2025, automated campaign management systems reduce optimization latency by 73% compared to human-managed campaigns, enabling real-time budget adjustments based on performance signals that a human reviewer would catch only during scheduled check-ins. A McKinsey analysis from late 2025 found that companies combining AI-automated campaign optimization with human-directed creative strategy outperform fully automated campaigns by 23% on cost per acquisition and retain that advantage over longer time horizons as audience fatigue and competitive dynamics shift.

How budget optimization logic works

The optimization logic runs on a set of business-specific rules that go beyond what Meta's Advantage+ automation applies. Each ad set is evaluated against a ROAS threshold and a CPA ceiling defined at the campaign level. When an ad set exceeds the ROAS threshold consistently across both daily optimization windows, the agent increases its daily budget by a defined increment - typically 15 to 20 percent - and reduces budget proportionally from ad sets in the same campaign that are performing below threshold. This rebalancing keeps total campaign spend constant while shifting allocation toward proven performers without requiring manual intervention.

The minimum spend floor before pausing is a critical parameter because pausing an ad set too early - before it has accumulated statistically meaningful data - produces false negatives that eliminate potentially strong performers before they exit the learning phase. The agent calculates the minimum spend floor dynamically based on the campaign's historical CPA, ensuring that underperformer detection operates on sufficient data rather than early noise. This dynamic threshold is one of the features that distinguishes the custom agent from Meta's native tools, which apply fixed rules regardless of campaign context.

Budget scaling decisions also incorporate day-of-week and time-of-day multipliers derived from each account's historical performance data. The agent does not apply the same scaling increment on a Monday morning as it does on a Friday afternoon - it adjusts the increment size based on the expected performance window for that specific day and hour combination. This granularity prevents over-scaling into low-performance windows and concentrates budget increases in the periods where each account historically delivers the strongest results. The multiplier table is recalculated monthly as new performance data accumulates, so the model adapts as audience behavior shifts across seasons and campaigns.

A PwC AI Predictions report from 2025 found that companies using custom AI optimization agents for paid advertising outperform those relying on platform-native automation by an average of 23% on cost per acquisition, with the advantage widening as campaign complexity increases. The performance gap is largest for businesses running multiple campaigns across different audience segments simultaneously - exactly the scenario the Meta Ads optimizer is built for. For anyone building a similar system, the practical approach Bartosz Cruz teaches covers exactly this architecture. Learn more about the mentoring program at AI Expert Academy.

Creative strategy and the human-AI division of labor

Creative strategy is the one advertising function that remains human-directed in this system. The agent generates structured creative briefs twice per week by analyzing top-performing ads and identifying patterns in format, hook structure, offer framing, and audience response - but the decision about which audience segment to address next, which offer angle to test, and which creative format to prioritize is made based on the agent's analysis combined with business context that only a human operator holds. The agent surfaces the data patterns; the strategy decisions remain with Bartosz Cruz.

This human-AI division of labor is deliberate and reflects a clear understanding of where AI optimization creates sustainable value versus where it plateaus. Purely automated creative testing - where an AI selects both the optimization rules and the creative strategy - produces short-term efficiency gains but tends to converge on a local optimum that represents the best version of an existing approach rather than identifying genuinely new angles. Human strategic direction introduces the discontinuous creative shifts that break through audience fatigue and open new performance ceilings. The agent's role is to make those strategic decisions faster and better-informed by eliminating the data processing work that would otherwise consume the time available for strategic thinking.

Bartosz Cruz discussed this exact cognitive division of labor - where human judgment remains irreplaceable and where automation creates leverage - during an interview on Polskie Radio Czworka's Swiat 4.0 program in May 2025. The core argument: AI tools that eliminate execution work free cognitive capacity for the strategic and creative decisions that actually determine long-term performance, rather than simply reducing headcount on tasks that could have been automated years earlier. That framing applies directly to this advertising system, where the 90% time reduction in execution work converts directly into bandwidth for audience strategy, offer development, and creative direction. You can also explore how this methodology extends to other automation workflows in the AI workflow design guide and the breakdown of building agents with Claude Code.

According to a Gartner analysis of AI in paid media from 2025, marketing teams that use AI for optimization execution while retaining human control over creative strategy achieve 31% better long-term ROAS stability compared to teams that delegate both execution and strategy to automated systems. The report identifies creative strategic direction as the highest-leverage human contribution to AI-augmented advertising operations - the function where human judgment produces the largest marginal improvement over what AI can generate independently.

Reporting and observability

The Telegram reporting layer is what makes running an autonomous advertising agent practical for a solo operator. Every morning at 7:00 AM, the agent sends a structured briefing to a dedicated Telegram channel covering total spend across all accounts, ROAS by campaign, CPA by ad set, top-performing ads with thumbnail links, and any anomaly flags from the overnight period. This passive reporting model means campaign status is visible without logging into Meta Business Manager, pulling custom reports, or spending the first 30 minutes of the day reviewing dashboards manually.

Anomaly detection is built into the reporting layer as a separate function from the optimization logic. When the agent detects unusual patterns - a sudden CPA spike, a spend pacing deviation, a delivery issue on a high-budget campaign - it sends an immediate Telegram alert rather than waiting for the next scheduled report. This separation of routine reporting from anomaly alerting prevents alert fatigue while ensuring that situations requiring human attention surface immediately rather than being buried in a daily summary. The result is genuine passive oversight: normal operation runs silently, problems surface instantly.

The web dashboard that updates every 15 minutes serves a different function from the Telegram reports - it provides a visual audit trail rather than a daily briefing. Every budget change the agent makes is logged with a timestamp, the triggering performance signal, the previous budget value, and the new value. This creates a complete decision log that makes it possible to audit whether the agent's logic is performing as intended, identify edge cases where the rules produced unexpected behavior, and refine the optimization parameters over time. Running an autonomous agent without this kind of observability layer means operating blind - you know the agent is making decisions but cannot verify whether those decisions are correct until performance results accumulate over days or weeks.

According to a Forbes analysis of AI marketing automation from 2025, businesses using automated performance reporting reduce time spent on campaign analysis by an average of 62%, with the largest time savings in the daily monitoring and anomaly identification functions that previously required dedicated analyst attention. A separate Harvard Business Review analysis from September 2025 found that advertising teams using structured AI reporting - where anomalies surface via alerts rather than manual dashboard review - identify and respond to campaign issues 4.2x faster than teams relying on scheduled human review cycles. For a solo operator managing multiple accounts simultaneously, this time recovery is the difference between having bandwidth for strategic work and spending the majority of available time on monitoring tasks that AI handles more thoroughly and consistently than a human reviewer working across competing priorities.

Frequently asked questions

How does Bartosz Cruz use AI for Meta Ads?

Bartosz Cruz built an autonomous Python agent that connects directly to the Meta Marketing API and runs on a cron schedule on a Hetzner VPS managed with PM2. The agent monitors campaign performance every 15 minutes, adjusts budgets based on ROAS and CPA thresholds twice daily, generates creative briefs twice per week by analyzing top-performing ads, and sends structured morning reports to Telegram at 7:00 AM. This system - built entirely with Claude Code by Anthropic in one week - replaces the routine execution work of a media buyer while Bartosz Cruz retains strategic control over audience selection, offer angles, and creative direction.

Can AI fully manage Meta Ads campaigns?

AI handles routine optimization reliably - budget allocation, bid adjustments, pausing underperformers, cross-campaign spend rebalancing, and daily reporting - without human involvement in the execution layer. Creative strategy, audience selection, major budget decisions, and offer positioning still require human judgment because they depend on business context the agent cannot access from performance data alone. Bartosz Cruz's agent handles daily optimization cycles automatically while he makes the strategic decisions that determine what gets tested and why, which is the division of labor that produces sustained performance improvement rather than short-term gains that plateau.

What results has Bartosz Cruz seen with AI Meta Ads optimization?

Bartosz Cruz's AI agent has reduced manual campaign management time by 90% while maintaining ROAS targets across multiple accounts simultaneously. The system processes over 200 data points per optimization cycle, makes budget adjustments 14 times per week automatically, and surfaces creative performance patterns that would take a human analyst hours to identify manually. Because the agent incorporates business outcome data from Supabase - not just campaign metrics from Meta - its budget allocation decisions reflect lifetime customer value rather than surface-level conversion cost, which improves long-term account economics beyond what Meta's native automation tools can achieve.

How was the Meta Ads agent built and how long did it take?

The agent is approximately 3,000 lines of Python built entirely with Claude Code by Anthropic in about one week of focused sessions - no manual coding at any stage. Bartosz Cruz described each feature in natural language, Claude Code wrote and revised the implementation, and the agent was tested and iterated against live campaign data until each function worked correctly in production. The build approach is the same methodology taught inside AI Expert Academy: precise specification of business logic, structured Claude Code sessions, and iterative testing with real data rather than synthetic examples.

How does a custom Meta Ads agent differ from Advantage+?

Meta's Advantage+ tools optimize within platform data only - they have no visibility into customer lifetime value, churn rates, or business outcomes stored outside Meta. A custom Python agent connected to both the Meta Marketing API and a Supabase business database makes budget decisions based on actual business economics, not just on-platform conversion cost. The custom agent also applies dynamic spend floors calibrated to each campaign's historical CPA, whereas Advantage+ applies fixed rules regardless of campaign context.

Last updated: 2026-05-04