Created
February 16, 2025 18:12
-
-
Save Sama-004/4c50ae5573fccfaf68adbd7006b027a8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export async function loader({ params }: LoaderFunctionArgs) { | |
//find messages from db | |
return { | |
chatMessages, | |
}; | |
} | |
// this is for new messages | |
export async function action({ request, params }: ActionFunctionArgs) { | |
const formData = await request.formData(); | |
const message = formData.get("message"); | |
const chatId = params.chatId; | |
if (!message) { | |
return null; | |
} | |
await db.insert(messages).values({ | |
chatId: chatId as string, | |
role: "user", | |
content: message as string, | |
createdAt: new Date(), | |
}); | |
return { success: true }; | |
} | |
export default function ChatComponent() { | |
const { chatMessages } = useLoaderData<typeof loader>(); | |
const params = useParams(); | |
const [streamedResponse, setStreamedResponse] = useState(""); | |
const [isLoading, setIsLoading] = useState(false); | |
const [searchParams] = useSearchParams(); | |
const searchParamsMessage = searchParams.get("message"); | |
const [message, setMessage] = useState(searchParamsMessage); | |
const chatId = params.chatId; | |
useEffect(() => { | |
if (!message) return; | |
fetchStream(); | |
}, []); | |
const fetchStream = async () => { | |
console.log("fetching stream"); | |
setIsLoading(true); | |
setMessage(""); | |
try { | |
const response = await fetch("http://localhost:5000/conversation", { | |
method: "POST", | |
headers: { | |
"Content-Type": "application/json", | |
}, | |
body: JSON.stringify({ | |
chatid: chatId, | |
question: message, | |
}), | |
}); | |
const reader = response.body?.getReader(); | |
const decoder = new TextDecoder(); | |
while (true) { | |
const { done, value } = await reader?.read(); | |
if (done) break; | |
const chunk = decoder.decode(value, { stream: true }); | |
const parts = chunk.split(/({.*?})/g).filter(Boolean); | |
for (const part of parts) { | |
try { | |
const parsed = JSON.parse(part); | |
if (parsed.answer) { | |
const decodedAnswer = parsed.answer; | |
setStreamedResponse(decodedAnswer); | |
} | |
} catch (e) { | |
continue; | |
} | |
} | |
} | |
} catch (error) { | |
console.error("Error fetching stream:", error); | |
setStreamedResponse("Sorry, there was an error processing your request."); | |
} finally { | |
setIsLoading(false); | |
} | |
}; | |
//rest of the rendering logic | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment