> ## Documentation Index
> Fetch the complete documentation index at: https://docs.trygravity.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Action ads

> Request action ads through the HTTP API and add reviewed prompts to your own composer.

An Action ad lets a user add an advertiser's reviewed prompt to your application's composer. Your application renders the ad and inserts the prompt. The user can edit it and chooses when to send it. Adding a prompt never submits a message automatically.

You can use Action ads without an SDK. If your server calls `/api/v1/ad` and your application renders its own markup, follow the examples below.

## Default behavior and review

Action ads are on by default for registered placements that declare a working prompt handler. Send `supportsPromptAction: true` on each placement where your application can insert the prompt. You do not need to request `units: ['action']` or enable a separate action unit.

Gravity automatically reviews the exact advertiser-provided prompt text and its campaign context for prompt injection, unsafe instructions, privacy risks, and brand alignment. Only the currently approved content can be served as an action. Changing the prompt or its associated campaign context requires a new automatic review. Publishers do not approve each prompt themselves.

An ad request can still return an ordinary ad without an `action` field, or no ad. Keep your normal ad renderer and website-link behavior for those cases. Two-phase `/bid` and `/render` requests do not return actions.

### Turn actions off for a placement

Turn off **Prompt actions** in the placement editor, or set this preference through the authenticated placement API:

```json theme={null}
{
  "display_config": {
    "prompt_actions_enabled": false
  }
}
```

