Creating the Root Page
Great! Let’s build the frontend. The AI SDK’suseChat
hook allows you to easily create a conversational user interface for your agent.
Replace your root page (app/page.tsx
) with the following code:
app/page.tsx
The
useChat
hook enables the streaming of chat messages from your AI
provider (you will be using OpenAI), manages the state for chat input, and
updates the UI automatically as new messages are received.Test the Chat Interface
1
Start the Development Server
Run the following command to start the Next.js dev server:
2
Navigate to the Application
Head to http://localhost:3000. You should see an empty screen with an input bar floating at the bottom.
3
Test Message Sending
Try to send a message. The message shows up in the UI for a fraction of a second and then disappears.
The message disappears because you haven’t set up the corresponding API route
to call the model! By default,
useChat
will send a POST request to the
/api/chat
endpoint with the messages as the request body.You can customize the endpoint in the
useChat
configuration object.Understanding the useChat Hook
TheuseChat
hook provides several key features:
Message Management
Automatic State: Handles message history and roles automatically
Input State
Form Management: Manages input field state and form submission
Streaming Support
Real-time Updates: Streams responses as they arrive from the AI
Error Handling
Built-in Errors: Handles and displays error messages automatically
Hook Configuration Options
You can customize theuseChat
hook with various options). The following is a list of the main functions you can use: