Documentation

Getting started

Add AgentAds to your AI app in 5 minutes. Works with React, Next.js, Vercel AI SDK, NVIDIA Agent Toolkit, and any Node.js or Python app.

01

Quick start

1. Install the SDK

sh
npm install @agentads/sdk
# or
yarn add @agentads/sdk
# or
pnpm add @agentads/sdk

2. Get your API key

Sign up at app.tryagentads.com and copy your publisher API key from the Integration page.

sh
# .env.local
AGENTADS_KEY=pub_live_xxxxxxxxxxxxxxxxxxxx

3. Wrap your model (Vercel AI SDK)

ts
import { openai } from '@ai-sdk/openai'
import { withAgentAds } from '@agentads/sdk'

// Drop-in replacement — same API, same streaming
const model = withAgentAds(openai('gpt-4o'), {
  publisherApiKey: process.env.AGENTADS_KEY!,
})

// Use exactly like before
const result = await generateText({ model, prompt: userMessage })
// result.text now includes a contextual ad if matched
// → "...your answer...

---
**Sponsored:** Clerk — Auth in 5 minutes..."

That's it.

The SDK runs a 50ms real-time auction in the background. If a relevant ad is found, it's appended after the AI response. If not (no fill, timeout, or low-intent query), nothing happens. Your users never experience latency.

02

React component

If you're building a React or Next.js chat UI, use the drop-in <AgentAd /> component. It handles fetching, rendering, and click tracking automatically. Shows nothing on no-fill — zero layout shift.

Basic usage

tsx
import { AgentAd } from '@agentads/sdk/react'

export function ChatMessage({ query, response }: { query: string; response: string }) {
  return (
    <div>
      <p>{response}</p>

      {/* Renders a sponsored card after each assistant message */}
      <AgentAd
        publisherApiKey={process.env.NEXT_PUBLIC_AGENTADS_KEY!}
        query={query}
        response={response}
      />
    </div>
  )
}

What it renders

SponsoredClerk — Auth in 5 minutes

Add sign-in, user management, and MFA to your app with 4 lines of code. Free up to 10k MAU.

All props

PropTypeDescription
publisherApiKeystringYour publisher API key (required)
querystringThe user's message or prompt
responsestringThe AI response text (first 200 chars used)
apiUrlstring?Override API URL (default: api.tryagentads.com)
timeoutnumber?Auction timeout in ms (default: 50)

Next.js example — after assistant messages

tsx
// components/messages.tsx
import { AgentAd } from '@agentads/sdk/react'

export function Messages({ messages }: { messages: Message[] }) {
  return messages.map((msg, i) => {
    const prevMsg = messages[i - 1]
    return (
      <div key={msg.id}>
        <MessageBubble message={msg} />

        {/* Show ad after each assistant response */}
        {msg.role === 'assistant' && (
          <AgentAd
            publisherApiKey={process.env.NEXT_PUBLIC_AGENTADS_KEY!}
            query={prevMsg?.role === 'user' ? prevMsg.content : ''}
            response={msg.content}
          />
        )}
      </div>
    )
  })
}

03

Node.js / fetch API

Use fetchAd() for full control — works in any Node.js environment, edge functions, or server-side code.

ts
import { fetchAd } from '@agentads/sdk'

const ad = await fetchAd({
  publisherApiKey: process.env.AGENTADS_KEY!,
  query: userMessage,
  response: aiResponse,   // first 200 chars used for classification
  timeout: 50,            // ms — never delays your response
})

if (ad) {
  // Append to your response however you like
  const sponsored = `\n\n---\n**Sponsored:** ${ad.headline}\n${ad.description} — [${ad.ctaText}](${ad.clickUrl})`
  return aiResponse + sponsored
}

// ad === null → no fill, timeout, or error — safe to ignore

Manual fetch (no SDK)

ts
const res = await fetch('https://api.tryagentads.com/bid', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-Publisher-Key': 'pub_live_...',
  },
  body: JSON.stringify({
    query: userMessage,
    response: aiResponse.slice(0, 200),
    format: 'suffix',   // 'suffix' | 'citation' | 'followup'
  }),
  signal: AbortSignal.timeout(50),
})

const data = await res.json()
// data.filled === true → data.ad has headline, description, cta, clickUrl
// data.filled === false → no auction winner

Python (requests)

python
import requests

try:
    r = requests.post(
        'https://api.tryagentads.com/bid',
        headers={'X-Publisher-Key': 'pub_live_...'},
        json={'query': user_message, 'response': ai_response[:200]},
        timeout=0.05  # 50ms
    )
    data = r.json()
    if data.get('filled') and data.get('ad'):
        ad = data['ad']
        sponsored = f"\n\n---\nSponsored: {ad['headline']} — {ad['cta']}: {ad['clickUrl']}"
        response_text += sponsored
