import React, { useState, useEffect } from "react";
import {
Box,
Typography,
CircularProgress,
Paper,
Tooltip,
} from "@mui/material";
import axios from "axios";
// Create a cache object to store explanations
const explanationCache = {};
function ExplanationBox({ documentId, threadId }) {
const [explanation, setExplanation] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchExplanation = async () => {
setLoading(true);
setError(null);
try {
// Check the cache before making a request
if (explanationCache[`${documentId}-${threadId}`]) {
setExplanation(explanationCache[`${documentId}-${threadId}`]);
setLoading(false);
return;
}
const response = await axios.get(
`http://localhost:8000/explain/${threadId}?docid=${documentId}`,
);
setExplanation(response.data);
// Store the fetched explanation in the cache
explanationCache[`${documentId}-${threadId}`] = response.data;
} catch (error) {
console.error("Error fetching explanation:", error);
setError("Failed to fetch explanation");
} finally {
setLoading(false);
}
};
fetchExplanation();
}, [documentId, threadId]);
if (loading) {
return (
);
}
if (error) {
return (
{error}
);
}
const renderExplanationWithLinks = (text, chunks) => {
const parts = text.split(/(\[\d+\])/);
return parts.map((part, index) => {
const match = part.match(/\[(\d+)\]/);
if (match) {
const chunkIndex = parseInt(match[1]);
return (
{`[${chunkIndex + 1}]`}
);
}
return {part};
});
};
return (
{explanation?.generation
? renderExplanationWithLinks(
explanation.generation,
explanation.chunks,
)
: "No explanation available."}
);
}
export default ExplanationBox;