Skip to content

Commit

Permalink
Add append helper to useAssistant. (#1407)
Browse files Browse the repository at this point in the history
  • Loading branch information
lgrammel committed Apr 23, 2024
1 parent 1e84d6d commit 9c2a049
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 12 deletions.
5 changes: 5 additions & 0 deletions .changeset/healthy-files-scream.md
@@ -0,0 +1,5 @@
---
'ai': patch
---

Add append() helper to useAssistant.
5 changes: 5 additions & 0 deletions docs/pages/docs/api-reference/use-assistant.mdx
Expand Up @@ -137,6 +137,11 @@ The `useAssistant` hook returns an object with several helper methods and variab
'React.Dispatch<React.SetStateAction<string>>',
'Function to update the `input` value.',
],
[
'append',
'(message: Message) => void',
` Append a user message to the chat list. This triggers the API call to fetch the assistant's response.`,
],
[
'handleInputChange',
'(e: any) => void',
Expand Down
48 changes: 36 additions & 12 deletions packages/core/react/use-assistant.ts
Expand Up @@ -4,7 +4,7 @@ import { useState } from 'react';

import { generateId } from '../shared/generate-id';
import { readDataStream } from '../shared/read-data-stream';
import { Message } from '../shared/types';
import { CreateMessage, Message } from '../shared/types';

export type AssistantStatus = 'in_progress' | 'awaiting_message';

Expand All @@ -29,6 +29,19 @@ export type UseAssistantHelpers = {
*/
input: string;

/**
* Append a user message to the chat list. This triggers the API call to fetch
* the assistant's response.
* @param message The message to append
* @param requestOptions Additional options to pass to the API call
*/
append: (
message: Message | CreateMessage,
requestOptions?: {
data?: Record<string, string>;
},
) => Promise<void>;

/**
* setState-powered method to update the input value.
*/
Expand Down Expand Up @@ -122,23 +135,18 @@ export function useAssistant({
setInput(event.target.value);
};

const submitMessage = async (
event?: React.FormEvent<HTMLFormElement>,
const append = async (
message: Message | CreateMessage,
requestOptions?: {
data?: Record<string, string>;
},
) => {
event?.preventDefault?.();

if (input === '') {
return;
}

setStatus('in_progress');

setMessages(messages => [
...messages,
{ id: '', role: 'user', content: input },
{
...message,
id: message.id ?? generateId(),
},
]);

setInput('');
Expand Down Expand Up @@ -240,7 +248,23 @@ export function useAssistant({
setStatus('awaiting_message');
};

const submitMessage = async (
event?: React.FormEvent<HTMLFormElement>,
requestOptions?: {
data?: Record<string, string>;
},
) => {
event?.preventDefault?.();

if (input === '') {
return;
}

append({ role: 'user', content: input }, requestOptions);
};

return {
append,
messages,
setMessages,
threadId,
Expand Down

0 comments on commit 9c2a049

Please sign in to comment.