Download src/hooks/useChat.ts from IOE-IFAD/test: direct link, hf CLI and curl.
- Browser
- Download file 2.03 kB
-
https://huggingface.co/spaces/IOE-IFAD/test/resolve/main/src/hooks/useChat.ts
- Command line
-
hf download hf://spaces/IOE-IFAD/test/src/hooks/useChat.ts
-
curl -L -o useChat.ts https://huggingface.co/spaces/IOE-IFAD/test/resolve/main/src/hooks/useChat.ts
2.03 kB
| import { useState } from 'react'; | |
| import { useSelectedChat } from '@/providers/selected-chat-provider'; | |
| import { Message } from '@/lib/types'; | |
| import { init_message } from '@/lib/prompts'; | |
| import { getNameForNewChat, sendChat } from '@/lib/api'; | |
| export function useChat() { | |
| const [isLoading, setIsLoading] = useState(false); | |
| const [error, setError] = useState<Error | null>(null); | |
| const { | |
| selectedChat, | |
| sendMessage, | |
| selectedChatId, | |
| loadChat, | |
| updateChatName, | |
| } = useSelectedChat(); | |
| const sendUserMessage = async (content: string) => { | |
| if (!selectedChatId || !selectedChat) return; | |
| setIsLoading(true); | |
| setError(null); | |
| try { | |
| const userMessage: Message = { | |
| content, | |
| transcripts: [], | |
| role: "user", | |
| timestamp: new Date(), | |
| id: crypto.randomUUID(), | |
| }; | |
| if (selectedChat.messages.length === 0) { | |
| await sendMessage(init_message); | |
| } | |
| await sendMessage(userMessage); | |
| const chat = await loadChat(selectedChatId); | |
| const aiResponse = await sendChat(chat.messages, userMessage); | |
| if (!aiResponse?.ok) { | |
| throw new Error("Failed to send message"); | |
| } | |
| const aiResponseData = await aiResponse.json(); | |
| const aiMessage: Message = { | |
| content: aiResponseData.response, | |
| transcripts: aiResponseData.timestamps, | |
| role: "assistant", | |
| timestamp: new Date(), | |
| id: crypto.randomUUID(), | |
| }; | |
| await sendMessage(aiMessage); | |
| const chatLength = (await loadChat(selectedChatId)).messages.length; | |
| if (chatLength === 3) { | |
| const name = await getNameForNewChat(userMessage.content, aiMessage.content); | |
| if (name) updateChatName(selectedChatId, name); | |
| } | |
| } catch (err) { | |
| setError(err instanceof Error ? err : new Error('Failed to send message')); | |
| } finally { | |
| setIsLoading(false); | |
| } | |
| }; | |
| return { | |
| selectedChat, | |
| selectedChatId, | |
| isLoading, | |
| error, | |
| sendUserMessage, | |
| }; | |
| } | |