Before you start
- You have an API key. See Quickstart.
- You registered your placements in the dashboard. See Placements.
The pattern
Start the ad request at the same time as your LLM call. There are two reasons:- Latency. The user waits for your LLM response, not for the ad. The ad request must not delay the response.
- Safe failure. If the ad request fails, the chat continues with no ad.
Direct API integrations require a signed agreement with Gravity. Send an email to support@trygravity.com to request access.
What’s in the request
Want to compare ad earnings with your model costs? Add optionalusage to your ad request. Send the input and output token counts from one completed model call, not totals for the conversation or user. See Report model usage below for timing and an example, or Understand what your users earn you for the dashboard and user tags.
Report model usage
The JavaScript SDK (
@gravity-ai/api 1.4.0 or later) takes usage as an option: gravity.getAds(req, messages, placements, { usage }). The published Python, iOS and Android SDKs don’t have a usage option. With those, send usage in a direct HTTP request to the ad API, as this section shows.usage.
Keep the provider’s usage object when a reply finishes, then attach it to the next turn’s ad request. Report that completed call only once. This keeps ad fetching parallel with the new model call; you never wait for its token counts.
inputTokens is everything read by that previous call (system prompt, conversation history and other context); outputTokens is what it generated. Input can grow as a chat gets longer because earlier messages are sent to the model again, but you still report only the counts from that one call, not running totals.
usage: { model: completion.model, ...completion.usage }. Snake_case token names and nested cache-read counts (input_tokens_details.cached_tokens or prompt_tokens_details.cached_tokens) are accepted. OpenAI’s input/prompt total already includes cached tokens: no manual summing is needed. You can also send cachedInputTokens (cached_input_tokens); it’s a subset of total input. Malformed cache counts are ignored and accepted counts are bounded by input. Optional cost is the USD you paid for that same call and overrides the list-price estimate. See the HTTP example, including the Anthropic cache-accounting caveat.
Usage counts from the day you start to send it. To fill in earlier days, see Load usage for past days.
Device signals
Thedevice object tells Gravity that a real device sent the request, what kind of device it is, and where it is. Send device.ip, device.ua, device.device_type, and device.os on every ad request. Without ip and ua, Gravity cannot do bot and fraud detection or find the location. Without device_type and os, Gravity has to guess the device from the User-Agent, and that guessing ends on December 1, 2026 (see Declare the device type and OS).
The engine also accepts other fields, for example
timezone, locale, browser, and device_model.
Native apps and other clients. If your iOS or Android app calls Gravity, send the real User-Agent of the app client (for example
CFNetwork/Darwin, okhttp, or ktor-client) and the end user’s IP address. Set device_type and os as well (for example mobile and ios). For an IDE or a CLI, send the User-Agent of the client application with device_type: "desktop" and the OS it runs on. A call from your server must also forward device.ip and device.ua of the end user, so that Gravity sees the end user and not your server.device.ip. Gravity ignores user.ip. On iOS and Android, pass the IP address through the userIP parameter of getAds().
Declare the device type and OS
Gravity used to work out the device type and OS from the free-text User-Agent. That is deprecated and ends on December 1, 2026. Declare both values withdevice.device_type and device.os, using the values in the table above. Gravity matches them without regard to case, and a declared value wins over the User-Agent.
Until you declare both, each ad response carries these headers. The status code and the body do not change.
A value outside the list, for example
os: "iOS 18.1" or device_type: "phablet", does not fail the request. Gravity ignores it and names it in X-Gravity-Warning. Keep sending ua: Gravity still needs it for fraud and bot detection.
gravityContext() in @gravity-ai/api 1.3.1 and later sets both fields for you, and so does the Python SDK, which forwards that context.
Forward device signals from your server
gravityContext() collects the device object on the client. Your client sends this context to your server, and your server sends it to Gravity. The SDK methods getAds(req, ...) and get_ads(request, ...) read gravity_context (with device) from the request body. They also add the end user’s ip from the incoming request headers. If you build the ad request yourself, copy the device object from the client into the request body.
Data quality
Each of these signals helps Gravity match ads, report results, and connect conversions to impressions. Device signals are needed for fraud checks (see above). The rest are optional, but the better your data, the higher your eCPM tends to be.- Conversation context. Send the recent messages, not only the last one.
- Stable user ID. A consistent
user.idper user lets Gravity remove duplicate requests and apply frequency limits. - Device and locale.
gravityContext()adds these in the browser. If you call the API directly, forward the end user’sdevice.uaanddevice.ip(see Device signals). - Hashed email or phone. Lets Gravity credit you for view-through conversions: a purchase on the advertiser’s site after the user saw your ad but did not click it.
- Age and gender. If your users tell you, send
user.ageanduser.gender. They help Gravity pick ads that fit the user, anduser.agekeeps ads away from minors.
device.os), a device ID (device.id), and an advertising ID (device.ifa). After 500 requests in 7 days, each signal also gets a status: Good, Low, or Missing.
Respect your users’ privacy choices. Pass their consent signals in the consent object (see Consent), and only send hashed identifiers you are allowed to share.
Hash user data
Never send a raw email or phone number. UsehashPii() in the browser to hash the values (SHA-256 of the normalized value) before the request leaves the client:
user from gravity_context.user in the request body. Hash the values on the client, as in the example above.
If you call the HTTP API directly and make the hashes yourself, use the same normalization:
- email:
sha256(email.strip().lower()) - phone:
sha256(re.sub(r"\D+", "", phone))(digits only)
user.hashed_email and the phone hash as user.hashed_phone, as hex strings.
The engine also accepts the older
user.email_hash field, and raw user.email and user.phone fields, for backward compatibility. The engine hashes raw values when it receives them. New integrations must send user.hashed_email.What’s in the response
When an ad matches, the endpoint returns HTTP200 with a JSON array of ad objects:
{ ads, status, elapsed } in JavaScript, and AdResult(ads, status, elapsed_ms, ...) in Python. The result object is part of the SDK only. It is not in the HTTP response.
Use clickUrl for ad links, not url. clickUrl records the click and sends a 302 redirect to the landing page. Request impUrl when the ad becomes visible. In the React SDK, GravityAd does this for you.
When no ad matches, the endpoint returns HTTP 204 No Content with an empty body. It also returns 204 when it filters the request as a bot, when the request times out, and on an internal error. Hide the ad slot when there is no ad.
Framework examples
Next.js (App Router)
In a route handler,req is a Web Request. Parse the body, then give the SDK an object with body and headers.
FastAPI
Multiple placements
You can request more than one placement in one call. All placements use the same auction:placement_id field of each ad to find its slot, and show a slot only when it has an ad.
Tune the request
Relevancy tradeoff
relevancy is a score from 0.0 to 1.0. The SDK default is 0.2. This setting has a large effect on your results, so make sure that you understand the tradeoff:
Gravity recommends
0.2 for most integrations. Start there, and change it if your results for each slot show a need.
Gravity applies a minimum relevancy for the full network. A value below this minimum has no effect. Gravity can also set a relevancy value for your account. When it does, that value replaces the value in your request.
Timeout
The JavaScript SDK stops the request after 4 seconds (timeoutMs). The engine also stops its work after 4 seconds and returns 204. The Python SDK stops the request after 3 seconds (timeout, in seconds). Use a higher value if your stack can wait longer. Use a lower value if your latency limits are strict.
Excluded topics
Exclude topics for one request:Next steps
Show ads
Show the ads in your UI.
API reference
All HTTP parameters.