# AdsRouter — Complete Publisher Integration Manual (llms-full.txt) > Self-contained technical reference for AI coding agents and developers integrating AdsRouter (https://adsrouter.ai). > Operated by Multify Inc. (sister product to FreeRouter). --- ## 1. Architecture & Base URLs - **Ad Server API**: `https://api.adsrouter.ai` - **Publisher Dashboard**: `https://app.adsrouter.ai` (OTP auth shared with FreeRouter) - **Marketing & Docs**: `https://adsrouter.ai` - **OpenAPI 3.1 Spec**: `https://adsrouter.ai/openapi.json` - **Browser Helper SDK**: `https://api.adsrouter.ai/sdk/adsrouter-client.js` AdsRouter mediates up to 7 demand sources per property and placement: `direct`, `network` (AdsRouter Network), `gravity` (S2S), `thrad` (S2S), `velocity` (S2S), `koah` (client_bridge), and `house` (fallback). Third-party mediation is strictly non-custodied (BYOK): publishers store their own encrypted credentials in the dashboard and keep 100% of direct network payouts. --- ## 2. Authentication Every `POST https://api.adsrouter.ai/v1/ad` request must authenticate a Property using ONE of these two methods: 1. **Bearer Property Secret (recommended)**: ``` Authorization: Bearer ar_sec_xxxxxxxxxxxxxxxxxxxxxxxx ``` 2. **Public Key + Secret Pair**: ``` X-Property-Key: ar_pub_xxxxxxxxxxxxxxxx X-Property-Secret: ar_sec_xxxxxxxxxxxxxxxxxxxxxxxx ``` - Keep `ar_sec_*` strictly server-side. Never embed `ar_sec_*` in browser JS or mobile app binaries. - Secret rotation in the dashboard supports a grace window (`previous_secret_hash`) so you can deploy zero-downtime key swaps. - Tracking URLs (`/v1/imp/:id`, `/v1/render/:id`, `/v1/click/:id`, `/v1/client-event`) are unauthenticated, browser-callable URLs bound to unguessable impression IDs. --- ## 3. Core Endpoint: POST /v1/ad ### Request Headers - `Authorization: Bearer ` (or `X-Property-Key` + `X-Property-Secret`) - `Content-Type: application/json` ### Request Body Schema ```json { "placement": "chat_below_answer", "messages": [ { "role": "user", "content": "Best running shoes for flat feet?" }, { "role": "assistant", "content": "Stability shoes like Brooks Adrenaline or ASICS GT-2000..." } ], "assistant_response": "Optional explicit latest assistant answer", "session_id": "conv_9f81a2", "user": { "maid": "optional-idfa-or-gaid-uuid", "pub_user_id": "usr_12345" }, "device": { "ip": "203.0.113.42", "ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36", "accept_language": "en-US,en;q=0.9", "country": "US", "device_type": "desktop", "platform": "web", "os": "macOS" }, "test_mode": false, "metadata": { "dimensions": { "maxWidth": 420, "maxHeight": 160 } } } ``` Field rules: - `placement`: string, defaults to `"default"`. Matches placement-specific mediation rules and campaign targeting. - `messages`: array of `{ role: "user" | "assistant" | "system", content: string }`. Used for contextual keyword matching and S2S networks (Gravity, Thrad, Velocity) + Koah Q&A extraction. - `device.ip` & `device.ua`: strongly recommended when calling from your backend; falls back to HTTP request IP/UA if omitted. Gravity and Thrad require end-user IP + UA. - `device.country`, `device_type`, `platform`, `os`: optional overrides; if omitted, AdsRouter automatically derives `country` via GeoIP and `device_type`/`platform`/`os` by parsing `device.ua`. - `test_mode`: boolean; when true (or enabled on the property), serves test ads and isolates impressions from production frequency caps and billing stats. ### Canonical Responses (ALWAYS HTTP 200 for valid auth/JSON) #### Case A: Filled Creative (`render_mode: "creative"`) Returned for `direct`, `network`, `house`, `gravity`, `thrad`, and `velocity`. ```json { "request_id": "req_01JXYZ...", "filled": true, "render_mode": "creative", "source": "gravity", "placement": "chat_below_answer", "ad": { "id": "imp_01JXYZ...", "headline": "Stability runners built for long miles", "description": "Free 30-day wear test and express shipping.", "image_url": "https://cdn.example.com/shoe.jpg", "cta": "Shop now", "brand_name": "StrideLab", "favicon_url": "https://cdn.example.com/favicon.png", "click_url": "https://api.adsrouter.ai/v1/click/imp_01JXYZ...", "impression_beacon_url": "https://api.adsrouter.ai/v1/imp/imp_01JXYZ...", "render_beacon_url": null, "sponsored_label": "Sponsored", "ttl_ms": 300000 } } ``` #### Case B: Client SDK Directive (`render_mode: "client_sdk"`) Returned when `koah` wins the waterfall (Koah has no public S2S ad-serving REST API). ```json { "request_id": "req_01JXYZ...", "filled": true, "render_mode": "client_sdk", "source": "koah", "placement": "chat_below_answer", "impression_id": "imp_01JXYZ...", "client_sdk": { "network": "koah", "script_url": "https://app.koah.ai/js", "config": { "token": "koah_pub_...", "slot": "chat-below", "context": { "type": "conversation", "question": "Best running shoes for flat feet?", "answer": "Stability shoes like Brooks Adrenaline or ASICS GT-2000..." }, "dimensions": { "maxWidth": 420, "maxHeight": 160 } }, "event_beacon_url": "https://api.adsrouter.ai/v1/client-event" } } ``` #### Case C: No-Fill (`render_mode: "none"`) ```json { "request_id": "req_01JXYZ...", "filled": false, "render_mode": "none", "placement": "chat_below_answer", "ad": null } ``` --- ## 4. Cloaked Tracking Beacons, Clicks & Viewability Rules All S2S ads use first-party cloaked URLs on `https://api.adsrouter.ai`: 1. **`GET /v1/imp/:id` (`ad.impression_beacon_url`)**: - Fire ONCE when the ad is genuinely viewable (at least 50% visible in the viewport via `IntersectionObserver({ threshold: 0.5 })`). - Use `navigator.sendBeacon(url)` with `fetch(url, { mode: 'no-cors', keepalive: true })` fallback. - Server stamps `viewed_at`, increments `ar_stats_daily.impressions`, and returns `204 No Content` (or 1x1 transparent GIF if `?gif=1`) for `direct`/`network`/`house`, or `302 Found` to the upstream network's impression URL for mediated ads. 2. **`GET /v1/render/:id` (`ad.render_beacon_url`)**: - Present when an upstream network (e.g., Thrad) requires a two-stage `rendered` tracker. - Fire immediately when the ad mounts in the DOM. 3. **`GET /v1/click/:id` (`ad.click_url`)**: - ALWAYS render `ad.click_url` as the anchor `href` with `target="_blank" rel="noopener noreferrer sponsored"`. - Server stamps `clicked_at`, increments `ar_stats_daily.clicks`, and returns `302 Found` to the advertiser destination URL (or upstream click URL). 4. **`POST /v1/client-event` (`client_sdk.event_beacon_url`)**: - Body: `{ "impression_id": "imp_...", "event": "fill" | "no_fill" | "impression" | "click" }`. - Used by client-SDK bridges (Koah) to report fill/no-fill and engagement telemetry back to AdsRouter. --- ## 5. Identity Resolution, Frequency Caps & Targeting ### Tiered Identity (automatic) 1. `maid` — `user.maid` (IDFA / GAID) if provided. 2. `pub_user_id` — `user.pub_user_id` if provided. 3. `ip_ua_hash` — one-way `sha256(ip|ua|accept_language)` fallback. ### Frequency Caps & 10-Minute In-Flight Reservation - Enforced at both property level (`default_freq_cap_hourly`, `default_freq_cap_daily`) and campaign level (`freq_cap_hourly`, `freq_cap_daily`, `freq_cap_window_sec`). - Counts BOTH `viewed_at IS NOT NULL` AND active in-flight reservations (`reservation_expires_at > now()`, default 10 minutes) so concurrent chat turns cannot exceed caps before beacons arrive. ### Direct/House/Network Campaign Targeting JSON ```json { "property_ids": ["uuid"], "placements": ["chat_below_answer"], "countries": ["US", "CA"], "device_types": ["mobile", "tablet", "desktop"], "platforms": ["ios", "android", "web"], "oses": ["iOS", "Android", "macOS", "Windows"], "include_keywords": ["running", "shoes"], "exclude_keywords": ["injury", "lawsuit"] } ``` ### Dayparting JSON (IANA Timezone) ```json { "timezone": "America/New_York", "windows": [ { "days": [1, 2, 3, 4, 5], "start_hour": 9, "end_hour": 18 } ] } ``` ### Pacing Modes - `even_pacing`: linear target across flight/day with controlled burst allowance. - `traffic_pct`: deterministic percentage sampling (0-100). - `asap`: deliver immediately until `cap_daily` / `cap_total`. --- ## 6. Koah Client-SDK Bridge & Drop-In Browser Helper Fastest browser integration — load `https://api.adsrouter.ai/sdk/adsrouter-client.js`: ```html
``` Manual Koah bridge (when `decision.render_mode === "client_sdk"`): ```js async function runKoahBridge(containerEl, decision) { const { script_url, config, event_beacon_url } = decision.client_sdk; if (!window.koah) { await new Promise((resolve, reject) => { const s = document.createElement('script'); s.src = `${script_url}?token=${encodeURIComponent(config.token)}`; s.async = true; s.onload = resolve; s.onerror = reject; document.head.appendChild(s); }); } const sendEvent = (event) => { const payload = JSON.stringify({ impression_id: decision.impression_id, event }); if (navigator.sendBeacon) { navigator.sendBeacon(event_beacon_url, new Blob([payload], { type: 'application/json' })); } else { fetch(event_beacon_url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: payload, keepalive: true }); } }; window.koah.requestAd({ target: containerEl, slot: config.slot, context: config.context, dimensions: config.dimensions, onFill: () => sendEvent('fill'), onNoFill: () => sendEvent('no_fill'), }); } ``` --- ## 7. Error Codes - `200 OK`: Decision returned (`filled: true` or `filled: false`). Upstream network misses/timeouts never 5xx. - `400 Bad Request`: Malformed JSON or invalid payload. - `401 Unauthorized`: Missing or invalid `Authorization: Bearer ar_sec_...` or `X-Property-Key` + `X-Property-Secret`. - `403 Forbidden`: Property is paused or disabled. - `404 Not Found`: Unknown impression ID on `/v1/imp/:id`, `/v1/render/:id`, or `/v1/click/:id`. --- ## 8. End-to-End Code Examples ### cURL ```bash curl -X POST https://api.adsrouter.ai/v1/ad \ -H "Authorization: Bearer $ADSROUTER_PROPERTY_SECRET" \ -H "Content-Type: application/json" \ -d '{ "placement": "chat_below_answer", "messages": [ { "role": "user", "content": "Best espresso machine under $500?" }, { "role": "assistant", "content": "The Breville Bambino is a popular pick..." } ], "user": { "pub_user_id": "usr_42" }, "device": { "ip": "203.0.113.10", "ua": "Mozilla/5.0 ..." } }' ``` ### Node.js (Express backend) ```js async function fetchChatAd({ messages, userId, req }) { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), 3500); try { const res = await fetch('https://api.adsrouter.ai/v1/ad', { method: 'POST', signal: controller.signal, headers: { Authorization: `Bearer ${process.env.ADSROUTER_PROPERTY_SECRET}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ placement: 'chat_below_answer', messages, user: userId ? { pub_user_id: String(userId) } : undefined, device: { ip: req.headers['x-forwarded-for']?.split(',')[0]?.trim() || req.ip, ua: req.headers['user-agent'] || '', accept_language: req.headers['accept-language'] || '', }, }), }); if (!res.ok) return { filled: false, render_mode: 'none', ad: null }; return await res.json(); } catch { return { filled: false, render_mode: 'none', ad: null }; } finally { clearTimeout(timer); } } ``` ### Python (FastAPI / requests) ```python import os import requests def fetch_chat_ad(messages: list[dict], user_id: str | None, client_ip: str, client_ua: str) -> dict: try: r = requests.post( "https://api.adsrouter.ai/v1/ad", headers={ "Authorization": f"Bearer {os.environ['ADSROUTER_PROPERTY_SECRET']}", "Content-Type": "application/json", }, json={ "placement": "chat_below_answer", "messages": messages, "user": {"pub_user_id": user_id} if user_id else {}, "device": {"ip": client_ip, "ua": client_ua}, }, timeout=3.5, ) return r.json() if r.ok else {"filled": False, "render_mode": "none", "ad": None} except Exception: return {"filled": False, "render_mode": "none", "ad": None} ```