@gravity-ai/api 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -8,6 +8,58 @@ type Role = 'user' | 'assistant';
8
8
  * @description Used for demographic targeting of advertisements
9
9
  */
10
10
  type Gender = 'male' | 'female' | 'other';
11
+ /**
12
+ * Placement positions for ad rendering
13
+ * @description Specifies where ads should appear relative to the AI response
14
+ */
15
+ type Placement = 'above_response' | 'below_response' | 'inline_response' | 'left_response' | 'right_response';
16
+ /**
17
+ * Individual ad placement specification
18
+ * @description Defines a single ad slot with its position and optional tracking ID
19
+ * @example
20
+ * ```typescript
21
+ * const placement: PlacementObject = {
22
+ * placement: 'below_response',
23
+ * placement_id: 'sidebar-1'
24
+ * };
25
+ * ```
26
+ */
27
+ interface PlacementObject {
28
+ /** Position where the ad should appear (required) */
29
+ placement: Placement;
30
+ /** Optional tracking ID for this specific ad slot */
31
+ placement_id?: string;
32
+ }
33
+ /**
34
+ * Describes how your app will display the ad
35
+ * @description Contains placement array and rendering capabilities for ad customization
36
+ * @example
37
+ * ```typescript
38
+ * const renderContext: RenderContextObject = {
39
+ * placements: [
40
+ * { placement: 'below_response' },
41
+ * { placement: 'right_response', placement_id: 'sidebar' }
42
+ * ],
43
+ * max_ad_length: 200
44
+ * };
45
+ * ```
46
+ */
47
+ interface RenderContextObject {
48
+ /** Where you plan to show the ad(s). Array of 1-3 placements, must match numAds. */
49
+ placements: PlacementObject[];
50
+ /** Character limit you can display, so we don't send copy that gets truncated */
51
+ max_ad_length?: number;
52
+ /** Whether you can render markdown-formatted text */
53
+ supports_markdown?: boolean;
54
+ /** Whether you can render clickable links */
55
+ supports_links?: boolean;
56
+ /** Whether you can display images (brand logos, product images) */
57
+ supports_images?: boolean;
58
+ /** Whether you can render CTA buttons */
59
+ supports_cta_button?: boolean;
60
+ /** Additional render context properties (supports JSON objects) */
61
+ [key: string]: PlacementObject[] | string | number | boolean | object | null | undefined;
62
+ }
11
63
  /**
12
64
  * Represents a single message in a conversation
13
65
  * @description Used to provide conversation context for contextual ad targeting
@@ -39,16 +91,18 @@ interface MessageObject {
39
91
  * ```
40
92
  */
41
93
  interface DeviceObject {
42
- /** User's IP address for geo-targeting */
94
+ /** User's IP address for geo-targeting (required) */
43
95
  ip: string;
96
+ /** Browser user-agent string (optional for non-web publishers like IDEs, CLIs, mobile apps) */
97
+ ua?: string;
44
98
  /** ISO 3166-1 alpha-2 country code (e.g., 'US', 'GB', 'DE') */
45
- country: string;
46
- /** User agent string from the browser */
47
- ua: string;
99
+ country?: string;
48
100
  /** Operating system name (e.g., 'macOS', 'Windows', 'iOS', 'Android') */
49
101
  os?: string;
50
102
  /** Identifier for Advertisers (mobile advertising ID) */
51
103
  ifa?: string;
104
+ /** Additional device properties (timezone, locale, browser, device_type, screen dimensions, etc.) */
105
+ [key: string]: string | number | boolean | undefined;
52
106
  }
53
107
  /**
54
108
  * User profile information for ad targeting
@@ -64,7 +118,7 @@ interface DeviceObject {
64
118
  * ```
65
119
  */
