Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.trygravity.ai/llms.txt

Use this file to discover all available pages before exploring further.

Installation

npm install @gravity-ai/api
Set GRAVITY_API_KEY in your server environment.

How the pieces fit together

1

Initialize the pixel

gravityPixel() handles session and visitor tracking automatically. Initialize it once when your app starts.
2

Prepare context

gravityContext() captures device signals and session info. Pass the pixel’s visitor and session IDs to link tracking with ad requests.
3

Fetch ads

gravity.getAds(req, messages, placements) reads the context, adds the client IP, and returns matched ads. Runs in parallel with your LLM call.

Initialize the pixel

import { gravityPixel } from '@gravity-ai/api';

const pixel = gravityPixel({ pixelId: 'YOUR_PIXEL_ID' });
await pixel.start();
Find YOUR_PIXEL_ID in your dashboard under Settings → Platform Settings. The pixel automatically manages sessions, visitor IDs, and attribution — same as the browser pixel (gr-pix.js), but using local file storage instead of cookies. Session state is persisted and cleaned up automatically on process exit.
ParameterTypeDefaultDescription
pixelIdstringRequired. Your Gravity pixel ID.
appNamestring'terminal'Application label, used as page title in events.
eventEndpointstring'https://api.trygravity.ai/track/gr-events'Event endpoint URL.
sessionEndpointstring'https://api.trygravity.ai/track/gr-session'Session endpoint URL.
sessionTimeoutMinutesnumber30Session idle timeout in minutes.
attrMaxAgeDaysnumber180Max age for persisted attribution in days.
sessionMaxPagesnumber50Max entries in invocation history.
hashIdentityFieldsbooleantrueHash identity fields with SHA-256 before sending.
storageDirstring'~/.gravity'Custom storage directory for session and attribution data.

Prepare context

import { gravityContext } from '@gravity-ai/api';

const gravity_context = gravityContext({
  sessionId: pixel.getSessionId()!,
  user: {
    userId: currentUser.id,
    gruid: pixel.getVisitorId(),
    grclid: pixel.getClickId(),
    graid: pixel.getGraid(),
  },
});
gravityContext() auto-detects terminal device signals (OS, timezone, locale). Required parameters:
ParameterTypeRequiredDescription
sessionIdstringYesFrom pixel.getSessionId()
user.userIdstringYesStable per-user identifier

Fetch ads

import { Gravity } from '@gravity-ai/api';

const gravity = new Gravity({ production: true });

const { ads } = await gravity.getAds(
  { body: { gravity_context }, headers: {} },
  messages,
  [{ placement: 'inline_response', placement_id: 'main' }],
);
gravity.getAds() never throws. On any failure, it returns { ads: [] } silently. Safe to fire-and-forget.

Full example

import { gravityPixel, gravityContext, Gravity } from '@gravity-ai/api';

// 1. Initialize pixel
const pixel = gravityPixel({ pixelId: 'YOUR_PIXEL_ID' });
await pixel.start();

// 2. Set up ad client
const gravity = new Gravity({ production: true });

// 3. On each user interaction
async function handleQuery(userId: string, messages: any[]) {
  const ctx = gravityContext({
    sessionId: pixel.getSessionId()!,
    user: {
      userId,
      gruid: pixel.getVisitorId(),
      grclid: pixel.getClickId(),
    },
  });

  const { ads } = await gravity.getAds(
    { body: { gravity_context: ctx }, headers: {} },
    messages,
    [{ placement: 'inline_response', placement_id: 'main' }],
  );

  return ads;
}

FAQ

No. gravityPixel ships inside @gravity-ai/api. Just npm install @gravity-ai/api and import it.
Yes. It uses standard APIs and falls back gracefully when Node-specific modules aren’t available.
No. Fire gravity.getAds() in parallel with your LLM call. It never throws, so failures are silent.
Set GRAVITY_API_KEY as an environment variable. The Gravity class reads it automatically. You can also pass it via new Gravity({ apiKey: '...' }).