fetchAd()

Fetches and renders an ad based on the provided parameters and callbacks.

fetchAd(fetchAdParams, callbacks)

Parameters

fetchAdParams
object
required

Configuration options for fetching ads

callbacks
object

Optional event handlers for the ad fetching process

markAdAsViewed()

Marks an ad as viewed when it becomes visible in the viewport.

markAdAsViewed(impressionId, serverUrl?)

Parameters

impressionId
string
required

The ID of the impression to be marked as viewed

serverUrl
string

The server URL. Defaults to “https://server.megabrain.co

Message Object

The Message object represents a single message in the conversation context. Each message must have:

id
string
required

Unique identifier for the message

createdAt
string | Date
required

Timestamp when message was created (ISO 8601 string or Date object)

role
string
required

Who sent the message: “user” | “assistant”

content
string
required

The text content of the message

Example Message Array

const messages = [
  {
    id: "message-uuid-1",
    createdAt: "2024-12-31T12:00:00.000Z",
    role: "user",
    content: "I am looking for a frying pan."
  },
  {
    id: "message-uuid-2",
    createdAt: "2024-12-31T12:00:05.000Z",
    role: "assistant",
    content: "For a versatile frying pan, consider an all-clad stainless steel..."
  }
];

Error Handling

The SDK provides robust error handling with:

  • Request timeout after 16 seconds by default
  • Automatic retry up to 3 times for retriable errors
  • Unretriable errors include HTTP 403, 429, and 404

Example error handling:

fetchAd(fetchAdParams, {
  onError: (error) => console.error("Ad fetch failed:", error)
});

Best Practices

  1. Chronological Order: Ensure messages are listed in chronological order
  2. Context Completeness: Include sufficient prior messages for context
  3. Assistant Reply: Always end messages array with an “assistant” role message
  4. Unique IDs: Use unique, immutable identifiers for each message