Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add onError handler to useAssistant hook #818

Merged
merged 9 commits into from
Jan 31, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -81,6 +81,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 @@ -89,12 +94,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 @@ -188,13 +194,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
Loading