Make a chatbot
I'll guide you through creating a simple chatbot using the AI SDK and Next.js with the App Router. This chatbot will use OpenAI's GPT-4 model for generating responses. Let's break it down into steps:
Step 1: Set up your Next.js project
First, create a new Next.js project if you haven't already:
npx create-next-app@latest chatbot-app
cd chatbot-appStep 2: Install dependencies
Install the required packages:
npm install ai @ai-sdk/openaiStep 3: Create the API route
Create a new file app/api/chat/route.ts with the following content:
import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';
// Allow streaming responses up to 30 seconds
export const maxDuration = 30;
export async function POST(req: Request) {
const { messages } = await req.json();
const result = streamText({
model: openai('gpt-4-turbo'),
messages,
});
return result.toDataStreamResponse();
}This API route uses the streamText function from the AI SDK to generate responses from the OpenAI model . It streams the response back to the client, allowing for real-time updates in the chat interface.
Step 4: Create the chat component
Now, let's create the main chat component. Create or update the file app/page.tsx:
'use client'
import { useChat } from 'ai/react'
import { useState } from 'react'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
export default function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat()
const [isTyping, setIsTyping] = useState(false)
const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
setIsTyping(true)
handleSubmit(e).finally(() => setIsTyping(false))
}
return (
<div className="flex items-center justify-center min-h-screen bg-gray-100">
<Card className="w-full max-w-2xl">
<CardHeader>
<CardTitle>AI Chat</CardTitle>
</CardHeader>
<CardContent className="h-[60vh] overflow-y-auto">
{messages.map(m => (
<div key={m.id} className={`mb-4 ${m.role === 'user' ? 'text-right' : 'text-left'}`}>
<span className={`inline-block p-2 rounded-lg ${m.role === 'user' ? 'bg-blue-500 text-white' : 'bg-gray-200 text-black'}`}>
{m.content}
</span>
</div>
))}
{isTyping && (
<div className="text-left">
<span className="inline-block p-2 rounded-lg bg-gray-200 text-black">
AI is typing...
</span>
</div>
)}
</CardContent>
<CardFooter>
<form onSubmit={onSubmit} className="flex w-full space-x-2">
<Input
value={input}
onChange={handleInputChange}
placeholder="Type your message..."
className="flex-grow"
/>
<Button type="submit" disabled={isTyping}>Send</Button>
</form>
</CardFooter>
</Card>
</div>
)
}This component uses the useChat hook from the AI SDK UI to manage the chat state and handle user input 1. It renders a simple chat interface with messages and an input form.
Step 5: Configure OpenAI API key
Create a .env.local file in your project root and add your OpenAI API key:
OPENAI_API_KEY=your_api_key_hereReplace your_api_key_here with your actual OpenAI API key.
Step 6: Run your application
Now you can start your Next.js application:
npm run devVisit http://localhost:3000 in your browser to interact with your chatbot.
This implementation creates a simple chatbot that uses the AI SDK to interact with OpenAI's GPT-4 model. The chat interface streams responses in real-time, providing a smooth user experience .
You can further customize this chatbot by:
Remember to replace the placeholder OpenAI API key in the .env.local file with your actual API key before running the application.