> ## Documentation Index
> Fetch the complete documentation index at: https://publisher-docs.thrads.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Sponsored Prompt Integration

> Learn how to integrate sponsored prompts into your conversational AI application.

# Integrating Sponsored Prompts

This guide provides comprehensive instructions on integrating sponsored prompts within your conversational AI. It covers essential aspects such as environment modes, tracking and more.

## Production vs. Sandbox Mode

<Note intent="warning">
  **Important:** When integrating sponsored prompts, it's crucial to
  distinguish between production and sandbox (non-production) environments. - In
  **sandbox mode** (`production=False`), ads are returned for testing purposes
  but are **not counted for monetization**. - In **production mode**
  (`production=True`), ads are live and contribute to monetization. Always
  ensure `production=True` is used *only* in your live production environment.
  For all testing and development, set `production=False`.
</Note>

## Using Sponsored Prompts

Sponsored prompts can be incorporated into your AI conversations in two primary ways: as an initial opener or as contextual follow-up questions.

<Tabs>
  <Tab title="Sponsored Opener">
    ### Starting Conversations with Sponsored Openers

    You can use the sponsored question endpoint to generate an "opener" – a question to initiate a conversation.

    **Key Points:**

    * **No Context Needed:** Simply call the endpoint without any prior conversational context.
    * **Tailored for Your App:** The API will provide a sponsored question suitable for your application, yet conversation-agnostic.
    * **Unaffected by `conversationalOffset` and `adFrequency` and `force`:** These parameters do not influence the behavior of opener prompts.

    **Code Example:**

    <CodeGroup>
      ```python Python theme={null}
      import requests

      url = "https://dev.thrads.ai/api/v1/prompt/get-ad/"

      payload = {
          "userId": "123",
          "chatId": "123"
      }
      headers = {
          "Thrads-Api-Key": "YOUR_API_KEY",
          "Content-Type": "application/json"
      }

      response = requests.request("POST", url, json=payload, headers=headers)

      print(response.text)
      ```

      ```javascript JavaScript theme={null}
      const url = "https://dev.thrads.ai/api/v1/prompt/get-ad/";

      const payload = {
        userId: "123",
        chatId: "123",
      };

      const headers = {
        "Thrads-Api-Key": "YOUR_API_KEY",
        "Content-Type": "application/json",
      };

      const response = await fetch(url, {
        method: "POST",
        headers: headers,
        body: JSON.stringify(payload),
      });

      const result = await response.text();
      console.log(result);
      ```
    </CodeGroup>
  </Tab>

  <Tab title="Sponsored Follow-up">
    ### Incorporating Sponsored Follow-up Prompts

    To provide relevant sponsored content during an ongoing conversation, use the endpoint for follow-up prompts.

    **Key Points:**

    * **Context is Crucial:** Call this endpoint after each AI-generated response.

    <Note intent="warning">
      **Important:** You must call the endpoint at every turn—even if the ad isn't wanted (configurable via settings like `adFrequency`, explained below). This enables conversation tracking, ensures relevant follow-ups, and maintains ad effectiveness. Skipping it degrades performance and monetization.
    </Note>

    * **Control Ad Frequency:** Manage the number of ads shown using the `adFrequency` and `conversationalOffset` parameters.
    * **`force` Parameter:** Use the `force` parameter if you need to override default frequency settings for specific scenarios.

    **Code Example:**

    <CodeGroup>
      ```python Python theme={null}
      import requests

      url = "https://dev.thrads.ai/api/v1/prompt/get-ad/"

      payload = {
          "production": True,
          "conversationOffset": 2,
          "adFrequencyLimit": 2,
          "userId": "123",
          "chatId": "123",
          "userRegion": "US",
          "content": {
              "user": "User message",
              "chatbot": "Bot message"
          }
      }
      headers = {
          "Thrads-Api-Key": "YOUR_API_KEY",
          "Content-Type": "application/json"
      }

      response = requests.request("POST", url, json=payload, headers=headers)

      print(response.text)
      ```

      ```javascript JavaScript theme={null}
      const url = "https://dev.thrads.ai/api/v1/prompt/get-ad/";

      const payload = {
        production: true,
        conversationOffset: 2,
        adFrequencyLimit: 2,
        userId: "123",
        chatId: "123",
        userRegion: "US",
        content: {
          user: "User message",
          chatbot: "Bot message",
        },
      };

      const headers = {
        "Thrads-Api-Key": "YOUR_API_KEY",
        "Content-Type": "application/json",
      };

      const response = await fetch(url, {
        method: "POST",
        headers: headers,
        body: JSON.stringify(payload),
      });

      const result = await response.text();
      console.log(result);
      ```
    </CodeGroup>

    ## Recommended Implementation Flow

    This is the general recommended flow for the integration.

    <Steps>
      <Step title="User sends a message">
        Capture the user message and forward to your chatbot service
      </Step>

      <Step title="Chatbot processes and responds">
        Your chatbot generates and returns a response
      </Step>

      <Step title="Call Thrads API">
        As soon as the chatbot response is recived send both the user message and chatbot response to Thrads
      </Step>

      <Step title="Render Ad">
        Display the sponsored prompt as a suggested follow-up question with visual branding:

        * Include the ad icon to displose advertisement (provided in response)
        * Include the name of the brand (provided in response) for visual recognition
        * Present as clickable suggested questions below the chat, or as “tabbable” ghost text in the input bar (users can press Tab to accept the suggestion)
      </Step>

      <Step title="Handle Click Tracking">
        Handle it just as explained below
      </Step>
    </Steps>
  </Tab>
