AdPilot architecture
AdPilot architecture
Prototype v0.1 · September 2026
1. System overview
┌──────────────────────────────────────────────────────────────────┐
│ AdPilot mobile app (Expo) │
│ iOS · Android · Web — one TypeScript codebase (expo-router) │
│ │
│ Screens: Dashboard · Copilot(chat) · Campaigns · Studio · Settings│
│ │
│ ┌────────────────────── on-device engine ────────────────────┐ │
│ │ planner.ts prompt → intent → campaign plan │ │
│ │ content.ts platform-shaped creative generation │ │
│ │ optimizer.ts efficiency scoring, bounded rebalances, │ │
│ │ alerts, weekly reports │ │
│ │ metrics.ts deterministic delivery simulation │ │
│ │ adapters.ts AdPlatformAdapter interface (sandbox impl) │ │
│ │ aiClient.ts optional live LLM (OpenAI-compatible) │ │
│ └────────────────────────────────────────────────────────────┘ │
│ Zustand store + AsyncStorage persistence │
└──────────────────────────────┬───────────────────────────────────┘
│ (v0.5: same engine moves server-side)
┌──────────────────────────────▼───────────────────────────────────┐
│ Agent gateway (Node + Hono, apps/backend) │
│ POST /api/plan prompt → LLM-or-heuristic → validated plan │
│ POST /api/launch plan → per-platform adapter calls │
│ POST /api/budget guarded budget change │
│ POST /api/status pause/resume │
│ │
│ Guardrails: zod schema validation · daily spend ceiling · │
│ platform minimum budgets · audit log of every mutation │
│ │
│ ┌── adapters ────────────────────────────────────────────────┐ │
│ │ MockAdapter (ships now) │ │
│ │ GoogleAdsAdapter ── Google Ads API v17+ (v0.5, GREEN) │ │
│ │ MicrosoftAdapter ── Microsoft Advertising (v0.5, GREEN) │ │
│ │ MetaAdapter ─────── Meta Marketing API (v1.0, YELLOW) │ │
│ │ TikTokAdapter ───── TikTok Marketing API (v1.0, YELLOW) │ │
│ └────────────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────────┘
Why the engine runs on-device in the prototype: the demo must work with zero credentials, zero cost and zero latency, and the heuristic planner is deterministic (testable). The backend is the production home for the agent: credentials, LLM calls, cron jobs (daily optimization + insights pull) and the audit trail don't belong in a mobile client. Both share the same interfaces and algorithm shapes, so migration is a transport swap, not a rewrite.
2. The agent pipeline
user message
│
▼
intentFromPrompt() launch | optimize | report | question
│
├─ launch ──► planFromPrompt() (or LLM via aiClient)
│ ├ extractProduct/goal/budget/days/platforms
│ ├ inferCategory() → audience + AOV priors
│ ├ choosePlatforms() → weighted picks (explicit
│ │ user-requested platforms are "locked in")
│ ├ splitBudget() → per-platform amounts w/ minimums
│ ├ generateCreatives() → 2 variants/platform
│ └ kpiTargets() → ROAS/CPA/CPI/CPM goals
│ PlanCard ──[user approves]──► launchPlan()
│ adapter.createCampaign()
│ per platform + audit log
│
├─ optimize ► buildOptimizationSuggestion()
│ 7-day efficiency score per platform (ROAS or
│ conversions/$) vs portfolio average
│ moves bounded: ±30% daily, ≥ platform minimum
│ SuggestionCard ──[user approves]──► applySuggestion()
│
├─ report ──► buildWeeklyReport() plain-language KPI summary
└─ question ► capability answer + quick prompts
Human-in-the-loop rule: every money-touching action (launch, budget change) renders as a card the user explicitly approves. Every applied action writes an audit-log event (eventLog) with platform, external id and delta. The agent never raises its own caps.
3. Data model (TypeScript, src/lib/types.ts)
| Entity | Purpose | Key fields |
|---|---|---|
CampaignPlan |
agent's proposal | budgetSplit[] with rationale, audience, creatives[], kpiTargets |
Campaign |
one platform flight | platform, dailyBudget, status, externalId, startedAt |
DailyMetrics |
one day of delivery | spend, impressions, clicks, conversions, revenue |
OptimizeSuggestion |
rebalance proposal | moves[] {platform, delta, reason}, applied flag |
ChatMessage |
conversation entry | kind: text/plan/optimization/report, planId/suggestionId refs |
LogEvent |
audit trail | human-readable action text, platform, ts |
Persistence: Zustand + AsyncStorage (localStorage on web). The metrics simulator is seeded per (campaignId, date) so history is stable across restarts while still responding to the demo time-machine.
4. The platform-adapter pattern (the integration seam)
interface AdPlatformAdapter {
createCampaign(input): Promise<{ externalId }>;
updateBudget(externalId, dailyBudget): Promise<void>;
setStatus(externalId, status): Promise<void>;
}
Every platform integration implements exactly this surface; everything above it (planner, optimizer, UI, audit log) is platform-agnostic. The sandbox adapter simulates latency and external ids. Production adapters (documented per platform in docs/04-platform-api-landscape.md):
| Platform | API | MVP verdict | Sequence |
|---|---|---|---|
| Google Ads | Google Ads API | 🟢 basic developer token ≈ 5 business days | v0.5 |
| Microsoft Ads | Microsoft Advertising API | 🟢 public sandbox token day 1 | v0.5 |
| Meta | Marketing API | 🟡 business verification + App Review + call-volume warm-up (~1–3 mo) | v1.0 (start warm-up at v0.5) |
| TikTok | Marketing API | 🟡 sandbox instant; full access weeks–2 months | v1.0 |
| Snap / Pinterest | Ads API | 🟡 | v1.x |
| X / LinkedIn | Ads API | 🟡 / 🔴 (LinkedIn is selective MDP-only) | later |
5. Metrics simulation (what powers the demo)
simulateDay(campaign, date, dayIndex) computes spend (learning-phase ramp), impressions (spend/CPM with a per-campaign quality factor that drifts by day), clicks (platform CTR × quality), conversions (goal CVR), revenue (category AOV × goal value factor). All random draws come from mulberry32(hash(campaignId + date)) — deterministic, so charts don't change between launches, and unit tests can assert on seeded portfolios (e.g., the seeded TikTok dip triggers alerts and a valid rebalance).
6. AI model strategy
| Task | Prototype | Production |
|---|---|---|
| Campaign planning | heuristic (offline, deterministic); optional OpenAI-compatible endpoint via Settings | server-side LLM (Gemini Flash-class ≈ $0.60/1k short gens or gpt-nano ≈ $0.25) with zod-validated JSON output; batch API −50% |
| Ad copy | template library per goal/platform/tone | LLM with category/hook-performance context |
| Image briefs | written briefs + ready image prompts | gpt-image-1-mini / Gemini image (≈ $0.01–0.04/img), aspect-ratio per format |
| Video (v1.x) | out of scope | Sora 2 API / Veo / HeyGen-class (≈ $0.2–1 per UGC-style video) |
| Orchestration | single-step intents | tool-calling with MCP server wrapping the adapters; spend ceiling enforced server-side regardless of model output |
The LLM path is strictly an upgrade, never a dependency: any API failure falls back to the deterministic engine (the app is fully usable offline and with zero keys — by design for demos and for trust).
7. Security & compliance posture (prototype)
- No ad-platform credentials are stored in the prototype (sandbox only); the Settings → AI key field is device-local and never logged.
- Production: OAuth tokens server-side only (encrypted at rest), GDPR/CCPA data map before v0.5, AI-content disclosure metadata on all generated creatives (TikTok mandatory labeling since 2026), special-ad-category gates (credit/employment/housing) in the planner.
- Spend guardrails are enforced below the LLM — model output is schema-validated and clamp-guardrailed before any adapter call.