To get started, you will need to set up a publisher account to get a publisherToken
and code
1. Import the SDK
<script type="module">
import { fetchAd } from 'https://server.megabrain.co/sdk/js';
</script>
In case fetchAd
can’t be accessed, you might need to make fetchAd
available globally.
<script type="module">
import { fetchAd } from 'https://server.megabrain.co/sdk/js';
window.fetchAd = fetchAd
</script>
2. Assemble messages & set up params
Firstly you will need to prepare a list of messages exchanged between assistant and user. They are used to determine which ads to show. Order of messages is important and it should always end with the last assistant message.
const messages = [
{
id: "message-uuid", // Any string id. Must be unique
createdAt: "2024-12-31T12:00:00.000Z" // ISO string or data object
role: "user", // "user" | "assistant"
content: "I am looking for a frying pan."
},
{
id: "message-uuid2",
createdAt: "2024-12-31T12:00:06.000Z",
role: "assistant",
content: "For a versatile frying pan, consider an all-clad stainless steel or non-stick hard-anodized aluminum pan, 10–12 inches in size, depending on your needs."
}
]
If you are integrating Kontext to a human-to-human messaging app, just use
role “assistant” for everyone else apart from the current user. This works well
both in 1:1 and group chat setups.
Create your params object
This object is used to call the fetchAd
function. Based on the params, it will determine what product and ad copy to show.
const fetchAdParams = {
publisherToken: "example-token", // Received during account setup
code: "example-code", // Received during account setup
userId: "user-uuid", // A persistent user identifier - user uuid or email hash works great
conversationId: "conversation", // Id of the current conversation the user is having with the bot
logLevel: "silent", // "debug" | "info" | "log" | "warn" | "error" | "silent"
messages: messages, // List of messages between assistant and user
element: document.getElementById("ad-container") // div where ad will be rendered
}
3. Show your first ad
To understand how the ad request works, check out our fetchAd docs.
At this point, you are all set. You can now call the fetchAd
function which also has a few optional callbacks that can be used for your analytics or rendering logic.
fetchAd(fetchAdParams, {
onStart: () => {/* Called just before the ad server request */ },
onComplete: (content, metadata) => {/* Called when ad is completely streamed */},
onError: (error: any) => {/* Called when streaming encounters an error */},
onBid: (value: number | null) => Promise<boolean> {/* Called when an ad is available to fill your ad slot along with the bid value for the ad. Return true if you want to render the ad. */}
onAdClick: (impression: { id: string, content: string }) => {/* Called when ad is clicked (for your analytics) */},
onAdView: (impression: { id: string, content: string }) => {/* Called when ad is viewed (for your analytics) */},
})