66
120
  interface UserObject {
67
- /** Unique user identifier for frequency capping and tracking */
121
+ /** Unique user identifier for improving ad relevance */
68
122
  uid?: string;
69
123
  /** User's gender for demographic targeting */
70
124
  gender?: Gender;
@@ -72,6 +126,8 @@ interface UserObject {
72
126
  age?: string;
73
127
  /** Comma-separated keywords representing user interests */
74
128
  keywords?: string;
129
+ /** Additional user properties (email, subscription_tier, user_interests, company_size, etc.) */
130
+ [key: string]: string | string[] | number | boolean | Gender | undefined;
75
131
  }
76
132
  /**
77
133
  * Parameters for requesting an advertisement
@@ -83,6 +139,13 @@ interface UserObject {
83
139
  * { role: 'user', content: 'What laptop should I buy?' },
84
140
  * { role: 'assistant', content: 'What is your budget?' }
85
141
  * ],
142
+ * sessionId: 'session-123',
143
+ * numAds: 1,
144
+ * render_context: {
145
+ * placements: [{ placement: 'below_response' }]
146
+ * },
147
+ * userId: 'user-456',
148
+ * testAd: true,
86
149
  * user: { gender: 'male', age: '25-34' },
87
150
  * device: { ip: '1.2.3.4', country: 'US', ua: 'Mozilla/5.0...' },
88
151
  * excludedTopics: ['politics'],
@@ -91,10 +154,16 @@ interface UserObject {
91
154
  * ```
92
155
  */
93
156
  interface AdParams {
94
- /** Override the client's API key for this request */
95
- apiKey?: string;
96
157
  /** Array of conversation messages for contextual targeting (required) */
97
158
  messages: MessageObject[];
159
+ /** Session identifier for ad relevance (required) */
160
+ sessionId: string;
161
+ /** Render context with placements array (required). Length of placements must match numAds. */
162
+ render_context: RenderContextObject;
163
+ /** Number of ads to return (1-3). Must match render_context.placements length. */
164
+ numAds?: number;
165
+ /** Unique user identifier */
166
+ userId?: string;
98
167
  /** Device and location information */
99
168
  device?: DeviceObject;
100
169
  /** User demographic and interest data */
@@ -103,43 +172,65 @@ interface AdParams {
103
172
  excludedTopics?: string[];
104
173
  /** Minimum relevancy score threshold (0-1). Higher = more relevant but fewer ads */
105
174
  relevancy?: number | null;
175
+ /** Returns a test ad when true */
176
+ testAd?: boolean;
106
177
  /**
107
178
  * Additional custom fields for publisher-specific targeting
108
179
  * @description Any additional key-value pairs will be passed to the API
109
180
  */
110
181
  [key: string]: unknown;
111
182
  }
183
+ /**
184
+ * Single ad object in responses.
185
+ * @description Contains all ad creative and tracking data.
186
+ */
187
+ interface Ad {
188
+ /** The advertisement copy text */
189
+ adText: string;
190
+ /** Unique ad identifier */
191
+ adId: string;
192
+ /** Ad title */
193
+ title?: string;
194
+ /** Brand/advertiser name */
195
+ brandName?: string;
196
+ /** Brand logo image URL */
197
+ brandImage?: string;
198
+ /** Landing page URL */
199
+ url?: string;
200
+ /** Favicon URL */
201
+ favicon?: string;
202
+ /** Impression tracking URL */
203
+ impUrl?: string;
204
+ /** Click-through tracking URL */
205
+ clickUrl?: string;
206
+ /** Payout amount in USD */
207
+ payout?: number;
208
+ }
112
209
  /**
113
210
  * Response from the Gravity API containing ad data
114
211
  * @description Returned by getAd() when a relevant advertisement is found
115
212
  * @example
116
213
  * ```typescript
117
- * const ad: AdResponse = {
118
- * adText: 'Check out our amazing laptops!',
119
- * impUrl: 'https://tracking.example.com/imp?id=123',
120
- * clickUrl: 'https://example.com/laptops',
121
- * payout: 0.50
214
+ * const response: AdResponse = {
215
+ * ads: [{
216
+ * adText: 'Check out our amazing laptops!',
217
+ * adId: 'ad-123',
218
+ * impUrl: 'https://tracking.example.com/imp?id=123',
219
+ * clickUrl: 'https://example.com/laptops',
220
+ * payout: 0.50
221
+ * }],
222
+ * numAds: 1,
223
+ * totalPayout: 0.50
122
224
  * };
123
225
  * ```
124
226
  */
125
227
  interface AdResponse {
126
- /** The advertisement copy text to display to the user */
127
- adText: string;
128
- /**
129
- * Impression tracking URL - fire this when the ad is viewed
130
- * @description Should be loaded (e.g., via image beacon) when ad becomes visible
131
- */
132
- impUrl?: string;
133
- /**
134
- * Click-through URL - navigate user here when ad is clicked
135
- * @description The destination page when the user clicks the ad
136
- */
137
- clickUrl?: string;
138
- /**
139
- * Payout amount in USD for this ad impression
140
- * @description The revenue earned for displaying this ad
141
- */
142
- payout?: number;
228
+ /** Array of ad objects */
229
+ ads: Ad[];
230
+ /** Number of ads returned */
231
+ numAds: number;
232
+ /** Total payout across all ads */
233
+ totalPayout?: number;
143
234
  }
144
235
  /**
145
236
  * Error response structure from the Gravity API
@@ -154,12 +245,15 @@ interface ApiErrorResponse {
154
245
  statusCode?: number;
155
246
  }
156
247
  /**
157
- * Base fields shared across all v1 ad requests.
158
- * @description Mirrors engine's AdRequestBaseV1. All fields are optional.
248
+ * Base fields shared across all ad requests.
159
249
  */
160
- interface AdRequestBaseV1 {
161
- /** Session identifier for tracking user sessions */
162
- sessionId?: string;
250
+ interface AdRequestBase {
251
+ /** Session identifier for ad relevance (required) */
252
+ sessionId: string;
253
+ /** Render context with placements array (required). Length of placements must match numAds. */
254
+ render_context: RenderContextObject;
255
+ /** Number of ads to return (1-3). Must match render_context.placements length. */
256
+ numAds?: number;
163
257
  /** Unique user identifier */
164
258
  userId?: string;
165
259
  /** Device and location information */
@@ -170,26 +264,16 @@ interface AdRequestBaseV1 {
170
264
  excludedTopics?: string[];
171
265
  /** Minimum relevancy score threshold (0-1) */
172
266
  relevancy?: number | null;
173
- /** Number of ads to return (1-3, default 1) */
174
- numAds?: number;
175
267
  /** Returns a test ad when true */
176
268
  testAd?: boolean;
177
269
  /** Additional custom fields */
178
270
  [key: string]: unknown;
179
271
  }
180
- /**
181
- * POST /api/v1/ad/contextual
182
- * @description Requires messages array for contextual targeting.
183
- */
184
- interface ContextualAdParams extends AdRequestBaseV1 {
185
- /** Array of conversation messages (required) */
186
- messages: MessageObject[];
187
- }
188
272
  /**
189
273
  * POST /api/v1/ad/summary
190
274
  * @description Requires queryString for summary-based targeting.
191
275
  */
192
- interface SummaryAdParams extends AdRequestBaseV1 {
276
+ interface SummaryAdParams extends AdRequestBase {
193
277
  /** Search/summary query string (required) */
194
278
  queryString: string;
195
279
  }
@@ -197,18 +281,21 @@ interface SummaryAdParams extends AdRequestBaseV1 {
197
281
  * POST /api/v1/ad/non-contextual
198
282
  * @description No context required - returns ads without context matching.
199
283
  */
200
- interface NonContextualAdParams extends AdRequestBaseV1 {
284
+ interface NonContextualAdParams extends AdRequestBase {
201
285
  }
202
286
  /**
203
287
  * POST /api/v1/bid
204
288
  * @description Two-phase bid request. Returns bid price and bidId.
205
- * @note Does NOT extend AdRequestBaseV1 - has its own field set.
206
289
  */
207
290
  interface BidParams {
208
291
  /** Array of conversation messages (required) */
209
292
  messages: MessageObject[];
210
- /** Session identifier */
211
- sessionId?: string;
293
+ /** Session identifier for ad relevance (required) */
294
+ sessionId: string;
295
+ /** Render context with placements array (required). Length of placements must match numAds. */
296
+ render_context: RenderContextObject;
297
+ /** Number of ads to return (1-3). Must match render_context.placements length. */
298
+ numAds?: number;
212
299
  /** Unique user identifier */
213
300
  userId?: string;
214
301
  /** Chat/conversation identifier */
@@ -227,45 +314,7 @@ interface RenderParams {
227
314
  realizedPrice: number;
228
315
  }
229
316
  /**
230
- * Single ad object in v1 responses.
231
- * @description Contains all ad creative and tracking data.
232
- */
233
- interface AdV1 {
234
- /** The advertisement copy text */
235
- adText: string;
236
- /** Unique ad identifier */
237
- adId: string;
238
- /** Ad title */
239
- title?: string;
240
- /** Brand/advertiser name */
241
- brandName?: string;
242
- /** Brand logo image URL */
243
- brandImage?: string;
244
- /** Landing page URL */
245
- url?: string;
246
- /** Favicon URL */
247
- favicon?: string;
248
- /** Impression tracking URL */
249
- impUrl?: string;
250
- /** Click-through tracking URL */
251
- clickUrl?: string;
252
- /** Payout amount in USD */
253
- payout?: number;
254
- }
255
- /**
256
- * v1 ad response (multi-ad support).
257
- * @description Returned by contextual, summary, non-contextual, and render endpoints.
258
- */
259
- interface AdResponseV1 {
260
- /** Array of ad objects */
261
- ads: AdV1[];
262
- /** Number of ads returned */
263
- numAds: number;
264
- /** Total payout across all ads */
265
- totalPayout?: number;
266
- }
267
- /**
268
- * v1 bid response.
317
+ * Bid response.
269
318
  * @description Returned by the bid endpoint.
270
319
  */
271
320
  interface BidResponse {
@@ -318,13 +367,19 @@ interface ClientParams {
318
367
  *
319
368
  * const client = new Client('your-api-key');
320
369
  *
321
- * const ad = await client.getAd({
370
+ * const response = await client.getAd({
322
371
  * messages: [
323
372
  * { role: 'user', content: 'What laptop should I buy?' }
324
- * ]
373
+ * ],
374
+ * sessionId: 'session-123',
375
+ * numAds: 1,
376
+ * render_context: {
377
+ * placements: [{ placement: 'below_response' }]
378
+ * }
325
379
  * });
326
380
  *
327
- * if (ad) {
381
+ * if (response) {
382
+ * const ad = response.ads[0];
328
383
  * console.log(ad.adText);
329
384
  * }
330
385
  * ```
@@ -373,7 +428,7 @@ declare class Client {
373
428
  /**
374
429
  * Request a contextually relevant advertisement
375
430
  *
376
- * @description Fetches an ad based on the provided conversation context and targeting parameters.
431
+ * @description Fetches ads based on the provided conversation context and targeting parameters.
377
432
  * Returns `null` if no relevant ad is available or if an error occurs.
378
433
  *
379
434
  * @param params - Ad request parameters including conversation messages
@@ -381,18 +436,36 @@ declare class Client {
381
436
  *
382
437
  * @example Basic request
383
438
  * ```typescript
384
- * const ad = await client.getAd({
439
+ * const response = await client.getAd({
385
440
  * messages: [
386
441
  * { role: 'user', content: 'I need a new laptop for programming' },
387
442
  * { role: 'assistant', content: 'What is your budget range?' }
388
- * ]
443
+ * ],
444
+ * sessionId: 'session-123',
445
+ * numAds: 1,
446
+ * render_context: {
447
+ * placements: [{ placement: 'below_response' }]
448
+ * },
449
+ * userId: 'user-456',
389
450
  * });
451
+ *
452
+ * if (response) {
453
+ * const ad = response.ads[0];
454
+ * console.log(ad.adText);
455
+ * }
390
456
  * ```
391
457
  *
392
458
  * @example Full request with targeting
393
459
  * ```typescript
394
- * const ad = await client.getAd({
460
+ * const response = await client.getAd({
395
461
  * messages: [...],
462
+ * sessionId: 'session-123',
463
+ * numAds: 1,
464
+ * render_context: {
465
+ * placements: [{ placement: 'below_response' }],
466
+ * max_ad_length: 200
467
+ * },
468
+ * userId: 'user-456',
396
469
  * user: {
397
470
  * uid: 'user-123',
398
471
  * gender: 'male',
@@ -410,9 +483,15 @@ declare class Client {
410
483
  *
411
484
  * @example Handling the response
412
485
  * ```typescript
413
- * const ad = await client.getAd({ messages });
486
+ * const response = await client.getAd({
487
+ * messages,
488
+ * sessionId: '...',
489
+ * numAds: 1,
490
+ * render_context: { placements: [{ placement: 'below_response' }] }
491
+ * });
414
492
  *
415
- * if (ad) {
493
+ * if (response) {
494
+ * const ad = response.ads[0];
416
495
  * // Display the ad
417
496
  * showAd(ad.adText);
418
497
  *
@@ -425,78 +504,27 @@ declare class Client {
425
504
  */
426
505
  getAd(params: AdParams): Promise<AdResponse | null>;
427
506
  /**
428
- * Request contextual advertisements (v1 API)
429
- *
430
- * @description Fetches ads based on conversation context. Requires messages array.
431
- * Returns null if no relevant ad is available or on error.
432
- *
433
- * @param params - Request parameters including messages array
434
- * @returns Promise resolving to AdResponseV1 or null if no ad available
435
- *
436
- * @example
437
- * ```typescript
438
- * const response = await client.contextualAd({
439
- * messages: [
440
- * { role: 'user', content: 'What laptop should I buy?' }
441
- * ],
442
- * sessionId: 'session-123',
443
- * userId: 'user-456',
444
- * });
445
- *
446
- * if (response) {
447
- * const ad = response.ads[0];
448
- * console.log(ad.adText);
449
- * }
450
- * ```
451
- */
452
- contextualAd(params: ContextualAdParams): Promise<AdResponseV1 | null>;
453
- /**
454
- * Request summary-based advertisements (v1 API)
507
+ * Request summary-based advertisements
455
508
  *
456
509
  * @description Fetches ads based on a search/summary query string.
457
510
  * Returns null if no relevant ad is available or on error.
458
511
  *
459
512
  * @param params - Request parameters including queryString
460
- * @returns Promise resolving to AdResponseV1 or null if no ad available
461
- *
462
- * @example
463
- * ```typescript
464
- * const response = await client.summaryAd({
465
- * queryString: 'best laptops for programming 2025',
466
- * sessionId: 'session-123',
467
- * });
468
- *
469
- * if (response) {
470
- * const ad = response.ads[0];
471
- * console.log(ad.adText);
472
- * }
473
- * ```
513
+ * @returns Promise resolving to AdResponse or null if no ad available
474
514
  */
475
- summaryAd(params: SummaryAdParams): Promise<AdResponseV1 | null>;
515
+ summaryAd(params: SummaryAdParams): Promise<AdResponse | null>;
476
516
  /**
477
- * Request non-contextual advertisements (v1 API)
517
+ * Request non-contextual advertisements
478
518
  *
479
519
  * @description Fetches ads without context matching. Useful for brand awareness placements.
480
520
  * Returns null if no ad is available or on error.
481
521
  *
482
- * @param params - Optional request parameters
483
- * @returns Promise resolving to AdResponseV1 or null if no ad available
484
- *
485
- * @example
486
- * ```typescript
487
- * const response = await client.nonContextualAd({
488
- * sessionId: 'session-123',
489
- * numAds: 2,
490
- * });
491
- *
492
- * if (response) {
493
- * response.ads.forEach(ad => console.log(ad.adText));
494
- * }
495
- * ```
522
+ * @param params - Request parameters (sessionId required)
523
+ * @returns Promise resolving to AdResponse or null if no ad available
496
524
  */
497
- nonContextualAd(params?: NonContextualAdParams): Promise<AdResponseV1 | null>;
525
+ nonContextualAd(params: NonContextualAdParams): Promise<AdResponse | null>;
498
526
  /**
499
- * Request a bid price for contextual ad placement (v1 API)
527
+ * Request a bid price for contextual ad placement
500
528
  *
501
529
  * @description First phase of two-phase ad flow. Returns bid price and bidId.
502
530
  * Use the bidId with render() to generate the actual ad creative.
@@ -504,51 +532,18 @@ declare class Client {
504
532
  *
505
533
  * @param params - Request parameters including messages array
506
534
  * @returns Promise resolving to BidResponse or null if no bid available
507
- *
508
- * @example
509
- * ```typescript
510
- * const bidResult = await client.bid({
511
- * messages: [
512
- * { role: 'user', content: 'I need help with my code' }
513
- * ],
514
- * sessionId: 'session-123',
515
- * });
516
- *
517
- * if (bidResult) {
518
- * console.log(`Bid price: $${bidResult.bid} CPM`);
519
- * // Decide whether to show ad based on price...
520
- * const ad = await client.render({
521
- * bidId: bidResult.bidId,
522
- * realizedPrice: bidResult.bid,
523
- * });
524
- * }
525
- * ```
526
535
  */
527
536
  bid(params: BidParams): Promise<BidResponse | null>;
528
537
  /**
529
- * Render an ad from a cached bid (v1 API)
538
+ * Render an ad from a cached bid
530
539
  *
531
540
  * @description Second phase of two-phase ad flow. Generates ad creative using cached bid context.
532
541
  * Returns null if bid expired (404) or on error. Bid expires after 60 seconds.
533
542
  *
534
543
  * @param params - Request parameters including bidId and realizedPrice
535
- * @returns Promise resolving to AdResponseV1 or null if bid expired/error
536
- *
537
- * @example
538
- * ```typescript
539
- * // After getting a bid...
540
- * const ad = await client.render({
541
- * bidId: bidResult.bidId,
542
- * realizedPrice: bidResult.bid,
543
- * });
544
- *
545
- * if (ad) {
546
- * const firstAd = ad.ads[0];
547
- * displayAd(firstAd);
548
- * }
549
- * ```
544
+ * @returns Promise resolving to AdResponse or null if bid expired/error
550
545
  */
551
- render(params: RenderParams): Promise<AdResponseV1 | null>;
546
+ render(params: RenderParams): Promise<AdResponse | null>;
552
547
  /**
553
548
  * Handle and log API errors
554
549
  *
@@ -563,4 +558,4 @@ declare class Client {
563
558
  private handleError;
564
559
  }
565
560
 
566
- export { type AdParams, type AdRequestBaseV1, type AdResponse, type AdResponseV1, type AdV1, type ApiErrorResponse, type BidParams, type BidResponse, Client, type ClientParams, type ContextualAdParams, type DeviceObject, type Gender, type MessageObject, type NonContextualAdParams, type RenderParams, type Role, type SummaryAdParams, type UserObject };
561
+ export { type Ad, type AdParams, type AdRequestBase, type AdResponse, type ApiErrorResponse, type BidParams, type BidResponse, Client, type ClientParams, type DeviceObject, type Gender, type MessageObject, type NonContextualAdParams, type Placement, type PlacementObject, type RenderContextObject, type RenderParams, type Role, type SummaryAdParams, type UserObject };