Sorry not compatible with mobile devices
Newton Raul
useChat()
What is useChat?
The useChat hook is one of the core utilities provided by the Vercel AI SDK for building conversational AI applications. In this section, we'll focus on covering the basics of message handling, API communication, streaming, and state management. The Vercel AI SDK offers many more advanced capabilities, so for a deeper dive into the hook and its full feature set, we recommend exploring the Official Vercel AI SDK documentation.
The useChat hook returns a set of functions & states that can be used to build AI interfaces fast such as:
'use client';
import { useChat } from '@ai-sdk/react';
import React from 'react';
export const page = () => {
const { messages, sendMessage, status, error, regenerate, stop } = useChat();
return <div>....</div>;
};sendMessage
sendMessage is a function provided by the useChat hook that sends a user's message to the configured API route and automatically updates the conversation state.
When called, it handles the entire request lifecycle, including sending the message, receiving the model's response, updating the messages array, and managing loading and error states.
This eliminates the need to manually make API requests or manage chat state, allowing developers to focus on building the user experience rather than handling communication between the client and the AI model.
'use client';
import { useChat } from '@ai-sdk/react';
export const page = () => {
const { sendMessage } = useChat();
return (
<form
onSubmit={(e) => {
e.preventDefault();
sendMessage({ text: 'What is an AI agent ?' });
}}
className='border-t border-zinc-200 p-4'
>
<div className='border border-zinc-200 rounded-xl bg-white flex flex-col'>
......
<div className='flex justify-end p-2'>
<button
type='submit'
className='bg-black text-white text-sm px-4 py-2 rounded-lg hover:bg-zinc-800 transition-colors disabled:opacity-40 flex items-center gap-2'
>
Send
</button>
</div>
</div>
</form>
)};
messages
messages is an array provided by the useChat hook that contains the complete conversation between the user and the AI model. Every message sent by the user and every response generated by the model is automatically added to this array.
The messages array serves as the source of truth for the chat interface, making it easy to render conversations in the UI while also providing the context needed for the model to understand previous interactions. As new messages are exchanged, the array is automatically updated by the Vercel AI SDK.
The messages array contains objects of type UIMessage
type UIMessage = {
id: string;
role: 'system' | 'user' | 'assistant';
parts: Array<{
type: string;
text?: string;
}>;
};The message array with it's type is used to create the chat interface helping you to easily distinct between your messages and the AI response
'use client';
import { useChat } from '@ai-sdk/react';
export const page = () => {
const { messages } = useChat();
return (
<>
...................
{messages.map((message) => (
<div key={message.id}>
<strong>{message.role}:</strong>
{message.parts.map((part, index) =>
part.type === "text" ? (
<p key={index}>{part.text}</p>
) : null
)}
</div>
))}
...................
</>
)};status
status is a value provided by the useChat hook that represents the current state of a chat request. It can be used to provide real-time feedback to users, such as showing loading indicators , disabling inputs while a response is being generated, or displaying error states.
The status has 4 states that indicate different information about a request:
- submitted : Request has been sent
- streaming : Receiving the response. When using the streamText this becomes true when the response is being typed out.
- error : Indicates and error prevented the message from being sent.
- ready : Shows an idle state
'use client';
import { useChat } from '@ai-sdk/react';
export const page = () => {
const { status } = useChat();
return (
<>
...................
<button
type='submit'
onClick={() => { if (status === 'streaming') stop() }}
className='bg-black text-white text-sm px-4 '>
{status === 'submitted' ? (
<><ForwardIcon size={14} /> Sending...</>
) : status === 'streaming' ? (
<><StopCircleIcon size={14} /> Stop</>
) : (
<><ForwardIcon size={14} /> Send</>
)}
</button>
...................
</>
)};