Creating the Root Page

Great! Let’s build the frontend. The AI SDK’s useChat 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
"use client";

import { useChat } from "@ai-sdk/react";
import { useState } from "react";

export default function Chat() {
  const [input, setInput] = useState("");
  const { messages, sendMessage } = useChat();
  return (
    <div className="flex flex-col w-full max-w-md py-24 mx-auto stretch">
      <div className="space-y-4">
        {messages.map((m) => (
          <div key={m.id} className="whitespace-pre-wrap">
            <div>
              <div className="font-bold">{m.role}</div>
              {m.parts.map((part) => {
                switch (part.type) {
                  case "text":
                    return <p>{part.text}</p>;
                }
              })}
            </div>
          </div>
        ))}
      </div>

      <form
        onSubmit={(e) => {
          e.preventDefault();
          sendMessage({ text: input });
          setInput("");
        }}>
        <input
          className="fixed bottom-0 w-full max-w-md p-2 mb-8 border border-gray-300 rounded shadow-xl"
          value={input}
          placeholder="Say something..."
          onChange={(e) => setInput(e.currentTarget.value)}
        />
      </form>
    </div>
  );
}
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:
pnpm run dev
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

The useChat 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 the useChat hook with various options). The following is a list of the main functions you can use:
const { messages, sendMessage } = useChat({
  api: "/api/chat/mycustom-route", // Defaults to /api/chat
  initialMessages: [], // Pre-populate with messages
  onData: (response) => {
    // Handle response
  },
  onFinish: (message) => {
    // Handle completion
  },
  onError: (error) => {
    // Handle errors
  },
});

Extension task