Next.js Chat UI Example
This is a simple Next.js application demonstrating how to use the @llamaindex/chat-ui library to build a chat interface.
Features
- Basic chat interface using
@llamaindex/chat-uicomponents - API route that integrates with LlamaIndex and OpenAI
- Fallback to fake streaming when API key is not available
- TypeScript support
Getting Started
-
Install dependencies:
npm install -
Set your OpenAI API key:
export OPENAI_API_KEY=your-api-key-here -
Start the development server:
npm run dev -
Open http://localhost:3000 in your browser.
Project Structure
app/page.tsx- Main chat interfaceapp/layout.tsx- Root layoutapp/api/chat/route.ts- Chat API endpoint using LlamaIndexapp/rsc/- React Server Components example with server actionspackage.json- Dependencies and scriptsnext.config.js- Next.js configurationtsconfig.json- TypeScript configuration
Examples
This project includes multiple examples to demonstrate different approaches:
1. Default Chat Interface
The standard implementation using client-side components with the useChat hook from Vercel AI SDK
2. Rendering Inline Annotations Example
Enable: Uncomment the advanced API route in app/page.tsx
Demonstrates inline annotations in the chat interface.
3. Edge Runtime Example
Enable: Uncomment the edge API route in app/page.tsx
Showcases running the chat API on Vercel's Edge Runtime for global distribution
4. RSC (React Server Components) Example
URL: http://localhost:3000/rsc
Demonstrates React Server Components with server actions for chat functionality.
-
AI Provider Setup (
ai.ts):- Creates an AI provider using
createAIfrom Vercel AI SDK - Defines server state (Message[]) and UI state (Message with ReactNode display)
- Exposes
chatActionas a server action
- Creates an AI provider using
-
Server Actions (
action.tsx):chatActionruns entirely on the server with'use server'directive- Uses
createStreamableUI()to stream React components to the client - Processes chat messages and returns React components as responses
- Demonstrates streaming with fake chat data including inline annotations
-
RSC Chat Hook (
use-chat-rsc.tsx):- Bridges server actions with @llamaindex/chat-ui components
- Uses
useUIStateanduseActionsto manage RSC state - Provides the same interface as the standard
useChathook - Handles message appending and UI updates seamlessly
-
Page Component (
page.tsx):- Uses the custom
useChatRSC()hook instead ofuseChat - Renders messages with server-generated React components
- Integrates with ChatCanvas for advanced UI features
- Uses the custom