# Creative AI Feedback Loop

Connect your creative model to real advertising screens. Generate or import images, choose what runs, and feed measured attention and dwell into the next decision. This guide covers the live creative optimization workflow through REST, MCP and the TypeScript SDK.

**Base URL:** `https://api.trillboards.com`

## Get your buying key

Use the existing [Partner API onboarding](https://api.trillboards.com/docs/guides/quickstart/partner) to create your account and key. Your key identifies the same buying account throughout inventory discovery, funding, creative review, serving and reward reads.

## Live workflow

### Fund a media buy

Discover products with `get_products` and inventory with `discover_inventory` on the [MCP endpoint](https://api.trillboards.com/mcp). Complete the existing `create_media_buy` flow and retain its `media_buy_id` and selected `package_id`. The experiment binds to that package's actual funded advertisement and placements. Use a production buying account to serve; a sandbox buy exercises validation without creating live placements.

Media and API usage have separate payment decisions. The media buy uses its accepted inventory, CPM and contracted quote; activation requires the native funding receipt. Generation, image import and each reward page use the existing `data_api/api_calls` tariff, free quota and API allowance. Media credit alone does not authorize an unfunded API read. Check current rates at [pricing](https://api.trillboards.com/v1/partner/pricing); metered responses include `usage_receipt` with exact units and charges. Stripe-backed account funding follows the existing verified payment flow; posting a creative does not fund a placement.

API holds use your current graduated tariff. A lone request that crosses the free allowance reserves only its paid suffix. Concurrent admitted work can rebalance active holds; commitment, cancellation and expiry return excess reserves. Your final `usage_receipt` reports the exact actual charge. Repeating an operation key retains its original identity and tariff.


Use a partner buying key with `campaigns:write`, `bid:write` or `partner:write` for writes, and `reports:read`, `stats:read` or `partner:read` for reads. MCP additionally requires `mcp:tools`.

### Fund and book with the SDK

Install `@trillboards/api-client@3.2.1`. The SDK uses the native MCP protocol for media buying and REST for account funding and creative experiments.

```typescript
import { TrillboardsClient } from '@trillboards/api-client';

const client = new TrillboardsClient({ apiKey: process.env.TRILLBOARDS_API_KEY! });

// Persist purchaseKey before calling; reuse it only for this exact purchase.
async function openCreditCheckout(purchaseKey: string) {
  const checkout = await client.billing.createCreditCheckout(
    { tier: 'tier_500' }, { idempotencyKey: purchaseKey },
  );
  return checkout.checkout_url;
}

async function readFunding() {
  const usage = await client.billing.getUsageSummary();
  return {
    balanceCents: usage.credit_balance_cents,
    reservedCents: usage.credit_reserved_cents,
  };
}

async function bookInventory(input: {
  productId: string; budgetUsd: number; brandDomain: string;
  startTime: string; endTime: string; operationKey: string;
}) {
  try {
    const accounts = await client.mediaBuys.listAccounts();
    const account = accounts.accounts.find(value => value.status === 'active');
    if (!account) throw new Error('Use an active production buying account.');
    const catalog = await client.mediaBuys.getProducts({
      pagination: { max_results: 100 },
    });
    const product = catalog.products.find(value => value.product_id === input.productId);
    const fixed = product?.pricing_options.find(value => value.fixed_price !== undefined);
    if (!product || !fixed) throw new Error('Select a current product and fixed CPM option from the catalog.');
    const buy = await client.mediaBuys.create({
      idempotency_key: input.operationKey,
      account: { account_id: account.account_id },
      brand: { domain: input.brandDomain },
      start_time: input.startTime, end_time: input.endTime,
      packages: [{ product_id: product.product_id,
        pricing_option_id: fixed.pricing_option_id, budget: input.budgetUsd }],
    });
    if (!buy.media_buy_id || !buy.packages?.length) throw new Error('Buy did not return its native identifiers.');
    return buy;
  } finally {
    await client.mediaBuys.close();
  }
}
```

Open the returned Checkout URL and complete payment. Read `credit_balance_cents` and `credit_reserved_cents` after the verified Stripe webhook commits the credit; a browser redirect or Checkout-session creation alone does not fund the account. These values and usage amounts are exact decimal strings in cents. `billing.setup({payment_method_id})` saves a payment method; `billing.purchaseCredits({tier}, {idempotencyKey})` uses an already configured payment method. Both credit-purchase paths require a stable `Idempotency-Key`. Direct purchases return `status`, `requires_action` and, when Stripe needs confirmation, `client_secret`; complete that Stripe action before treating credits as settled.

Call `mediaBuys.getProducts` to choose the product and pricing-option identifiers, following `pagination.cursor` when `pagination.has_more` is true. Supply your budget, brand domain and future ISO8601 flight bounds to `bookInventory`. Retain `media_buy_id`, `packages[].package_id` and the returned funding state. The native buy quote, funding receipt, creative eligibility and screen-owner preferences determine serving readiness. `status` at the MCP task layer describes task execution. Once the package is funded, use those exact identifiers in the experiment below; creative review and registration complete its native serving workflow.

### Create, review and register an action

Create the experiment after funding. Policy versions are exact decimal strings. Reuse the enrollment key only for the same creation request.

```bash
curl -sS -X POST https://api.trillboards.com/v1/partner/creative-experiments \
  -H "Authorization: Bearer $TRILLBOARDS_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"name":"Creative attention loop","media_buy_id":"YOUR_MEDIA_BUY_ID","package_id":"YOUR_PACKAGE_ID","objective":"gaze_share","idempotency_key":"enroll-attention-v1","expected_policy_version":"0"}'
```

Keep the response's `data.id` and `data.policy_version`. Configure `/brand` using your `brand_name`, complete `brand_rules`, optional `brand_assets` and `stance`. The brand-rules object contains `brand_name`, `palette` (`primary`, `secondary`, `accents`), `typography` (`headline`, `body`), `voice_tone`, `mandatory_elements`, `prohibited_elements`, `products`, `taglines` and `stance_preferences`; see the [Partner reference](https://api.trillboards.com/docs/partner) for the full schema.

A complete brand body for `/brand`:

```json
{
  "brand_name": "Acme",
  "brand_rules": {
    "brand_name": "Acme",
    "palette": {"primary": "#111111", "secondary": "#FFFFFF", "accents": []},
    "typography": {"headline": "Bold sans serif", "body": "Sans serif"},
    "voice_tone": ["clear"],
    "mandatory_elements": ["Brand name", "Clear call to action"],
    "prohibited_elements": [],
    "products": [],
    "taglines": [],
    "stance_preferences": ["intent_capture"]
  },
  "brand_assets": [],
  "stance": "intent_capture"
}
```

Then choose an image source:

- Call `/creatives/generate` with `stance`, `aspectRatio`, `brief` and a fresh `idempotency_key` to use native generation.
- Call `/creatives/import` with a fresh key and exactly one of `asset_url`, `source_creative_id` or `image_base64`. Inline bytes also require `content_type`. PNG, JPEG and WebP are validated from their actual bytes; an existing source creative must belong to this partner.

Both paths return a staged `creativeId` and `cdnUrl`. If a response is lost, reuse its operation key: the committed 409 response retains the original receipt. Get the existing experiment to recover your native `creatives` library, which returns the latest 500 candidates and marks `creatives_truncated` when more exist. Each row retains its original `advertisement_mongo_id` and reports `linked_to_experiment_ad` for this experiment's current ad; the committed receipt also retains its server-derived `creativeId` and `renderKey`. This recovery does not repeat paid generation/import. `moderation_status` and `content_sha256` stay NULL until the review matches that exact asset URL. Preview the image and call `/creatives/review` with `{"creative_id":"YOUR_CREATIVE_ID","decision":"approve"}` or `"reject"`. Brand approval and AI moderation are separate steps. Registration succeeds once the creative is approved, linked to this advertisement and eligible; `CREATIVE_NOT_READY` means it has not reached that state.

Register the approved action with the latest version:

```json
{
  "expected_version": "1",
  "variants": [
    {"variant_id": "headline-a", "creative_id": "YOUR_CREATIVE_ID", "model_version": "your-model-v3"}
  ]
}
```

Post that body to `/v1/partner/creative-experiments/YOUR_EXPERIMENT_ID/variants`, using the actual current version from the experiment response. Registration returns a new `policy_version`; retain it. Variant, model and byte identity stay fixed after registration. A new model/image gets a new variant identity.

### Start serving and iterate

Put a weight generation to `/v1/partner/creative-experiments/YOUR_EXPERIMENT_ID/policy`:

```json
{
  "expected_version": "2",
  "weights": [{"creative_id": "YOUR_CREATIVE_ID", "weight": 1}]
}
```

Use the registration response's version. Weights must be between zero and one, with at least one positive entry; zero removes that creative from selection. Every update returns the next version. On `CREATIVE_POLICY_CONFLICT`, get the experiment and reconcile the current version before writing again.

The next signed paid play uses the current eligible policy. Screen preferences and current approval are checked at selection. Each resulting reward retains the issued variant, model version, policy version, byte hash, render specification and selection probability. You can update the next play's policy as soon as your model makes a decision. Measured rewards follow the existing five-minute refresh and daily 48-hour correction sweep.

### Read rewards and keep corrections

```bash
curl -sS -G "https://api.trillboards.com/v1/partner/creative-experiments/$EXPERIMENT_ID/rewards" \
  -H "Authorization: Bearer $TRILLBOARDS_API_KEY" \
  --data-urlencode "from=$FROM_DATE" --data-urlencode "to=$TO_DATE" \
  --data-urlencode 'limit=500' --data-urlencode "idempotency_key=$READ_OPERATION_KEY"
```

Dates are inclusive UTC calendar dates, up to 31 days per scope; pages contain at most 5,000 rows. Use a fresh operation key for each page and each new poll. A repeated pending or committed key returns HTTP 409 (`OPERATION_IN_PROGRESS` or `OPERATION_ALREADY_COMMITTED`); a committed response includes the original receipt at `error.help.usage_receipt`.

Follow `next_cursor` with the same dates. When `scan_complete` is true, the next poll starts with no cursor. This reads latest measured states and recovers late writes on the next complete rescan. Store rows by `canonical_key` and deduplicate by `reward_revision_id`: an `upsert` replaces that play's contribution; a `retract` removes it. Keep the revision so a repeated tombstone has no second effect. `build_stamp` and `builder_version` record provenance; a rebuild can retain the same logical revision.

`gaze_share` uses `gaze_pct_on_screen` on a 0–1 scale; `gaze_overlap_ms` uses milliseconds; `dwell_ms` uses `dwell_capped_ms_mean`. NULL means unmeasured. Parse `creative_feedback` for the immutable issued action and model metadata. Train/evaluate against actual served observations; an unserved candidate has no measured reward.

Subscribe to `creative.rewards_ready` through existing partner webhooks or SSE. Hints are free and carry an experiment, date range, build provenance and reward-reader URL. Fetching each reward page uses the API tariff. On reconnect, recover with a full bounded rescan and logical deduplication. The hint is a wake-up signal; your stored canonical keys and revisions own recovery.

### Complete operation map

All paths below use `/v1/partner/creative-experiments`; `{id}` is the returned experiment ID. REST responses use `{success:true,data:...}`. MCP tools use the same schemas and native account.

| REST | MCP tool | Result / usage |
|---|---|---|
| POST base | `create_creative_experiment` | Funded enrollment; free |
| GET `/{id}` | `get_creative_experiment` | Current experiment/version; free |
| POST `/{id}/brand` | `configure_feedback_brand` | Native brand/reactive configuration; free |
| POST `/{id}/creatives/generate` | `generate_brand_creative` | Staged generated image; metered |
| POST `/{id}/creatives/import` | `import_feedback_creative` | Staged imported image; metered |
| POST `/{id}/creatives/review` | `review_feedback_creative` | Brand approve/reject; free |
| POST `/{id}/variants` | `register_creative_variants` | Approved immutable actions; free |
| PUT `/{id}/policy` | `update_creative_policy` | Versioned weights/start; free |
| GET `/{id}/rewards` | `get_creative_rewards` | Latest-state reward page/receipt; metered |
| POST `/{id}/stop` | `stop_creative_experiment` | Stop using `expected_version`; free |

Use the REST examples above or these MCP tools to start optimizing creatives. Both transports accept the same request bodies and return the same typed results.

Historical HUD tasksets use the existing verified product export, immutable vintage, manifest and dictionary. Their actor sees earlier measured observations; their verifier grades against later actual plays. The live HUD adapter calls these same MCP operations. See the repository's `integrations/hud/creative-feedback/README.md` for packaging and runtime commands.


## TypeScript SDK

Install the published client:

```bash
npm install @trillboards/api-client@3.2.1
```

The same operations are available on `client.creativeExperiments`. These functions use your funded media-buy identifiers, actual brand configuration and model-generated assets. Persist the experiment ID and each returned policy version. Call `approveAndServe` after inspecting the returned `cdnUrl` and completing AI moderation; `CREATIVE_NOT_READY` means that candidate is not eligible yet.

```typescript
import { TrillboardsClient } from '@trillboards/api-client';
import { randomUUID } from 'node:crypto';

const apiKey = process.env.TRILLBOARDS_API_KEY;
if (!apiKey) throw new Error('Set TRILLBOARDS_API_KEY to your partner buying key.');
const client = new TrillboardsClient({ apiKey });

type BrandConfiguration =
  Parameters<typeof client.creativeExperiments.configureBrand>[1];

async function createLoop(
  mediaBuyId: string, packageId: string, brand: BrandConfiguration,
  operationKey: string,
) {
  const experiment = await client.creativeExperiments.create({
    name: 'Creative attention loop',
    media_buy_id: mediaBuyId,
    package_id: packageId,
    objective: 'gaze_share',
    idempotency_key: operationKey,
    expected_policy_version: '0',
  });
  const id = experiment.data.id;
  await client.creativeExperiments.configureBrand(id, brand);
  return id;
}

async function stageAction(
  id: string, brief: string, operationKey: string, assetUrl?: string,
) {
  const creative = assetUrl
    ? await client.creativeExperiments.importCreative(id, {
        asset_url: assetUrl, idempotency_key: operationKey,
      })
    : await client.creativeExperiments.generate(id, {
        brief, stance: 'intent_capture', aspectRatio: '16:9',
        idempotency_key: operationKey,
      });
  return creative.data; // creativeId, cdnUrl and the usage_receipt
}

async function approveAndServe(
  id: string, creativeId: string, variantId: string, modelVersion: string,
) {
  await client.creativeExperiments.review(id, {
    creative_id: creativeId, decision: 'approve',
  });
  const current = await client.creativeExperiments.get(id);
  const registered = await client.creativeExperiments.registerVariants(id, {
    expected_version: current.data.policy_version,
    variants: [{
      variant_id: variantId, creative_id: creativeId, model_version: modelVersion,
    }],
  });
  return client.creativeExperiments.updatePolicy(id, {
    expected_version: registered.data.policy_version,
    weights: [{ creative_id: creativeId, weight: 1 }],
  });
}

async function* readRewardPages(
  id: string, from: string, to: string,
) {
  const scanId = randomUUID();
  let cursor: string | undefined;
  let page = 0;
  do {
    const result = await client.creativeExperiments.getRewards(id, {
      from, to, limit: 500, idempotency_key: `${scanId}:page:${page}`,
      ...(cursor ? { cursor } : {}),
    });
    yield result.data;
    if (result.data.scan_complete) return;
    cursor = result.data.next_cursor ?? undefined;
    page += 1;
    if (!cursor) throw new Error('Incomplete reward scan returned no next cursor.');
  } while (cursor);
}

async function stopLoop(id: string) {
  const current = await client.creativeExperiments.get(id);
  return client.creativeExperiments.stop(id, {
    expected_version: current.data.policy_version,
  });
}
```

Generate and persist a unique operation key (for example, `crypto.randomUUID()`) before each new creation, generation or import. Pass the same key only for the same operation and inputs. `readRewardPages` creates a fresh `scanId` for every invocation; its pages derive distinct billing keys.

Create the loop once, then stage and review each new model candidate against that experiment. A full reward-page scan feeds your next decision; apply each row's upsert or retraction using the keys above. Start the next poll with no cursor so corrections remain visible. For generation/import, keep the original operation key after a lost response: retrying it recovers the committed receipt and creative identity without repeating generation/import. For reward reads, the committed receipt contains no reward rows or cursor. Abandon an interrupted scan and invoke `readRewardPages` again from the beginning; it creates fresh page keys. Each recovery page follows the normal API tariff. Apply its latest states using the same canonical-key and revision deduplication.

## Inventory planning and ad-serving debugging environments

The Inventory Planning package combines measured screen-hour history with a dated native catalog and availability snapshot. Its HUD tasks forecast gaze share, dwell milliseconds and face density, then grade budget-constrained plans against that frozen snapshot and separate recorded reference windows. The downloadable package contains the source Parquets, dictionary, exact units, task splits, baseline scores and separate numerical verifier.

The Ad-serving Debugging package follows actual issued request and impression identifiers through request, auction, render and completion evidence. Tasks diagnose the observed stage or evidence gap and reconcile canonical billable plays and recorded USD amounts. Native billing-key and eligibility projections retain the existing billing policy.

Both version-3 downloads include a portable Python project and HUD0.6.20. From the extracted directory:

```bash
python3.12 -m venv ../trillboards-venv
. ../trillboards-venv/bin/activate
python -m pip install -r requirements.lock
export PYTHONDONTWRITEBYTECODE=1
python -m trillboards_hud.product_package verify .
python -m trillboards_hud.product_runner . --split evaluation --receipt ../evaluation.json
```

The baseline needs no account or model key. Add `--provider openai --model YOUR_MODEL` with your provider credential to evaluate a model through the same tools and verifier. Put execution receipts beside the immutable download. Live inventory discovery and delivery use `client.mediaBuys`; creative outcomes use `client.creativeExperiments.getRewards`. General screen history and the separate live audience tail are exposed through `client.data`, with their endpoint scopes `read:historical`, `read:live` and `stream:live`. The audience stream is a live tail; use bounded history reads after reconnect. Creative reward recovery uses the canonical-key/revision protocol above.

## References

- [Complete Partner API reference](https://api.trillboards.com/docs/partner)
- [Current API pricing](https://api.trillboards.com/v1/partner/pricing)
- [Error reference](https://api.trillboards.com/docs/errors)
