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.
useAssistant
is supported in ai/react
, ai/svelte
, and ai/vue
.
Import
import { useAssistant } from 'ai/react'
API Signature
Parameters
api:
The API endpoint that accepts a threadId and message object and returns an AssistantResponse stream.
threadId?:
Represents the ID of an existing thread. If not provided, a new thread will be created.
credentials?:
Sets the mode of credentials to be used on the request.
headers?:
Headers to be passed to the API endpoint.
body?:
Additional body to be passed to the API endpoint.
onError?:
Callback that will be called when the assistant encounters an error
fetch:
Optional. A custom fetch function to be used for the API call. Defaults to the global fetch function.
Returns
messages:
The current array of chat messages.
setMessages:
Function to update the `messages` array.
threadId:
The current thread ID.
setThreadId:
Set the current thread ID. Specifying a thread ID will switch to that thread, if it exists. If set to 'undefined', a new thread will be created. For both cases, `threadId` will be updated with the new value and `messages` will be cleared.
input:
The current value of the input field.
setInput:
Function to update the `input` value.
handleInputChange:
Handler for the `onChange` event of the input field to control the input's value.
submitMessage:
Form submission handler that automatically resets the input field and appends a user message.
status:
The current status of the assistant. This can be used to show a loading indicator.
append:
Function to append a user message to the current thread. This triggers the API call to fetch the assistant's response.
stop:
Function to abort the current request from streaming the assistant response. Note that the run will still be in progress.
error:
The error thrown during the assistant message processing, if any.