The preference applies to that placement only. Missing or null means enabled; setting it to `true` enables actions again. Unrelated placement edits preserve your choice. See [Placements](https://docs.trygravity.com/ai-platforms/placements.md).

## 1. Declare the capability in your ad request

Make the request from your server. Keep your publisher key out of browser code. Use the same registered placement ID, conversation session, user context, consent, and end-user device signals as your normal ad requests.

```js theme={null}
async function requestAds({ messages, sessionId, clientIp }) {
  const response = await fetch('https://server.trygravity.ai/api/v1/ad', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.GRAVITY_PUBLISHER_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      messages,
      sessionId,
      device: { ip: clientIp },
      placements: [{
        placement: 'below_response',
        placement_id: 'composer-slot',
        supportsPromptAction: true,
      }],
    }),
  });

  if (response.status === 204 || !response.ok) return [];
  return response.json();
}
```

Replace `composer-slot` with your placement's ID or slug. `clientIp` is the end user's IP from your trusted request context, not your server's IP. Keep forwarding your existing user, device, and consent fields; this shortened example shows the added placement capability. See [Request ads](https://docs.trygravity.com/ai-platforms/request-ads.md) for those fields.

Only declare the capability where the browser actually has a working composer insertion handler. A request-level `supportsPromptAction` field does not enable another placement.

## 2. Read the optional action field

The endpoint returns an array of ads. An eligible ad includes `action` alongside its normal copy and tracking URLs:

```json theme={null}
{
  "placement_id": "composer-slot",
  "adText": "Plan your garden with Example Garden.",
  "cta": "Visit website",
  "url": "https://example.com",
  "clickUrl": "https://tracking.example/click",
  "impUrl": "https://tracking.example/impression",
  "action": {
    "type": "prompt",
    "id": "garden-plan-v1",
    "prompt": "Help me plan a garden. Ask about my space and budget first.",
    "openUrl": true
  }
}
```

Use the URLs from the actual response; the URLs above are placeholders. `action.id` identifies the action. `action.prompt` is the text to insert into your own composer. It is not HTML, a URL, or instructions for your application to execute.

`openUrl` defaults to `true` when omitted: the same user click adds the prompt and opens the existing tracked `clickUrl`. Only explicit `false` selects prompt insertion without website navigation. A button such as **Add prompt + open website** makes the default behavior clear.

If `action` is missing, malformed, or has an unknown `type`, render the ordinary ad and website link. Do not execute unknown action kinds. Additional fields do not grant new behavior.

## 3. Insert the prompt into your own composer

This browser example uses ordinary HTML elements, not a Gravity SDK. It leaves an existing draft untouched, inserts only after a user clicks, and never submits the form.

```html theme={null}
<section id="ad-slot" aria-label="Sponsored ad"></section>
<form id="chat-form">
  <label for="composer">Message</label>
  <textarea id="composer"></textarea>
  <button type="submit">Send</button>
</form>
```

```js theme={null}
function safeHttpUrl(value) {
  if (typeof value !== 'string') return null;
  try {
    const url = new URL(value);
    return ['https:', 'http:'].includes(url.protocol) &&
      !url.username && !url.password ? url.href : null;
  } catch {
    return null;
  }
}

function openWebsite(clickUrl) {
  if (!clickUrl) return;
  let popup;
  try {
    popup = window.open('', '_blank');
    if (!popup) return;
    popup.opener = null;
    popup.location.href = clickUrl;
  } catch {
    try { popup?.close(); } catch {}
  }
}

function renderActionAd(ad, slot, composer) {
  slot.replaceChildren();
  if (!ad) return;

  const label = document.createElement('small');
  label.textContent = 'Sponsored';
  const copy = document.createElement('p');
  copy.textContent = ad.adText || '';
  slot.append(label, copy);

  const clickUrl = safeHttpUrl(ad.clickUrl);
  const action = ad.action;
  const usable = action?.type === 'prompt' &&
    typeof action.id === 'string' && action.id.trim() &&
    typeof action.prompt === 'string' && action.prompt.trim() &&
    (action.openUrl === undefined || typeof action.openUrl === 'boolean');

  if (!usable) {
    if (clickUrl) {
      const link = document.createElement('a');
      link.href = clickUrl;
      link.target = '_blank';
      link.rel = 'noopener noreferrer sponsored';
      link.textContent = ad.cta || 'Visit website';
      slot.append(link);
    }
    return;
  }

  const button = document.createElement('button');
  button.type = 'button';
  button.textContent = action.openUrl !== false
    ? 'Add prompt + open website' : 'Add prompt';
  button.addEventListener('click', () => {
    if (composer.value) return;
    if (action.openUrl !== false) openWebsite(clickUrl);
    composer.value = action.prompt;
    composer.dispatchEvent(new Event('input', { bubbles: true }));
    composer.focus();
  });
  slot.append(button);
}

renderActionAd(
  ads[0],
  document.querySelector('#ad-slot'),
  document.querySelector('#composer'),
);
```

Here, `ads` is the array your server passed to the browser. Keep your application's existing Send handler separate. For a controlled or rich-text composer, replace the `composer.value` assignment with your own state or editor API. Report insertion as successful only after that API accepts the text.

The example declines the action before opening a website when a draft already exists. Your application may instead ask permission to append or replace; never overwrite the draft silently. If consent is asynchronous, a new window must be opened during the original user activation to avoid popup blocking. In that design, website navigation may happen before consent resolves. A blocked popup does not prevent prompt insertion.

Do not use `innerHTML`, execute the prompt, call your LLM, or simulate a Send click to insert it.

## Tracking and fallbacks

Keep your normal raw-API impression tracking: request the ad's `impUrl` once when the ad is visibly rendered. Requesting an ad or putting text in a composer is not an impression. The rendering example above does not send impression requests for you.

For actual website navigation, use the response's tracked `clickUrl`. Do not prefetch it or send an extra click beacon. Prompt-only insertion and refusal send no click request or insertion callback to Gravity. A normal tracked website click can incur the existing CPC charge; insertion alone is not a click or conversion. CPM and CPA campaigns do not gain an extra click charge.

## SDK and iframe integrations

With `@gravity-ai/react`, pass `onPrompt` to `GravityAd`. The handler returns or resolves `{ status: 'inserted' }`, `{ status: 'declined' }`, or `{ status: 'failed' }`. A render-only React component cannot modify your separate server request: that request must still declare the placement capability above. Self-fetching `GravityAd` in the UI SDK and Horizon infer capability from their `onPrompt` callback.

An iframe is optional; raw publishers can use the native example above. An eligible iframe can send the fixed GFB-1 trigger `action: 'prompt'`. Its host uses only the reviewed parent response's `ad.action`, never prompt text, IDs, URLs, or `openUrl` supplied by the frame. SDK hosts require their own iframe window, the expected protocol envelope, and live parent user activation. Normal frame eligibility and independent HTML/version review still apply.

Without a usable parent action or handler, keep the ordinary frame or website-link behavior. SDK iframe handlers can attempt the existing tracked website fallback after an insertion failure; they do not synthesize a click or add a click beacon. SDK outcome feedback stays visually hidden, and the action button keeps its original label.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.