Skip to content

Commit

Permalink
Add onError handler to useAssistant hook (#818)
Browse files Browse the repository at this point in the history
Co-authored-by: Max Leiter <max.leiter@vercel.com>
  • Loading branch information
mfts and MaxLeiter authored Jan 31, 2024
1 parent 3152643 commit 8542ae7
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/mean-deers-try.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'ai': patch
---

react/use-assistant: add onError handler
5 changes: 5 additions & 0 deletions docs/pages/docs/api-reference/use-assistant.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,11 @@ export default function Chat() {
'any',
'An optional, additional body object to be passed to the API endpoint.',
],
[
'onError',
'(err: Error) => void',
'An optional callback that will be called when the assistant encounters an error',
],
]}
/>

Expand Down
17 changes: 14 additions & 3 deletions packages/core/react/use-assistant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ export type UseAssistantOptions = {
* An optional, additional body object to be passed to the API endpoint.
*/
body?: object;

/**
* An optional callback that will be called when the assistant encounters an error.
*/
onError?: (error: Error) => void;
};

export function experimental_useAssistant({
Expand All @@ -94,12 +99,13 @@ export function experimental_useAssistant({
credentials,
headers,
body,
onError,
}: UseAssistantOptions): UseAssistantHelpers {
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState('');
const [threadId, setThreadId] = useState<string | undefined>(undefined);
const [status, setStatus] = useState<AssistantStatus>('awaiting_message');
const [error, setError] = useState<unknown | undefined>(undefined);
const [error, setError] = useState<undefined | Error>(undefined);

const handleInputChange = (
event:
Expand Down Expand Up @@ -193,13 +199,18 @@ export function experimental_useAssistant({
}

case 'error': {
setError(value);
const errorObj = new Error(value);
setError(errorObj);
break;
}
}
}
} catch (error) {
setError(error);
if (onError && error instanceof Error) {
onError(error);
}

setError(error as Error);
}

setStatus('awaiting_message');
Expand Down

0 comments on commit 8542ae7

Please sign in to comment.