Unit 5: Developing an Intelligent AI Chatbot
Welcome to Unit 5 of the Avarix AI Development Program! This comprehensive module focuses on building sophisticated AI-powered chatbots by leveraging OpenAI's technology with the Vercel AI SDK in a Next.js environment. You'll master project initialization, chatbot implementation, and real-time response streaming using cutting-edge Edge Runtime capabilities.
Lesson 5.1: Developing Your Next.js AI-Powered Chat Application
Master the process of building and configuring a Next.js application with intelligent chatbot capabilities.
Project Initialization
- Launch a fresh empty codespace environment
- Initialize a Next.js application with the following command:
npx create-next-app@latest
Important: Ensure you extract all contents from the generated app directory to the root level, otherwise the application will not function properly. Refer to the instructional video for guidance.
Package Installation
Add the necessary Vercel AI SDK and OpenAI libraries to your project:
pnpm install ai openai
Environment Configuration
- Generate a .env file in your project's root directory (right-click to create new file)
- Insert your OpenAI API credentials. OBTAIN THE API KEY FROM YOUR INSTRUCTOR OR CONTACT US DIRECTLY - THIS IS CONFIDENTIAL:
OPENAI_API_KEY=your_openai_api_key
Building the AI Chat API Endpoint
Establish app/api/chat/route.ts to manage chat communication:
import OpenAI from 'openai'
import { OpenAIStream, StreamingTextResponse } from 'ai'
const openai = new OpenAI(process.env.OPENAI_API_KEY)
export const runtime = 'edge'
export async function POST(req: Request) {
const { messages } = await req.json()
console.log(messages)
// Inject a system message at the beginning of the conversation
messages.unshift({
role: 'system',
content:
'You are an enthusiastic teacher who explains everything using simple examples.',
})
console.log(messages)
const response = await openai.chat.completions.create({
model: 'gpt-3.5-turbo',
stream: true,
messages,
})
const stream = OpenAIStream(response)
return new StreamingTextResponse(stream)
}
This API handler integrates with OpenAI's chat completion service and delivers streaming responses in real-time.
Designing the Chat Interface
Modify app/page.tsx to implement the interactive chat interface:
'use client'
import { useChat } from 'ai/react'
export default function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat()
return (
<main className="mx-auto flex h-screen w-full max-w-lg flex-col bg-indigo-500 p-6">
<section className="mb-4 overflow-auto rounded-lg bg-white p-4 shadow">
{messages.map((m) => (
<div
className={`mb-2 rounded-md p-2 ${
m.role === 'user' ? 'bg-indigo-200' : 'bg-emerald-200'`}
key={m.id}
>
<strong>{m.role === 'user' ? 'You: ' : 'Assistant: '}</strong>
{m.content}
</div>
))}
</section>
<form className="mt-auto flex space-x-4" onSubmit={handleSubmit}>
<input
className="flex-grow rounded-md border-2 border-gray-300 p-2 text-black"
value={input}
onChange={handleInputChange}
placeholder="Type your message..."
/>
<button
className="rounded-md bg-indigo-600 p-2 text-white hover:bg-indigo-700"
type="submit"
>
Send
</button>
</form>
</main>
)
}
Personalizing Your Assistant
- Modify the system prompt to reflect your chatbot's unique personality
- Customize the visual design and color scheme
- Leverage AI assistance to enhance your chatbot's functionality
Lesson 5.2: Advanced Next.js AI Chatbot Implementation Guide
Elevate your chatbot by creating a specialized, theme-focused application.
Enhanced Interface Design
Transform your chatbot interface in app/page.tsx with a health & wellness theme:
'use client'
import { useChat } from 'ai/react'
export default function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat()
return (
<main className="mx-auto mb-auto flex h-screen w-full max-w-lg flex-col bg-emerald-400 p-6">
<span className="mb-4 bg-gradient-to-r from-teal-400 to-teal-600 bg-clip-text text-3xl font-bold text-transparent drop-shadow-[0_1.2px_1.2px_rgba(0,0,0,0.8)]">
WellnessBot Pro
</span>
<section className="mb-4 overflow-auto rounded-lg bg-white p-4 shadow">
{messages.map((m) => (
<div
className={`mb-2 rounded-md p-2 ${
m.role === 'user' ? 'text-white-400 bg-teal-400' : 'text-white-400 bg-slate-400'`}
key={m.id}
>
<strong>{m.role === 'user' ? 'You: ' : 'Coach: '}</strong>
{m.content}
</div>
))}
</section>
<form className="mt-auto flex space-x-4" onSubmit={handleSubmit}>
<input
className="flex-grow rounded-md border-2 border-gray-300 p-2 text-black"
value={input}
onChange={handleInputChange}
placeholder="Ask about your wellness..."
/>
<button
className="text-white-400 rounded-md bg-teal-400 p-2 hover:bg-teal-500"
type="submit"
>
Send
</button>
</form>
</main>
)
}
Implementing a Welcome Screen
Create an engaging landing page in app/page.tsx that greets users before accessing the chatbot:
'use client'
import { useState } from 'react'
function LandingPage({ onStartChat }) {
return (
<main className="fixed inset-0 flex items-center justify-center bg-emerald-500">
<div className="animate__animated animate__fadeIn mx-auto flex w-full max-w-lg flex-col items-center justify-center rounded-lg bg-emerald-500 p-8 shadow-lg">
<h1 className="mb-6 text-3xl font-bold">
<span className="bg-gradient-to-r from-teal-400 to-teal-600 bg-clip-text text-transparent drop-shadow-[0_1.2px_1.2px_rgba(0,0,0,0.8)]">
Welcome to Wellness AI
</span>
</h1>
<button
className="rounded-md border border-black bg-teal-500 p-3 text-white transition duration-300 hover:bg-teal-600"
onClick={onStartChat}
>
Begin Journey
</button>
</div>
</main>
)
}
Implementing Screen Navigation Logic
Add the main App component to app/page.tsx that manages screen transitions:
'use client'
export default function App() {
const [isChatStarted, setIsChatStarted] = useState(false)
const handleStartChat = () => {
setIsChatStarted(true)
}
//when the button is pressed
return isChatStarted ? (
<Chat />
) : (
<LandingPage onStartChat={handleStartChat} />
)
}
To expand with additional screens, create new functions like function profilePage(), design your layouts, and request ChatGPT assistance to integrate navigation logic within the App component.
Assignment: Custom AI Assistant
Design and develop your own unique AI chatbot application with personalized features.
Project Foundation
Complete Lessons 5.1 and 5.2 to establish your working chatbot foundation. Once operational, customize and transform it into your unique creation.
Project Requirements
- Implement personalized system instructions
- Redesign the HTML structure to reflect your vision
- Apply custom CSS styling for enhanced visual appeal
- Upload your completed project to Schoology for evaluation
Was this page helpful?