</Tabs>

## Handling Click Tracking

To ensure accurate monetization and analytics, you must track user clicks on sponsored messages.

<Steps>
  <Step title="Receive the Token">
    The sponsored prompts endpoint (for both openers and follow-ups) returns a unique `token` along with the sponsored question. Store this token.
  </Step>

  <Step title="Detect User Interaction">
    When a user clicks or taps on the displayed sponsored question.
  </Step>

  <Step title="Send Click Confirmation">
    Immediately send a POST request to the `/api/v1/prompt/click/` endpoint. Include the `token` (received in Step 1) in the JSON body of your request.

    ```json theme={null}
    {
      "token": "THE_UNIQUE_TOKEN_RECEIVED"
    }
    ```
  </Step>

  <Step title="Receive Reward Confirmation">
    A successful POST request to the click tracking endpoint will record the click and associate the reward.
  </Step>
</Steps>

**Code Example for Click Tracking:**

<CodeGroup>
  ```python Python theme={null}
  import requests

  url = "https://api.thrads.ai/api/v1/prompt/click/"

  payload = {"token": "<string>"}
  headers = {"Content-Type": "application/json"}

  response = requests.request("POST", url, json=payload, headers=headers)

  print(response.text)
  ```

  ```javascript JavaScript theme={null}
  const url = "https://api.thrads.ai/api/v1/prompt/click/";

  const payload = { token: "<string>" };
  const headers = { "Content-Type": "application/json" };

  const response = await fetch(url, {
    method: "POST",
    headers: headers,
    body: JSON.stringify(payload),
  });

  const result = await response.text();
  console.log(result);
  ```
</CodeGroup>

## Best Practices

### 1. Use Metadata for Better Targeting

```python theme={null}
payload = {
    "userId": "user123",
    "chatId": "chat456",
    "content": content,
    "metaData": {
        "topic": "outdoor gear",
        "user_interests": "camping, hiking, outdoor",
        "conversation_stage": "gear_selection"
    },
    "production": True
}
```

### 2. Control Ad Frequency (**Only for follow-up**)

Use `adFrequencyLimit` and `conversationOffset` to prevent ad fatigue:

```python theme={null}
payload = {
    "userId": "user123",
    "chatId": "chat456",
    "content": content,
    "adFrequencyLimit": 2,  # Maximum of 1 ad every 2 turns
    "conversationOffset": 5,  # Wait for 5 turns before showing ads
    "production": True
}

```

### 3. **Managing Response Delays**

In rare cases, the Thrads API response might be delayed (typically between 0.5-0.8 seconds). During this time, the user may begin typing a new question. **We recommend to have some logic in place to suppress the ad render if that arrives late.**

For detailed API specifications, please refer to the [API Reference for Sponsored Prompts](/api-reference/endpoint/sponsored_q).