except requests.exceptions.Timeout:
    pass  # No ad — always safe to ignore

04

Conversion tracking

Track when a user converts after clicking your ad. Works automatically — when a user clicks an ad, we append ?aads_tid=... and ?aads_token=... to the destination URL. The pixel on the advertiser's thank-you page reads them and records the conversion.

This is an advertiser feature

Publishers don't need to do anything. The tracking params are appended automatically by AgentAds on every ad click. Advertisers get the conversion pixel snippet in their campaign analytics dashboard.

Advertiser pixel — paste on your thank-you / confirmation page

html
<!-- AgentAds Conversion Pixel -->
<script>
(function() {
  var params = new URLSearchParams(window.location.search);
  var tid = params.get('aads_tid');
  var token = params.get('aads_token');
  if (!tid || !token) return;
  new Image().src =
    'https://api.tryagentads.com/v1/convert' +
    '?tid=' + encodeURIComponent(tid) +
    '&token=' + encodeURIComponent(token) +
    '&value=VALUE_CENTS';  // replace with order value, e.g. 4900 for $49
})();
</script>

How it works

  1. 1User sees your ad in an AI response and clicks it
  2. 2AgentAds appends ?aads_tid=TRACKING_ID&aads_token=HMAC_TOKEN to your destination URL
  3. 3User lands on your site with those params in the URL
  4. 4On your thank-you page, the pixel reads the params and fires a 1px request to api.tryagentads.com/v1/convert
  5. 5Conversion is logged to your campaign — you see conversions + ROAS in your dashboard

Attribution window

30-day attribution. Conversions are deduplicated by tracking ID — one conversion per click, regardless of how many times the pixel fires. The HMAC token prevents fake conversion submissions.

05

API reference

POST/bid— Request an ad

Base URL: https://api.tryagentads.com

Request headers

HeaderValue
Content-Typeapplication/json
X-Publisher-Keypub_live_...

Request body

FieldTypeDescription
querystringThe user's message or prompt (required)
responsestringAI response text, first 200 chars used (required)
format'suffix' | 'citation' | 'followup'Ad placement format (default: suffix)
sessionIdstring?Hashed session ID for frequency capping

Response

json
// filled
{
  "filled": true,
  "requestId": "abc123",
  "ad": {
    "format": "suffix",
    "headline": "Clerk — Auth in 5 minutes",
    "description": "Add sign-in and user management with 4 lines of code.",
    "cta": "Get started free",
    "clickUrl": "https://api.tryagentads.com/click/track_xyz",
    "label": "Ad"
  }
}

// no fill
{
  "filled": false,
  "requestId": "abc123"
}
GET/v1/convert— Record a conversion
ParamDescription
tidTracking ID from ?aads_tid URL param
tokenHMAC token from ?aads_token URL param
valueConversion value in cents (e.g. 4900 for $49)

Returns a 1×1 transparent GIF. Deduped by tracking ID. HMAC-verified to prevent forgery.

06

NVIDIA Agent Toolkit (Python)

Building agents on NVIDIA's NeMo Agent Toolkit? Install agentads-nat to monetize any NAT workflow with 3 lines of YAML config. Works with all NAT agent types — ReAct, reasoning, router, and custom agents.

1. Install

sh
pip install agentads-nat

2. Add to your workflow config

yaml
# config.yaml
functions:
  monetize:
    _type: agentads_monetize
    publisher_api_key: ${AGENTADS_API_KEY}
    format: suffix        # suffix | citation | followup
    timeout_ms: 50        # never blocks your agent

workflow:
  _type: react_agent
  tool_names: [your_tools, monetize]
  llm_name: your_llm

3. Run

sh
export AGENTADS_API_KEY=pub_live_xxx
nat run --config_file config.yaml --input "What CRM should I use?"

Also works standalone.

Don't use NAT? The Python package works with any agent framework — just call monetize_output(config, response, query) to append an ad to any string output.

Standalone usage (any Python agent)

python
from agentads_nat import AgentAdsConfig, monetize_output

config = AgentAdsConfig(publisher_api_key="pub_live_xxx")

# Your agent produces a response
response = await my_agent(query)

# One line to monetize
result = await monetize_output(config, response, query=query)
# → response + contextual ad appended (or unchanged on no-fill)

OpenShell network policy

Running inside NVIDIA OpenShell? Apply the included policy to allow only the required API call:

sh
openshell policy set agentads --policy policies/agentads.yaml --wait
# Allows only POST /v1/bid to api.tryagentads.com

Configuration

OptionDefaultDescription
publisher_api_keyrequiredYour publisher API key
formatsuffixAd rendering format (suffix, citation, followup)
timeout_ms50Bid timeout in ms - never blocks your agent
disabledfalseKill switch to disable ads
session_idnullSession ID for frequency capping

View on PyPI ↗ · GitHub ↗