Skip to main content
Use @gravity-ai/api on your server to request ads, and @gravity-ai/react in your client to show them. For the terms on this page, see Core concepts.

Before you start

  • You have a Gravity API key. Get it from your dashboard under Settings → Platform Settings.
  • Your server runs Node.js (or another runtime with fetch), and your client uses React 17 or later.
  • You have a chat endpoint on your server that calls your model.

Install

  1. Install the packages:
  2. Set GRAVITY_API_KEY in your server environment.
Do not reference GRAVITY_API_KEY in client code. A bundler can put the value into your public JavaScript.

Step 1: Prepare the context in the client

In your client, call gravityContext() and send the result to your server with the messages:
gravityContext() collects the device data, the session, and the consent signal from the page. user.userId is required. In a browser with the Gravity pixel, sessionId is optional: the SDK uses the pixel session. Send the complete gravity_context object to your server.

Step 2: Request ads on the server

Start the ad request at the same time as your model call:
gravity.getAds() reads gravity_context from req.body, adds the end user’s IP address from the request headers, and sends the last two messages to Gravity. It never throws. On no-fill or on an error, ads is an empty array. The result is { ads, status, elapsed, requestBody, error }. status is the HTTP status from Gravity, or 0 for a network error or a missing API key.

Options

Pass these options to new Gravity(). You can also pass them as the fourth argument of getAds() for one call.

User tags and model usage

Add tags to the user when you prepare context:
Tags are optional. See Understand what your users earn you for the rules.
@gravity-ai/api doesn’t have a model usage option. To report model usage, send it in a direct HTTP request to the ad API: see Report model usage.

Step 3: Show the ad in React

Give the ad to GravityAd:
You see the ad under the response. GravityAd draws the placement design, shows a built-in card when no design is available, records the impression and the click, and shows the ad label. Show the slot only when ads has an ad. Keep one stable sessionId for each conversation.

Custom renderer

Use GravityAd if you can. If you draw ads with your own code, do these things:
  1. Send supportsSpec: false in the getAds() options.
  2. Load ad.impUrl once when the ad becomes visible.
  3. Open ad.clickUrl, not ad.url, when the user clicks the ad.
  4. Show a clear ad label.

Troubleshoot