Vercel AI SDK: Xây Chatbot UI Với Streaming Responses Trong Next.js
Hướng dẫn xây dựng chatbot UI với streaming responses sử dụng Vercel AI SDK và Next.js App Router. Từ setup đến deploy chỉ trong 30 phút.
Nếu bạn từng thử build chatbot UI từ scratch, bạn biết pain: handle streaming, manage state, render markdown real-time... Vercel AI SDK giải quyết tất cả trong vài dòng code.
Tại sao Vercel AI SDK?
Vercel AI SDK cung cấp React hooks chuyên biệt cho AI interactions. Thay vì tự handle EventSource, parse chunks, manage conversation history — bạn chỉ cần useChat(). SDK support OpenAI, Anthropic, Google AI, và nhiều provider khác out of the box.
Setup project
Bắt đầu với Next.js App Router project:
npm install ai @ai-sdk/openai
Tạo API route handler — đây là nơi magic xảy ra:
// app/api/chat/route.ts
import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';
export async function POST(req: Request) {
const { messages } = await req.json();
const result = streamText({
model: openai('gpt-4o'),
system: 'Bạn là AI assistant chuyên về frontend development.',
messages,
});
return result.toDataStreamResponse();
}
Build Chat UI Component
Phần frontend cực kỳ clean với useChat hook:
// components/chat-bot.tsx
'use client';
import { useChat } from 'ai/react';
export function ChatBot() {
const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat();
return (
<div className="flex flex-col h-[600px] border rounded-xl">
<div className="flex-1 overflow-y-auto p-4 space-y-4">
{messages.map((m) => (
<div key={m.id} className={m.role === 'user' ? 'text-right' : 'text-left'}>
<div className={}>
{m.content}
</div>
</div>
))}
</div>
<form onSubmit={handleSubmit} className="p-4 border-t flex gap-2">
<input
value={input}
onChange={handleInputChange}
placeholder="Hỏi gì đó về frontend..."
className="flex-1 px-4 py-2 border rounded-lg"
/>
<button type="submit" disabled={isLoading}
className="px-6 py-2 bg-blue-600 text-white rounded-lg">
{isLoading ? 'Đang trả lời...' : 'Gửi'}
</button>
</form>
</div>
);
}
Các tính năng nâng cao
Vercel AI SDK còn hỗ trợ nhiều feature hữu ích:
- Tool calling: Cho phép AI gọi functions bạn define, ví dụ search database hoặc fetch API
- Generative UI: Stream React components thay vì chỉ text — game changer cho interactive responses
- Multi-modal: Gửi images kèm text messages
- Rate limiting: Dễ dàng integrate với middleware
Tips production
Một số điều cần lưu ý khi deploy:
- Luôn set
maxTokensđể control cost - Implement error boundary cho chat component
- Cache system prompt ở server side
- Dùng
onFinishcallback để log conversations vào database - Consider dùng Edge Runtime cho lower latency
Vercel AI SDK là tool tốt nhất hiện tại cho việc build AI-powered UI trong React ecosystem. Nếu bạn đang plan build bất kỳ AI feature nào cho frontend app, đây là starting point hoàn hảo.
Admin
Bình luận (0)
Đăng nhập để bình luận
Chưa có bình luận nào. Hãy là người đầu tiên!