useChat()

Allows you to easily create a conversational user interface for your chatbot application. It enables the streaming of chat messages from your AI provider, manages the chat state, and updates the UI automatically as new messages are received.

The useChat API has been significantly updated in AI SDK 5.0. It now uses a transport-based architecture and no longer manages input state internally. See the migration guide for details.

Import

import { useChat } from '@ai-sdk/react'

API Signature

Parameters

chat?:

Chat<UIMessage>

transport?:

ChatTransport
DefaultChatTransport

api?:

string = '/api/chat'

credentials?:

RequestCredentials

headers?:

Record<string, string> | Headers

body?:

object

prepareSendMessagesRequest?:

PrepareSendMessagesRequest
PrepareSendMessagesRequest

options:

PrepareSendMessageRequestOptions
PrepareSendMessageRequestOptions

id:

string

messages:

UIMessage[]

requestMetadata:

unknown

body:

Record<string, any> | undefined

credentials:

RequestCredentials | undefined

headers:

HeadersInit | undefined

api:

string

trigger:

'submit-message' | 'regenerate-message'

messageId:

string | undefined

prepareReconnectToStreamRequest?:

PrepareReconnectToStreamRequest
PrepareReconnectToStreamRequest

options:

PrepareReconnectToStreamRequestOptions
PrepareReconnectToStreamRequestOptions

id:

string

requestMetadata:

unknown

body:

Record<string, any> | undefined

credentials:

RequestCredentials | undefined

headers:

HeadersInit | undefined

api:

string

id?:

string

messages?:

UIMessage[]

onToolCall?:

({toolCall: ToolCall}) => void | Promise<void>

sendAutomaticallyWhen?:

(options: { messages: UIMessage[] }) => boolean | PromiseLike<boolean>

onFinish?:

(options: OnFinishOptions) => void
OnFinishOptions

message:

UIMessage

messages:

UIMessage[]

isAbort:

boolean

isDisconnect:

boolean

isError:

boolean

finishReason?:

'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'

onError?:

(error: Error) => void

onData?:

(dataPart: DataUIPart) => void

experimental_throttle?:

number

resume?:

boolean

Returns

id:

string

messages:

UIMessage[]
UIMessage

id:

string

role:

'system' | 'user' | 'assistant'

parts:

UIMessagePart[]

metadata?:

unknown

status:

'submitted' | 'streaming' | 'ready' | 'error'

error:

Error | undefined

sendMessage:

(message: CreateUIMessage | string, options?: ChatRequestOptions) => void
ChatRequestOptions

headers:

Record<string, string> | Headers

body:

object

metadata:

JSONValue

regenerate:

(options?: { messageId?: string }) => void

stop:

() => void

clearError:

() => void

resumeStream:

() => void

addToolOutput:

(options: { tool: string; toolCallId: string; output: unknown } | { tool: string; toolCallId: string; state: "output-error", errorText: string }) => void

setMessages:

(messages: UIMessage[] | ((messages: UIMessage[]) => UIMessage[])) => void

Learn more