AI SDK UIuseAssistant

useAssistant

Allows you to handle the client state when interacting with an OpenAI compatible assistant API. This hook is useful when you want to integrate assistant capibilities into your application, with the UI updated automatically as the assistant is streaming its execution.

This works in conjunction with AssistantResponse in the backend.

Import

React

import { useAssistant } from "ai/react"

Object Parameters

api:

string
The API endpoint that accepts a threadId and message object and returns an AssistantResponse stream.

threadId?:

string | undefined
Represents the ID of an existing thread. If not provided, a new thread will be created.

credentials?:

'omit' | 'same-origin' | 'include' = 'same-origin'
Sets the mode of credentials to be used on the request.

headers?:

Record<string, string> | Headers
Headers to be passed to the API endpoint.

body?:

any
Additional body to be passed to the API endpoint.

onError?:

(error: Error) => void
Callback that will be called when the assistant encounters an error

Response Object

messages:

Message[]
The current array of chat messages.

setMessages:

React.Dispatch<React.SetStateAction<Message>>
Function to update the `messages` array.

threadId:

string | undefined
The current thread ID.

input:

string
The current value of the input field.

setInput:

React.Dispatch<React.SetStateAction<string>>
Function to update the `input` value.

handleInputChange:

(event: any) => void
Handler for the `onChange` event of the input field to control the input's value.

submitMessage:

(event?: React.FormEvent<HTMLFormElement>) => void
Form submission handler that automatically resets the input field and appends a user message.

status:

'awaiting_message' | 'in_progress'
The current status of the assistant. This can be used to show a loading indicator.

error:

undefined | Error
The error thrown during the assistant message processing, if any.