How to Build an AI Chatbot Application with ChatBotKit and Next.js Framework
This tutorial provides a step-by-step guide on how to create a powerful AI chatbot application using the ChatBotKit SDK and Next.js framework. The tutorial covers setting up the environment, creating the necessary pages, and running the application. By the end of this tutorial, you will have a fully functional chatbot application that allows users to interact with the bot and see its responses in real-time.
Key Concepts
One of the key concepts in this tutorial is the ChatBotKit Conversation session. A session is created to provide an easy and secure mechanism for communicating with a chatbot using a predefined set of settings. This is a more secure way of interacting with the chatbot than directly talking to an API, which can be vulnerable to abuse from malicious actors.
The ChatBotKit SDK provides a simple API for creating a conversation session. Once the session is established, the user can interact with the chatbot using the session token. The session token is used to authenticate the user and ensure that the communication is secure.
By using ChatBotKit Conversation sessions, you can easily build powerful AI chatbot applications that provide a secure and easy-to-use interface for developers.
Step By Step Guide
Step 1: Setup
Create a new Next.js project using the following command:
npx create-next-app my-chatbot-app cd my-chatbot-app
Install the required dependencies by running the following command inside your project directory:
npm install @chatbotkit/sdk @chatbotkit/react
Step 2: Create the Pages
Create a new file pages/index.js
and add the following code:
import { AutoTextarea, useConversationManager } from '@chatbotkit/react' export default function Home() { const { conversationId, setConversationId, token, setToken, text, setText, messages, thinking, interact, } = useConversationManager({ stream: true }) async function createSession() { const response = await fetch(`/api/session/create`) if (!response.ok) { throw new Error(`Unexpected error`) } const { conversationId, token } = await response.json() setConversationId(conversationId) setToken(token) } function handleOnKeyDown(event) { // Detect the enter key. if (event.keyCode === 13) { event.preventDefault() // Call the interact method to exchange the message between the user and the bot. interact() } } // Our renderer is quite basic. We simply iterate over the messages and render them accordingly. // We also use our own AutoTextarea for the user input. return ( <div> {conversationId && token ? ( <> <div> {messages.map(({ id, type, text }) => { switch (type) { case 'user': return <div key={id}>user: {text}</div> case 'bot': return <div key={id}>bot: {text}</div> } })} {thinking ? <div key="thinking">bot: thinking...</div> : null} </div> <AutoTextarea value={text} onChange={(e) => setText(event.target.value)} onKeyDown={handleOnKeyDown} /> </> ) : ( <button onClick={() => createSession()}>Start Chat</button> )} </div> ) }
Create a new file pages/api/session.js
and add the following code:
import { ChatBotKit } from '@chatbotkit/sdk' // First, let's create a global instance of the ChatBotKit SDK client. You can // put it in a separate library file and reuse it elsewhere in your project. const cbk = new ChatBotKit({ secret: process.env.CHATBOTKIT_API_SECRET, }) // This method creates a conversation and a session token. We can use the // session token to initialize the React SDK. This way we do not need to build // our own backend but we can leverage ChatBotKit API directly and with that all // other goodies such globally distributed endpoints on the edge and streaming. export default async function handler(req, res) { // Step 1: create a conversation const { id: conversationId } = await cbk.conversation.create({}) // Step 2: create an authentication token for this conversation const { token } = await cbk.conversation.session.create(conversationId, { durationInSeconds: 3600, // 1 hour }) // Step 3: pass the conversationId and the token to the front-end return res.status(200).json({ conversationId, token }) }
Step 3: Run the Application
Start the development server by running the following command in your project directory:
npm run dev
Open your browser and navigate to http://localhost:3000
to see the chatbot application.
That's it! You have successfully created a powerful AI application on top of Next.js using the ChatBotKit SDK. The application allows users to have interactive conversations with the bot and see the bot's responses in real-time.