Spaces:
Running
Running
File size: 1,853 Bytes
ca7a659 a86b547 c232e44 ca7a659 5ec491a ca7a659 a86b547 5ec491a d553ae5 a86b547 84c9f51 a86b547 92f037b a86b547 92f037b a86b547 5d7d435 ca7a659 84c9f51 ca7a659 a86b547 5ec491a a86b547 ca7a659 a86b547 5ec491a 92f037b 5ec491a c232e44 84c9f51 c232e44 84c9f51 5ec491a ca7a659 5ec491a 84c9f51 a86b547 ca7a659 a86b547 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
import { useChat, UseChatHelpers } from 'ai/react';
import { toast } from 'react-hot-toast';
import { useEffect, useRef } from 'react';
import { ChatWithMessages } from '../db/types';
import { dbPostCreateMessage } from '../db/functions';
import {
convertDbMessageToMessage,
convertMessageToDbMessage,
} from '../messageUtils';
const useVisionAgent = (chat: ChatWithMessages) => {
const { messages: initialMessages, id, mediaUrl } = chat;
const {
messages,
append: appendRaw,
isLoading,
reload,
} = useChat({
api: '/api/vision-agent',
// @ts-ignore https://sdk.vercel.ai/docs/troubleshooting/common-issues/use-chat-failed-to-parse-stream
streamMode: 'text',
onResponse(response) {
if (response.status !== 200) {
toast.error(response.statusText);
}
},
onFinish: async message => {
await dbPostCreateMessage(id, convertMessageToDbMessage(message));
},
initialMessages: initialMessages.map(convertDbMessageToMessage),
body: {
mediaUrl,
id,
},
onError: err => {
err && toast.error(err.message);
},
});
/**
* If case this is first time user navigated with init message, we need to reload the chat for the first response
*/
const once = useRef(true);
useEffect(() => {
if (
!isLoading &&
messages.length === 1 &&
messages[0].role === 'user' &&
once.current
) {
once.current = false;
reload();
}
}, [isLoading, messages, reload]);
const append: UseChatHelpers['append'] = async message => {
dbPostCreateMessage(id, {
role: message.role as 'user' | 'assistant',
content: message.content,
result: null,
});
return appendRaw(message);
};
return {
messages,
append,
reload,
isLoading,
};
};
export default useVisionAgent;
|