Skip to content

Next JS (AI SDK)

If your AI chatbot is running on a NextJS backend with AI SDK, use this guide to send user conversation data to Growl.

If you’re using streamText to generate LLM responses, you can send conversation data to Growl by calling the after method in onFinish parameter of streamText.

import recordGrowlEvent from "./growl";
export async function POST(req: Request) {
// extract user chat message and visitor_id from client
// visitor_id is required - must be obtained from window.GrowlAds.getVisitorId() on client-side
const { prompt, visitor_id }: { prompt: string; visitor_id: string } = await req.json();
const result = streamText({
model: openai("gpt-4"),
prompt,
// ...
// Implement this
onFinish: async ({ text }) => {
const headersObject = Object.fromEntries(req.headers.entries());
after(async () => {
await recordGrowlEvent({
publisher_id: "<your-publisher-id>",
user_id: "<user-id>",
user_email: "<user-email>",
visitor_id: visitor_id, // from client: await GrowlAds.getVisitorId()
chat_id: null,
headers: headersObject,
user_message: { text: prompt },
ai_message: { text: text },
});
});
},
});
return result.toUIMessageStreamResponse();
}

If you’re using AI SDK’s generateText function, you can schedule the HTTP call to Growl using the after function provided by Next.JS SDK.

import recordGrowlEvent from "./growl";
import { ModelMessage, generateText } from "ai";
import { openai } from "@ai-sdk/openai";
import { after } from "next/server";
export async function POST(req: Request) {
// visitor_id is required - must be obtained from window.GrowlAds.getVisitorId() on client-side
const { messages, visitor_id }: { messages: ModelMessage[]; visitor_id: string } = await req.json();
const { response } = await generateText({
model: openai("gpt-4"),
system: "You are a helpful assistant.",
messages,
});
const headersObject = Object.fromEntries(req.headers.entries());
// schedule HTTP POST call with user data to Growl
after(async () => {
await recordGrowlEvent({
publisher_id: "<your-publisher-id>",
user_id: "<user-id>",
user_email: "<user-email>",
visitor_id: visitor_id, // from client: await GrowlAds.getVisitorId()
chat_id: "<chat-id>",
headers: headersObject,
user_message: { text: messages[messages.length - 1] },
ai_message: { text: response.messages[0].content },
});
});
// send response to user
return Response.json({ messages: response.messages });
}