@botonic/react
Version:
Build Chatbots using React
129 lines • 5.7 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useKnowledgeBaseInfo = void 0;
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const core_1 = require("@botonic/core");
const react_1 = require("react");
const context_1 = require("../../../webchat/context");
const icons_1 = require("../icons");
const useKnowledgeBaseInfo = ({ sourceIds, chunkIds, messageId, existingChunksWithSources, failReason, }) => {
const { updateMessage, webchatState, previewUtils } = (0, react_1.useContext)(context_1.WebchatContext);
// Check if we have cached data
const hasCachedData = existingChunksWithSources !== undefined;
// Initialize state from existing chunks with sources if available
const initialChunksWithSources = existingChunksWithSources || [];
const initialSources = initialChunksWithSources.map(item => item.source);
const initialChunks = initialChunksWithSources.flatMap(item => item.chunks);
const [chunksWithSources, setChunksWithSources] = (0, react_1.useState)(initialChunksWithSources);
const [sources, setSources] = (0, react_1.useState)(initialSources);
const [chunks, setChunks] = (0, react_1.useState)(initialChunks);
const [isLoading, setIsLoading] = (0, react_1.useState)(false);
const updateMessageWithKnowledgeData = (fetchedChunksWithSources) => {
if (!messageId) {
return;
}
const message = webchatState.messagesJSON.find(m => m.id === messageId);
if (!message) {
return;
}
// Parse the existing data if it's a string (shouldn't be, but handle it)
const parsedData = typeof message.data === 'string' ? JSON.parse(message.data) : message.data;
// Update with fetched chunks with sources and preserve original IDs
const updatedData = Object.assign(Object.assign({}, parsedData), {
// eslint-disable-next-line @typescript-eslint/naming-convention
knowledgebase_sources_ids: sourceIds,
// eslint-disable-next-line @typescript-eslint/naming-convention
knowledgebase_chunks_ids: chunkIds,
// eslint-disable-next-line @typescript-eslint/naming-convention
knowledge_base_chunks_with_sources: fetchedChunksWithSources });
// Update the message in webchat state - keep data as object
updateMessage(Object.assign(Object.assign({}, message), { data: updatedData }));
};
const fetchChunksWithSources = () => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
if (chunkIds.length === 0 || !previewUtils)
return [];
setIsLoading(true);
try {
const fetchedChunksWithSources = yield previewUtils.getChunkIdsGroupedBySource(chunkIds);
return fetchedChunksWithSources;
}
catch (error) {
console.error('Error fetching chunks with sources:', error);
return [];
}
finally {
setIsLoading(false);
}
});
const getIconForSourceType = (source) => {
switch (source.type) {
case 'file':
if (source.activeExtractionJob.fileName.endsWith('.pdf')) {
return (0, jsx_runtime_1.jsx)(icons_1.FilePdfSvg, {});
}
else {
return (0, jsx_runtime_1.jsx)(icons_1.FileWordSvg, {});
}
case 'url':
return (0, jsx_runtime_1.jsx)(icons_1.LinkSvg, {});
default:
return null;
}
};
const { hasKnowledge, isFaithful } = (0, react_1.useMemo)(() => {
const typedFailReason = failReason;
if (typedFailReason === core_1.KnowledgebaseFailReason.NoKnowledge) {
return {
hasKnowledge: false,
isFaithful: false,
};
}
if (typedFailReason === core_1.KnowledgebaseFailReason.Hallucination) {
return {
hasKnowledge: true,
isFaithful: false,
};
}
return {
hasKnowledge: true,
isFaithful: true,
};
}, [failReason]);
(0, react_1.useEffect)(() => {
// If we already have cached data (even if empty), don't fetch again
if (hasCachedData) {
return;
}
// Only fetch if previewUtils is available
if (!previewUtils) {
return;
}
// Otherwise, fetch the data
const fetchData = () => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
const fetchedChunksWithSources = yield fetchChunksWithSources();
// Extract sources and chunks from chunks with sources
const fetchedSources = fetchedChunksWithSources.map(item => item.source);
const fetchedChunks = fetchedChunksWithSources.flatMap(item => item.chunks);
setChunksWithSources(fetchedChunksWithSources);
setSources(fetchedSources);
setChunks(fetchedChunks);
// Always update the message with the fetched data (even if empty arrays)
// This marks the data as fetched so we don't fetch again
updateMessageWithKnowledgeData(fetchedChunksWithSources);
});
fetchData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return {
sources,
chunks,
chunksWithSources,
isLoading,
getIconForSourceType,
hasKnowledge,
isFaithful,
};
};
exports.useKnowledgeBaseInfo = useKnowledgeBaseInfo;
//# sourceMappingURL=use-knowledge-base-info.js.map