@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
-
Install the packages:
-
Set
GRAVITY_API_KEYin your server environment.
Step 1: Prepare the context in the client
In your client, callgravityContext() 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 tonew Gravity(). You can also pass them as the fourth argument of getAds() for one call.
User tags and model usage
Addtags to the user when you prepare context:
@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 toGravityAd:
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
UseGravityAd if you can. If you draw ads with your own code, do these things:
- Send
supportsSpec: falsein thegetAds()options. - Load
ad.impUrlonce when the ad becomes visible. - Open
ad.clickUrl, notad.url, when the user clicks the ad. - Show a clear ad label.