matt HOFFNER
fix
d9a1036
raw
history blame
3.1 kB
"use client"
import { useEffect, useState } from "react";
import { URL } from 'url';
import { MemoizedReactMarkdown } from '../../../components/MemoizedReactMarkdown'
export default function WebSearchPage({ searchParams }) {
const [aiResponse, setAiResponse] = useState("");
const [eventSource, setEventSource] = useState(null);
const [searchTerm, setSearchTerm] = useState()
useEffect(() => {
setSearchTerm(searchParams.searchTerm)
}, [searchParams])
useEffect(() => {
const url = new URL(`/api/llm?question=${searchTerm}`);
console.log(url);
// No need to make a fetch request. Directly open the EventSource connection.
const es = new EventSource(url);
setEventSource(es);
return () => {
if (es) es.close(); // Close the EventSource when the component is unmounted.
};
}, [searchParams]);
// Add event listener for the EventSource
useEffect(() => {
if (eventSource) {
eventSource.onmessage = (event) => {
setAiResponse(prev => prev + event.data);
};
eventSource.onerror = (event) => {
console.error("EventSource failed:", event);
};
}
return () => {
if (eventSource) {
eventSource.close();
}
};
}, [eventSource]);
console.log(aiResponse);
return (
<div className="flex flex-row">
<MemoizedReactMarkdown
className="prose dark:prose-invert flex-1"
components={{
code({ node, inline, className, children, ...props }) {
if (children.length) {
if (children[0] == '▍') {
return <span className="animate-pulse cursor-default mt-1">▍</span>
}
children[0] = (children[0]).replace("`▍`", "▍")
}
const match = /language-(\w+)/.exec(className || '');
return !inline ? (
<CodeBlock
key={Math.random()}
language={(match && match[1]) || ''}
value={String(children).replace(/\n$/, '')}
{...props}
/>
) : (
<code className={className} {...props}>
{children}
</code>
);
},
table({ children }) {
return (
<table className="border-collapse border border-black px-3 py-1 dark:border-white">
{children}
</table>
);
},
th({ children }) {
return (
<th className="break-words border border-black bg-gray-500 px-3 py-1 text-white dark:border-white">
{children}
</th>
);
},
td({ children }) {
return (
<td className="break-words border border-black px-3 py-1 dark:border-white">
{children}
</td>
);
},
}}
>
{aiResponse}
</MemoizedReactMarkdown>
</div>
);
}