@red-hat-developer-hub/backstage-plugin-lightspeed 0.5.0 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/README.md +15 -0
- package/config.d.ts +21 -0
- package/dist/api/LightspeedApiClient.esm.js +3 -2
- package/dist/api/LightspeedApiClient.esm.js.map +1 -1
- package/dist/api/api.esm.js.map +1 -1
- package/dist/components/Attachment.esm.js +98 -0
- package/dist/components/Attachment.esm.js.map +1 -0
- package/dist/components/AttachmentContext.esm.js +105 -0
- package/dist/components/AttachmentContext.esm.js.map +1 -0
- package/dist/components/FilePreview.esm.js +59 -0
- package/dist/components/FilePreview.esm.js.map +1 -0
- package/dist/components/LightSpeedChat.esm.js +40 -26
- package/dist/components/LightSpeedChat.esm.js.map +1 -1
- package/dist/components/LightspeedChatBox.esm.js +56 -5
- package/dist/components/LightspeedChatBox.esm.js.map +1 -1
- package/dist/components/LightspeedPage.esm.js +3 -2
- package/dist/components/LightspeedPage.esm.js.map +1 -1
- package/dist/const.esm.js +58 -1
- package/dist/const.esm.js.map +1 -1
- package/dist/hooks/useAutoScroll.esm.js +78 -0
- package/dist/hooks/useAutoScroll.esm.js.map +1 -0
- package/dist/hooks/useBufferedMessages.esm.js +27 -0
- package/dist/hooks/useBufferedMessages.esm.js.map +1 -0
- package/dist/hooks/useConversationMessages.esm.js +34 -4
- package/dist/hooks/useConversationMessages.esm.js.map +1 -1
- package/dist/hooks/useCreateCoversationMessage.esm.js +4 -2
- package/dist/hooks/useCreateCoversationMessage.esm.js.map +1 -1
- package/dist/hooks/useWelcomePrompts.esm.js +20 -0
- package/dist/hooks/useWelcomePrompts.esm.js.map +1 -0
- package/dist/types.esm.js +9 -0
- package/dist/types.esm.js.map +1 -0
- package/dist/utils/attachment-utils.esm.js +23 -0
- package/dist/utils/attachment-utils.esm.js.map +1 -0
- package/dist/utils/lightspeed-chatbox-utils.esm.js +9 -4
- package/dist/utils/lightspeed-chatbox-utils.esm.js.map +1 -1
- package/dist/utils/prompt-utils.esm.js +17 -0
- package/dist/utils/prompt-utils.esm.js.map +1 -0
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useConversationMessages.esm.js","sources":["../../src/hooks/useConversationMessages.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport React from 'react';\n\nimport { useApi } from '@backstage/core-plugin-api';\n\nimport { MessageProps } from '@patternfly/chatbot';\nimport { useQuery } from '@tanstack/react-query';\n\nimport { lightspeedApiRef } from '../api/api';\nimport { TEMP_CONVERSATION_ID } from '../const';\nimport logo from '../images/logo.svg';\nimport {\n createBotMessage,\n createUserMessage,\n getMessageData,\n getTimestamp,\n} from '../utils/lightspeed-chatbox-utils';\nimport { useCreateConversationMessage } from './useCreateCoversationMessage';\n\n// Fetch all conversation messages\nexport const useFetchConversationMessages = (currentConversation: string) => {\n const lightspeedApi = useApi(lightspeedApiRef);\n return useQuery({\n queryKey: ['conversationMessages', currentConversation],\n queryFn: currentConversation\n ? async () => {\n const response =\n await lightspeedApi.getConversationMessages(currentConversation);\n\n return response;\n }\n : undefined,\n retry: false,\n });\n};\n\ntype Conversations = { [_key: string]: MessageProps[] };\n\nconst defaultAvatar =\n 'https://img.freepik.com/premium-photo/graphic-designer-digital-avatar-generative-ai_934475-9292.jpg';\n/**\n * Fetches all the messages for given conversation_id\n * @param conversationId\n * @param userName\n * @param selectedModel\n * @param avatar\n *\n */\nexport const useConversationMessages = (\n conversationId: string,\n userName: string | undefined,\n selectedModel: string,\n avatar: string = defaultAvatar,\n onComplete?: (message: string) => void,\n onStart?: (conversation_id: string) => void,\n) => {\n const { mutateAsync: createMessage } = useCreateConversationMessage();\n const scrollToBottomRef = React.useRef<HTMLDivElement>(null);\n\n const [currentConversation, setCurrentConversation] =\n React.useState(conversationId);\n const [conversations, setConversations] = React.useState<Conversations>({\n [currentConversation]: [],\n });\n const streamingConversations = React.useRef<Conversations>({\n [currentConversation]: [],\n });\n\n React.useEffect(() => {\n if (currentConversation !== conversationId) {\n setCurrentConversation(conversationId);\n setConversations(prev => {\n if (prev[conversationId]) return prev;\n\n return {\n ...prev,\n [conversationId]: [],\n };\n });\n }\n }, [currentConversation, conversationId]);\n\n const { data: conversationsData = [], ...queryProps } =\n useFetchConversationMessages(currentConversation);\n\n React.useEffect(() => {\n if (!Array.isArray(conversationsData) || conversationsData.length === 0)\n return;\n\n const newConvoIndex: number[] = [];\n\n if (conversations) {\n const _conversations: { [key: string]: any[] } = {\n [currentConversation]: [],\n };\n\n let index = 0;\n for (let i = 0; i < conversationsData.length; i += 2) {\n const userMessage = conversationsData[i];\n const aiMessage = conversationsData[i + 1];\n\n const { content: humanMessage, timestamp: userTimestamp } =\n getMessageData(userMessage);\n const {\n model,\n content: botMessage,\n timestamp: botTimestamp,\n } = getMessageData(aiMessage);\n\n _conversations[currentConversation].push(\n ...[\n createUserMessage({\n avatar,\n name: userName,\n content: humanMessage,\n timestamp: userTimestamp,\n }),\n createBotMessage({\n avatar: logo,\n isLoading: false,\n name: model ?? selectedModel,\n content: botMessage,\n timestamp: botTimestamp,\n }),\n ],\n );\n\n newConvoIndex.push(index);\n index++;\n }\n\n if (streamingConversations.current[currentConversation]) {\n _conversations[currentConversation].push(\n ...streamingConversations.current[currentConversation],\n );\n }\n\n setConversations(_conversations);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n conversationsData,\n userName,\n avatar,\n currentConversation,\n selectedModel,\n streamingConversations,\n ]);\n\n const handleInputPrompt = React.useCallback(\n async (prompt: string) => {\n let newConversationId = '';\n\n const conversationTuple = [\n createUserMessage({\n avatar,\n name: userName,\n content: prompt,\n timestamp: getTimestamp(Date.now()) ?? '',\n }),\n createBotMessage({\n avatar: logo,\n isLoading: true,\n name: selectedModel,\n content: '',\n timestamp: '',\n }),\n ];\n\n streamingConversations.current = {\n ...streamingConversations.current,\n [currentConversation]: conversationTuple,\n };\n\n setConversations((prevConv: Conversations) => {\n return {\n ...prevConv,\n [currentConversation]: [\n ...(prevConv?.[currentConversation] ?? []),\n ...conversationTuple,\n ],\n };\n });\n\n setTimeout(() => {\n scrollToBottomRef.current?.scrollIntoView({ behavior: 'auto' });\n }, 0);\n const finalMessages: string[] = [];\n let buffer = '';\n\n try {\n const reader = await createMessage({\n prompt,\n selectedModel,\n currentConversation,\n });\n\n const decoder = new TextDecoder('utf-8');\n const keepGoing = true;\n\n while (keepGoing) {\n const { value, done } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n\n // Process all complete messages separated by double newlines\n const parts = buffer.split('\\n\\n');\n buffer = parts.pop()!;\n\n for (const part of parts) {\n const lines = part\n .split('\\n')\n .filter(line => line.startsWith('data:'));\n\n const jsonString = lines\n .map(line => line.trim().slice(5).trim())\n .join('');\n try {\n const { event, data } = JSON.parse(jsonString);\n if (event === 'start') {\n if (currentConversation === TEMP_CONVERSATION_ID) {\n // If the conversation is temp, we need to set the new conversation id\n newConversationId = data?.conversation_id;\n }\n }\n\n if (event === 'token') {\n const content = data?.token || '';\n\n finalMessages.push(content);\n\n // Store streaming message\n const [humanMessage, aiMessage] =\n streamingConversations.current[currentConversation];\n streamingConversations.current[currentConversation] = [\n humanMessage,\n { ...aiMessage, content: aiMessage.content + content },\n ];\n\n setConversations(prevConversations => {\n const conversation =\n prevConversations[currentConversation] ?? [];\n\n const lastMessageIndex = conversation.length - 1;\n const lastMessage =\n conversation.length === 0\n ? createBotMessage({\n content: '',\n timestamp: getTimestamp(Date.now()),\n })\n : { ...conversation[lastMessageIndex] };\n\n lastMessage.isLoading = false;\n lastMessage.content += content;\n lastMessage.name =\n data?.response_metadata?.model || selectedModel;\n lastMessage.timestamp = getTimestamp(\n data?.response_metadata?.created_at || Date.now(),\n );\n\n const updatedConversation = [\n ...conversation.slice(0, lastMessageIndex),\n lastMessage,\n ];\n\n return {\n ...prevConversations,\n [currentConversation]: updatedConversation,\n };\n });\n }\n } catch (error) {\n // eslint-disable-next-line no-console\n console.warn('Error parsing JSON:', error);\n if (typeof onComplete === 'function') {\n onComplete('Invalid JSON received');\n }\n }\n }\n }\n } catch (e) {\n setConversations(prevConversations => {\n const conversation = prevConversations[currentConversation] ?? [];\n\n const lastMessageIndex = conversation.length - 1;\n const lastMessage =\n conversation.length === 0\n ? createBotMessage({\n content: '',\n timestamp: getTimestamp(Date.now()),\n })\n : { ...conversation[lastMessageIndex] };\n\n lastMessage.isLoading = false;\n lastMessage.content += e;\n lastMessage.error = {\n title: e.message,\n };\n lastMessage.timestamp = getTimestamp(Date.now());\n\n const updatedConversation = [\n ...conversation.slice(0, lastMessageIndex),\n lastMessage,\n ];\n\n finalMessages.push(`${e}`);\n\n return {\n ...prevConversations,\n [newConversationId.length > 0\n ? newConversationId\n : currentConversation]: updatedConversation,\n };\n });\n }\n // reset current streaming\n streamingConversations.current[currentConversation] = [];\n if (typeof onComplete === 'function') {\n onComplete(finalMessages.join(''));\n }\n // Swap temp conversation messages with new conversation\n\n if (currentConversation === TEMP_CONVERSATION_ID && newConversationId) {\n setConversations(prevConversations => {\n return {\n ...prevConversations,\n [newConversationId]: prevConversations[TEMP_CONVERSATION_ID],\n };\n });\n\n onStart?.(newConversationId);\n\n setConversations(prev => {\n const { temp, ...rest } = prev;\n return rest;\n });\n }\n },\n\n [\n avatar,\n userName,\n onComplete,\n onStart,\n selectedModel,\n createMessage,\n currentConversation,\n ],\n );\n\n return {\n conversationMessages: conversations[currentConversation] ?? [],\n handleInputPrompt,\n conversations,\n scrollToBottomRef,\n ...queryProps,\n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AAA,IAC7D,iBAAA;AAAA,IACA,aAAA;AAAA,IACA,iBAAA;AAAA,IACA,GAAG;AAAA,GACL;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"useConversationMessages.esm.js","sources":["../../src/hooks/useConversationMessages.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport React from 'react';\n\nimport { useApi } from '@backstage/core-plugin-api';\n\nimport { MessageProps } from '@patternfly/chatbot';\nimport { useQuery } from '@tanstack/react-query';\n\nimport { lightspeedApiRef } from '../api/api';\nimport { ScrollContainerHandle } from '../components/LightspeedChatBox';\nimport { TEMP_CONVERSATION_ID } from '../const';\nimport logo from '../images/logo.svg';\nimport { Attachment } from '../types';\nimport {\n createBotMessage,\n createUserMessage,\n getMessageData,\n getTimestamp,\n} from '../utils/lightspeed-chatbox-utils';\nimport { useCreateConversationMessage } from './useCreateCoversationMessage';\n\n// Fetch all conversation messages\nexport const useFetchConversationMessages = (currentConversation: string) => {\n const lightspeedApi = useApi(lightspeedApiRef);\n return useQuery({\n queryKey: ['conversationMessages', currentConversation],\n queryFn: currentConversation\n ? async () => {\n const response =\n await lightspeedApi.getConversationMessages(currentConversation);\n\n return response;\n }\n : undefined,\n retry: false,\n });\n};\n\ntype Conversations = { [_key: string]: MessageProps[] };\n\nconst defaultAvatar =\n 'https://img.freepik.com/premium-photo/graphic-designer-digital-avatar-generative-ai_934475-9292.jpg';\n/**\n * Fetches all the messages for given conversation_id\n * @param conversationId\n * @param userName\n * @param selectedModel\n * @param avatar\n *\n */\nexport const useConversationMessages = (\n conversationId: string,\n userName: string | undefined,\n selectedModel: string,\n avatar: string = defaultAvatar,\n onComplete?: (message: string) => void,\n onStart?: (conversation_id: string) => void,\n) => {\n const { mutateAsync: createMessage } = useCreateConversationMessage();\n const scrollToBottomRef = React.useRef<ScrollContainerHandle>(null);\n\n const [currentConversation, setCurrentConversation] =\n React.useState(conversationId);\n const [conversations, setConversations] = React.useState<Conversations>({\n [currentConversation]: [],\n });\n const streamingConversations = React.useRef<Conversations>({\n [currentConversation]: [],\n });\n\n React.useEffect(() => {\n if (currentConversation !== conversationId) {\n setCurrentConversation(conversationId);\n setConversations(prev => {\n if (prev[conversationId]) return prev;\n\n return {\n ...prev,\n [conversationId]: [],\n };\n });\n }\n }, [currentConversation, conversationId]);\n\n const { data: conversationsData = [], ...queryProps } =\n useFetchConversationMessages(currentConversation);\n\n React.useEffect(() => {\n if (\n !Array.isArray(conversationsData) ||\n (conversationsData.length === 0 &&\n conversationId !== TEMP_CONVERSATION_ID)\n )\n return;\n\n const newConvoIndex: number[] = [];\n\n if (conversations) {\n const _conversations: { [key: string]: any[] } = {\n [currentConversation]: [],\n };\n\n let index = 0;\n for (let i = 0; i < conversationsData.length; i += 2) {\n const userMessage = conversationsData[i];\n const aiMessage = conversationsData[i + 1];\n\n const { content: humanMessage, timestamp: userTimestamp } =\n getMessageData(userMessage);\n const {\n model,\n content: botMessage,\n timestamp: botTimestamp,\n } = getMessageData(aiMessage);\n\n _conversations[currentConversation].push(\n ...[\n createUserMessage({\n avatar,\n name: userName,\n content: humanMessage,\n timestamp: userTimestamp,\n }),\n createBotMessage({\n avatar: logo,\n isLoading: false,\n name: model ?? selectedModel,\n content: botMessage,\n timestamp: botTimestamp,\n }),\n ],\n );\n\n newConvoIndex.push(index);\n index++;\n }\n\n if (streamingConversations.current[currentConversation]) {\n _conversations[currentConversation].push(\n ...streamingConversations.current[currentConversation],\n );\n }\n\n setConversations(_conversations);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n conversationsData,\n userName,\n avatar,\n currentConversation,\n selectedModel,\n streamingConversations,\n ]);\n\n const handleInputPrompt = React.useCallback(\n async (prompt: string, attachments: Attachment[] = []) => {\n let newConversationId = '';\n\n const conversationTuple = [\n createUserMessage({\n avatar,\n name: userName,\n content: prompt,\n timestamp: getTimestamp(Date.now()) ?? '',\n }),\n createBotMessage({\n avatar: logo,\n isLoading: true,\n name: selectedModel,\n content: '',\n timestamp: '',\n }),\n ];\n\n streamingConversations.current = {\n ...streamingConversations.current,\n [currentConversation]: conversationTuple,\n };\n\n setConversations((prevConv: Conversations) => {\n return {\n ...prevConv,\n [currentConversation]: [\n ...(prevConv?.[currentConversation] ?? []),\n ...conversationTuple,\n ],\n };\n });\n\n setTimeout(() => {\n scrollToBottomRef.current?.scrollToBottom();\n }, 0);\n const finalMessages: string[] = [];\n let buffer = '';\n\n try {\n const reader = await createMessage({\n prompt,\n selectedModel,\n currentConversation,\n attachments,\n });\n\n const decoder = new TextDecoder('utf-8');\n const keepGoing = true;\n\n while (keepGoing) {\n const { value, done } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n\n // Process all complete messages separated by double newlines\n const parts = buffer.split('\\n\\n');\n buffer = parts.pop()!;\n\n for (const part of parts) {\n const lines = part\n .split('\\n')\n .filter(line => line.startsWith('data:'));\n\n const jsonString = lines\n .map(line => line.trim().slice(5).trim())\n .join('');\n try {\n const { event, data } = JSON.parse(jsonString);\n if (event === 'start') {\n if (currentConversation === TEMP_CONVERSATION_ID) {\n // If the conversation is temp, we need to set the new conversation id\n newConversationId = data?.conversation_id;\n }\n }\n\n if (event === 'token') {\n const content = data?.token || '';\n\n finalMessages.push(content);\n\n // Store streaming message\n const [humanMessage, aiMessage] =\n streamingConversations.current[currentConversation];\n streamingConversations.current[currentConversation] = [\n humanMessage,\n { ...aiMessage, content: aiMessage.content + content },\n ];\n\n setConversations(prevConversations => {\n const conversation =\n prevConversations[currentConversation] ?? [];\n\n const lastMessageIndex = conversation.length - 1;\n const lastMessage =\n conversation.length === 0\n ? createBotMessage({\n content: '',\n timestamp: getTimestamp(Date.now()),\n })\n : { ...conversation[lastMessageIndex] };\n\n lastMessage.isLoading = false;\n lastMessage.content += content;\n lastMessage.name =\n data?.response_metadata?.model || selectedModel;\n lastMessage.timestamp = getTimestamp(\n data?.response_metadata?.created_at || Date.now(),\n );\n\n const updatedConversation = [\n ...conversation.slice(0, lastMessageIndex),\n lastMessage,\n ];\n\n return {\n ...prevConversations,\n [currentConversation]: updatedConversation,\n };\n });\n }\n\n if (event === 'end') {\n const documents = data?.referenced_documents || [];\n\n setConversations(prevConversations => {\n const conversation =\n prevConversations[currentConversation] ?? [];\n\n const lastMessageIndex = conversation.length - 1;\n const lastMessage =\n conversation.length === 0\n ? createBotMessage({\n content: '',\n timestamp: getTimestamp(Date.now()),\n })\n : { ...conversation[lastMessageIndex] };\n\n if (documents.length) {\n lastMessage.sources = {\n sources: documents.map(\n (doc: { doc_title: string; doc_url: string }) => ({\n title: doc.doc_title,\n link: doc.doc_url,\n }),\n ),\n };\n }\n\n const updatedConversation = [\n ...conversation.slice(0, lastMessageIndex),\n lastMessage,\n ];\n\n return {\n ...prevConversations,\n [currentConversation]: updatedConversation,\n };\n });\n }\n } catch (error) {\n // eslint-disable-next-line no-console\n console.warn('Error parsing JSON:', error);\n if (typeof onComplete === 'function') {\n onComplete('Invalid JSON received');\n }\n }\n }\n }\n } catch (e) {\n setConversations(prevConversations => {\n const conversation = prevConversations[currentConversation] ?? [];\n\n const lastMessageIndex = conversation.length - 1;\n const lastMessage =\n conversation.length === 0\n ? createBotMessage({\n content: '',\n timestamp: getTimestamp(Date.now()),\n })\n : { ...conversation[lastMessageIndex] };\n\n lastMessage.isLoading = false;\n lastMessage.content += e;\n lastMessage.error = {\n title: e.message,\n };\n lastMessage.timestamp = getTimestamp(Date.now());\n\n const updatedConversation = [\n ...conversation.slice(0, lastMessageIndex),\n lastMessage,\n ];\n\n finalMessages.push(`${e}`);\n\n return {\n ...prevConversations,\n [newConversationId.length > 0\n ? newConversationId\n : currentConversation]: updatedConversation,\n };\n });\n }\n // reset current streaming\n streamingConversations.current[currentConversation] = [];\n if (typeof onComplete === 'function') {\n onComplete(finalMessages.join(''));\n }\n // Swap temp conversation messages with new conversation\n\n if (currentConversation === TEMP_CONVERSATION_ID && newConversationId) {\n setConversations(prevConversations => {\n return {\n ...prevConversations,\n [newConversationId]: prevConversations[TEMP_CONVERSATION_ID],\n };\n });\n\n onStart?.(newConversationId);\n\n setConversations(prev => {\n const { temp, ...rest } = prev;\n return rest;\n });\n }\n },\n\n [\n avatar,\n userName,\n onComplete,\n onStart,\n selectedModel,\n createMessage,\n currentConversation,\n ],\n );\n\n return {\n conversationMessages: conversations[currentConversation] ?? [],\n handleInputPrompt,\n conversations,\n scrollToBottomRef,\n ...queryProps,\n };\n};\n"],"names":["React"],"mappings":";;;;;;;;;AAqCa,MAAA,4BAAA,GAA+B,CAAC,mBAAgC,KAAA;AAC3E,EAAM,MAAA,aAAA,GAAgB,OAAO,gBAAgB,CAAA;AAC7C,EAAA,OAAO,QAAS,CAAA;AAAA,IACd,QAAA,EAAU,CAAC,sBAAA,EAAwB,mBAAmB,CAAA;AAAA,IACtD,OAAA,EAAS,sBACL,YAAY;AACV,MAAA,MAAM,QACJ,GAAA,MAAM,aAAc,CAAA,uBAAA,CAAwB,mBAAmB,CAAA;AAEjE,MAAO,OAAA,QAAA;AAAA,KAET,GAAA,SAAA;AAAA,IACJ,KAAO,EAAA;AAAA,GACR,CAAA;AACH;AAIA,MAAM,aACJ,GAAA,qGAAA;AASW,MAAA,uBAAA,GAA0B,CACrC,cACA,EAAA,QAAA,EACA,eACA,MAAiB,GAAA,aAAA,EACjB,YACA,OACG,KAAA;AACH,EAAA,MAAM,EAAE,WAAA,EAAa,aAAc,EAAA,GAAI,4BAA6B,EAAA;AACpE,EAAM,MAAA,iBAAA,GAAoBA,cAAM,CAAA,MAAA,CAA8B,IAAI,CAAA;AAElE,EAAA,MAAM,CAAC,mBAAqB,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IAAA,EAAS,GAAA,IAAA;AAC1B,UAAO,OAAA,IAAA;AAAA,SACR,CAAA;AAAA;AACH,KACF;AAAA,IAEA;AAAA,MACE,MAAA;AAAA,MACA,QAAA;AAAA,MACA,UAAA;AAAA,MACA,OAAA;AAAA,MACA,aAAA;AAAA,MACA,aAAA;AAAA,MACA;AAAA;AACF,GACF;AAEA,EAAO,OAAA;AAAA,IACL,oBAAsB,EAAA,aAAA,CAAc,mBAAmB,CAAA,IAAK,EAAC;AAAA,IAC7D,iBAAA;AAAA,IACA,aAAA;AAAA,IACA,iBAAA;AAAA,IACA,GAAG;AAAA,GACL;AACF;;;;"}
|
|
@@ -8,7 +8,8 @@ const useCreateConversationMessage = () => {
|
|
|
8
8
|
mutationFn: async ({
|
|
9
9
|
prompt,
|
|
10
10
|
selectedModel,
|
|
11
|
-
currentConversation
|
|
11
|
+
currentConversation,
|
|
12
|
+
attachments
|
|
12
13
|
}) => {
|
|
13
14
|
if (!currentConversation) {
|
|
14
15
|
throw new Error("Failed to generate AI response");
|
|
@@ -16,7 +17,8 @@ const useCreateConversationMessage = () => {
|
|
|
16
17
|
return await lightspeedApi.createMessage(
|
|
17
18
|
`${prompt}`,
|
|
18
19
|
selectedModel,
|
|
19
|
-
currentConversation
|
|
20
|
+
currentConversation,
|
|
21
|
+
attachments
|
|
20
22
|
);
|
|
21
23
|
},
|
|
22
24
|
onError: (error) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useCreateCoversationMessage.esm.js","sources":["../../src/hooks/useCreateCoversationMessage.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useApi } from '@backstage/core-plugin-api';\n\nimport { useMutation } from '@tanstack/react-query';\n\nimport { lightspeedApiRef } from '../api/api';\n\nexport const useCreateConversationMessage = () => {\n const lightspeedApi = useApi(lightspeedApiRef);\n\n return useMutation({\n mutationFn: async ({\n prompt,\n selectedModel,\n currentConversation,\n }: {\n prompt: string;\n selectedModel: string;\n currentConversation: string;\n }) => {\n if (!currentConversation) {\n throw new Error('Failed to generate AI response');\n }\n\n return await lightspeedApi.createMessage(\n `${prompt}`,\n selectedModel,\n currentConversation,\n );\n },\n onError: error => {\n // eslint-disable-next-line\n console.warn(error);\n },\n });\n};\n"],"names":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"useCreateCoversationMessage.esm.js","sources":["../../src/hooks/useCreateCoversationMessage.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useApi } from '@backstage/core-plugin-api';\n\nimport { useMutation } from '@tanstack/react-query';\n\nimport { lightspeedApiRef } from '../api/api';\nimport { Attachment } from '../types';\n\nexport const useCreateConversationMessage = () => {\n const lightspeedApi = useApi(lightspeedApiRef);\n\n return useMutation({\n mutationFn: async ({\n prompt,\n selectedModel,\n currentConversation,\n attachments,\n }: {\n prompt: string;\n selectedModel: string;\n currentConversation: string;\n attachments: Attachment[];\n }) => {\n if (!currentConversation) {\n throw new Error('Failed to generate AI response');\n }\n\n return await lightspeedApi.createMessage(\n `${prompt}`,\n selectedModel,\n currentConversation,\n attachments,\n );\n },\n onError: error => {\n // eslint-disable-next-line\n console.warn(error);\n },\n });\n};\n"],"names":[],"mappings":";;;;AAuBO,MAAM,+BAA+B,MAAM;AAChD,EAAM,MAAA,aAAA,GAAgB,OAAO,gBAAgB,CAAA;AAE7C,EAAA,OAAO,WAAY,CAAA;AAAA,IACjB,YAAY,OAAO;AAAA,MACjB,MAAA;AAAA,MACA,aAAA;AAAA,MACA,mBAAA;AAAA,MACA;AAAA,KAMI,KAAA;AACJ,MAAA,IAAI,CAAC,mBAAqB,EAAA;AACxB,QAAM,MAAA,IAAI,MAAM,gCAAgC,CAAA;AAAA;AAGlD,MAAA,OAAO,MAAM,aAAc,CAAA,aAAA;AAAA,QACzB,GAAG,MAAM,CAAA,CAAA;AAAA,QACT,aAAA;AAAA,QACA,mBAAA;AAAA,QACA;AAAA,OACF;AAAA,KACF;AAAA,IACA,SAAS,CAAS,KAAA,KAAA;AAEhB,MAAA,OAAA,CAAQ,KAAK,KAAK,CAAA;AAAA;AACpB,GACD,CAAA;AACH;;;;"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import React__default from 'react';
|
|
2
|
+
import { useApi, configApiRef } from '@backstage/core-plugin-api';
|
|
3
|
+
import { RHDH_SAMPLE_PROMPTS, DEFAULT_SAMPLE_PROMPTS } from '../const.esm.js';
|
|
4
|
+
import { getRandomSamplePrompts } from '../utils/prompt-utils.esm.js';
|
|
5
|
+
|
|
6
|
+
const useWelcomePrompts = () => {
|
|
7
|
+
const configApi = useApi(configApiRef);
|
|
8
|
+
return React__default.useMemo(() => {
|
|
9
|
+
const questionValidationEnabled = configApi.getOptionalBoolean("lightspeed.questionValidation") ?? true;
|
|
10
|
+
const DEFAULT_PROMPTS = questionValidationEnabled ? RHDH_SAMPLE_PROMPTS : [...DEFAULT_SAMPLE_PROMPTS, ...RHDH_SAMPLE_PROMPTS];
|
|
11
|
+
const samplePrompts = (configApi?.getOptionalConfigArray("lightspeed.prompts") ?? []).map((config) => ({
|
|
12
|
+
title: config.getString("title") ?? "",
|
|
13
|
+
message: config.getString("message") ?? ""
|
|
14
|
+
}));
|
|
15
|
+
return getRandomSamplePrompts(samplePrompts, DEFAULT_PROMPTS);
|
|
16
|
+
}, [configApi]);
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export { useWelcomePrompts };
|
|
20
|
+
//# sourceMappingURL=useWelcomePrompts.esm.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useWelcomePrompts.esm.js","sources":["../../src/hooks/useWelcomePrompts.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport React from 'react';\n\nimport { ConfigApi, configApiRef, useApi } from '@backstage/core-plugin-api';\n\nimport { DEFAULT_SAMPLE_PROMPTS, RHDH_SAMPLE_PROMPTS } from '../const';\nimport { SamplePrompts } from '../types';\nimport { getRandomSamplePrompts } from '../utils/prompt-utils';\n\nexport const useWelcomePrompts = (): SamplePrompts => {\n const configApi: ConfigApi = useApi(configApiRef);\n\n return React.useMemo(() => {\n const questionValidationEnabled =\n configApi.getOptionalBoolean('lightspeed.questionValidation') ?? true;\n\n const DEFAULT_PROMPTS = questionValidationEnabled\n ? RHDH_SAMPLE_PROMPTS\n : [...DEFAULT_SAMPLE_PROMPTS, ...RHDH_SAMPLE_PROMPTS];\n\n const samplePrompts: SamplePrompts = (\n configApi?.getOptionalConfigArray('lightspeed.prompts') ?? []\n ).map(config => ({\n title: config.getString('title') ?? '',\n message: config.getString('message') ?? '',\n }));\n return getRandomSamplePrompts(samplePrompts, DEFAULT_PROMPTS);\n }, [configApi]);\n};\n"],"names":["React"],"mappings":";;;;;AAuBO,MAAM,oBAAoB,MAAqB;AACpD,EAAM,MAAA,SAAA,GAAuB,OAAO,YAAY,CAAA;AAEhD,EAAO,OAAAA,cAAA,CAAM,QAAQ,MAAM;AACzB,IAAA,MAAM,yBACJ,GAAA,SAAA,CAAU,kBAAmB,CAAA,+BAA+B,CAAK,IAAA,IAAA;AAEnE,IAAA,MAAM,kBAAkB,yBACpB,GAAA,mBAAA,GACA,CAAC,GAAG,sBAAA,EAAwB,GAAG,mBAAmB,CAAA;AAEtD,IAAM,MAAA,aAAA,GAAA,CACJ,WAAW,sBAAuB,CAAA,oBAAoB,KAAK,EAAC,EAC5D,IAAI,CAAW,MAAA,MAAA;AAAA,MACf,KAAO,EAAA,MAAA,CAAO,SAAU,CAAA,OAAO,CAAK,IAAA,EAAA;AAAA,MACpC,OAAS,EAAA,MAAA,CAAO,SAAU,CAAA,SAAS,CAAK,IAAA;AAAA,KACxC,CAAA,CAAA;AACF,IAAO,OAAA,sBAAA,CAAuB,eAAe,eAAe,CAAA;AAAA,GAC9D,EAAG,CAAC,SAAS,CAAC,CAAA;AAChB;;;;"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
var SupportedFileType = /* @__PURE__ */ ((SupportedFileType2) => {
|
|
2
|
+
SupportedFileType2["JSON"] = "application/json";
|
|
3
|
+
SupportedFileType2["YAML"] = "application/x-yaml";
|
|
4
|
+
SupportedFileType2["TEXT"] = "text/plain";
|
|
5
|
+
return SupportedFileType2;
|
|
6
|
+
})(SupportedFileType || {});
|
|
7
|
+
|
|
8
|
+
export { SupportedFileType };
|
|
9
|
+
//# sourceMappingURL=types.esm.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.esm.js","sources":["../src/types.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SourcesCardProps } from '@patternfly/chatbot';\nimport { AlertProps } from '@patternfly/react-core';\n\nexport type Conversations = {\n [key: string]: {\n user: string;\n bot: string;\n model: string;\n loading: boolean;\n timestamp: string;\n botTimestamp: string;\n error?: AlertProps;\n };\n};\n\nexport interface BaseMessage {\n name: string;\n type: string;\n id: number;\n content: string;\n response_metadata: {\n model?: string;\n created_at: number;\n role?: string;\n };\n sources?: SourcesCardProps;\n additional_kwargs: {\n [_key: string]: any;\n };\n error?: AlertProps;\n}\nexport type ConversationSummary = {\n conversation_id: string;\n last_message_timestamp: number;\n topic_summary: string;\n};\n\nexport enum SupportedFileType {\n JSON = 'application/json',\n YAML = 'application/x-yaml',\n TEXT = 'text/plain',\n}\nexport interface FileContent {\n content: string;\n type: string;\n name: string;\n}\n\nexport type Attachment = {\n attachment_type: string;\n content_type: string;\n content: string;\n};\n\nexport type ConversationList = ConversationSummary[];\n\nexport type SamplePrompts = {\n title: string;\n message: string;\n}[];\n"],"names":["SupportedFileType"],"mappings":"AAqDY,IAAA,iBAAA,qBAAAA,kBAAL,KAAA;AACL,EAAAA,mBAAA,MAAO,CAAA,GAAA,kBAAA;AACP,EAAAA,mBAAA,MAAO,CAAA,GAAA,oBAAA;AACP,EAAAA,mBAAA,MAAO,CAAA,GAAA,YAAA;AAHG,EAAAA,OAAAA,kBAAAA;AAAA,CAAA,EAAA,iBAAA,IAAA,EAAA;;;;"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { SupportedFileType } from '../types.esm.js';
|
|
2
|
+
|
|
3
|
+
const isSupportedFileType = (file) => {
|
|
4
|
+
const isJson = file.type === SupportedFileType.JSON;
|
|
5
|
+
const isYaml = file.type === SupportedFileType.YAML || file.name.endsWith(".yaml") || file.name.endsWith(".yml");
|
|
6
|
+
const isText = file.type === SupportedFileType.TEXT;
|
|
7
|
+
return isJson || isYaml || isText;
|
|
8
|
+
};
|
|
9
|
+
const readFileAsText = (file) => new Promise((resolve, reject) => {
|
|
10
|
+
const reader = new FileReader();
|
|
11
|
+
reader.onload = () => resolve(reader.result);
|
|
12
|
+
reader.onerror = () => reject(reader.error);
|
|
13
|
+
reader.readAsText(file);
|
|
14
|
+
});
|
|
15
|
+
const sanitizeFileType = (fileContent) => fileContent.type === SupportedFileType.YAML ? "application/yaml" : fileContent.type;
|
|
16
|
+
const getAttachments = (fileContents) => fileContents.map((file) => ({
|
|
17
|
+
attachment_type: "api object",
|
|
18
|
+
content_type: sanitizeFileType(file),
|
|
19
|
+
content: fileContents.find((f) => f.name === file.name)?.content || ""
|
|
20
|
+
}));
|
|
21
|
+
|
|
22
|
+
export { getAttachments, isSupportedFileType, readFileAsText, sanitizeFileType };
|
|
23
|
+
//# sourceMappingURL=attachment-utils.esm.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attachment-utils.esm.js","sources":["../../src/utils/attachment-utils.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Attachment, FileContent, SupportedFileType } from '../types';\n\nexport const isSupportedFileType = (file: File) => {\n const isJson = file.type === SupportedFileType.JSON;\n const isYaml =\n file.type === SupportedFileType.YAML ||\n file.name.endsWith('.yaml') ||\n file.name.endsWith('.yml');\n const isText = file.type === SupportedFileType.TEXT;\n return isJson || isYaml || isText;\n};\n\nexport const readFileAsText = (file: File): Promise<string | null> =>\n new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = () => reject(reader.error);\n reader.readAsText(file);\n });\n\nexport const sanitizeFileType = (fileContent: FileContent): string =>\n fileContent.type === SupportedFileType.YAML\n ? 'application/yaml'\n : fileContent.type;\n\nexport const getAttachments = (fileContents: FileContent[]): Attachment[] =>\n fileContents.map(file => ({\n attachment_type: 'api object',\n content_type: sanitizeFileType(file),\n content: fileContents.find(f => f.name === file.name)?.content || '',\n }));\n"],"names":[],"mappings":";;AAiBa,MAAA,mBAAA,GAAsB,CAAC,IAAe,KAAA;AACjD,EAAM,MAAA,MAAA,GAAS,IAAK,CAAA,IAAA,KAAS,iBAAkB,CAAA,IAAA;AAC/C,EAAA,MAAM,MACJ,GAAA,IAAA,CAAK,IAAS,KAAA,iBAAA,CAAkB,IAChC,IAAA,IAAA,CAAK,IAAK,CAAA,QAAA,CAAS,OAAO,CAAA,IAC1B,IAAK,CAAA,IAAA,CAAK,SAAS,MAAM,CAAA;AAC3B,EAAM,MAAA,MAAA,GAAS,IAAK,CAAA,IAAA,KAAS,iBAAkB,CAAA,IAAA;AAC/C,EAAA,OAAO,UAAU,MAAU,IAAA,MAAA;AAC7B;AAEO,MAAM,iBAAiB,CAAC,IAAA,KAC7B,IAAI,OAAQ,CAAA,CAAC,SAAS,MAAW,KAAA;AAC/B,EAAM,MAAA,MAAA,GAAS,IAAI,UAAW,EAAA;AAC9B,EAAA,MAAA,CAAO,MAAS,GAAA,MAAM,OAAQ,CAAA,MAAA,CAAO,MAAgB,CAAA;AACrD,EAAA,MAAA,CAAO,OAAU,GAAA,MAAM,MAAO,CAAA,MAAA,CAAO,KAAK,CAAA;AAC1C,EAAA,MAAA,CAAO,WAAW,IAAI,CAAA;AACxB,CAAC;AAEU,MAAA,gBAAA,GAAmB,CAAC,WAC/B,KAAA,WAAA,CAAY,SAAS,iBAAkB,CAAA,IAAA,GACnC,qBACA,WAAY,CAAA;AAEX,MAAM,cAAiB,GAAA,CAAC,YAC7B,KAAA,YAAA,CAAa,IAAI,CAAS,IAAA,MAAA;AAAA,EACxB,eAAiB,EAAA,YAAA;AAAA,EACjB,YAAA,EAAc,iBAAiB,IAAI,CAAA;AAAA,EACnC,OAAA,EAAS,aAAa,IAAK,CAAA,CAAA,CAAA,KAAK,EAAE,IAAS,KAAA,IAAA,CAAK,IAAI,CAAA,EAAG,OAAW,IAAA;AACpE,CAAE,CAAA;;;;"}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
|
-
const getFootnoteProps = () => ({
|
|
2
|
-
label: "
|
|
1
|
+
const getFootnoteProps = (additionalClassName) => ({
|
|
2
|
+
label: "Always check AI/LLM generated responses for accuracy prior to use.",
|
|
3
3
|
popover: {
|
|
4
|
+
popoverProps: {
|
|
5
|
+
className: additionalClassName ?? ""
|
|
6
|
+
},
|
|
4
7
|
title: "Verify accuracy",
|
|
5
8
|
description: `While Lightspeed strives for accuracy, there's always a possibility of errors. It's a good practice to verify critical information from reliable sources, especially if it's crucial for decision-making or actions.`,
|
|
6
9
|
bannerImage: {
|
|
@@ -46,7 +49,8 @@ const createMessage = ({
|
|
|
46
49
|
isLoading = false,
|
|
47
50
|
content,
|
|
48
51
|
timestamp,
|
|
49
|
-
error
|
|
52
|
+
error,
|
|
53
|
+
sources
|
|
50
54
|
}) => ({
|
|
51
55
|
role,
|
|
52
56
|
name,
|
|
@@ -54,7 +58,8 @@ const createMessage = ({
|
|
|
54
58
|
isLoading,
|
|
55
59
|
content,
|
|
56
60
|
timestamp,
|
|
57
|
-
error
|
|
61
|
+
error,
|
|
62
|
+
sources
|
|
58
63
|
});
|
|
59
64
|
const createUserMessage = (props) => createMessage({
|
|
60
65
|
...props,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lightspeed-chatbox-utils.esm.js","sources":["../../src/utils/lightspeed-chatbox-utils.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Conversation } from '@patternfly/chatbot';\n\nimport { BaseMessage, ConversationList, ConversationSummary } from '../types';\n\nexport const getFootnoteProps = () => ({\n label: 'Lightspeed uses AI. Check for mistakes.',\n popover: {\n title: 'Verify accuracy',\n description: `While Lightspeed strives for accuracy, there's always a possibility of errors. It's a good practice to verify critical information from reliable sources, especially if it's crucial for decision-making or actions.`,\n bannerImage: {\n src: 'https://cdn.dribbble.com/userupload/10651749/file/original-8a07b8e39d9e8bf002358c66fce1223e.gif',\n alt: 'Example image for footnote popover',\n },\n cta: {\n label: 'Got it',\n onClick: () => {},\n },\n link: {\n label: 'Learn more',\n url: 'https://www.redhat.com/',\n },\n },\n});\n\nexport const getTimestampVariablesString = (v: number) => {\n if (v < 10) {\n return `0${v}`;\n }\n return `${v}`;\n};\n\nexport const getTimestamp = (unix_timestamp: number) => {\n if (typeof unix_timestamp !== 'number' || isNaN(unix_timestamp)) {\n // eslint-disable-next-line no-console\n console.error('Invalid Unix timestamp provided');\n return '';\n }\n\n const a = new Date(unix_timestamp);\n const month = getTimestampVariablesString(a.getMonth() + 1);\n const year = a.getFullYear();\n const date = getTimestampVariablesString(a.getDate());\n const hour = getTimestampVariablesString(a.getHours());\n const min = getTimestampVariablesString(a.getMinutes());\n const sec = getTimestampVariablesString(a.getSeconds());\n const time = `${date}/${month}/${year}, ${hour}:${min}:${sec}`;\n return time;\n};\n\nexport const splitJsonStrings = (jsonString: string): string[] => {\n const chunks = jsonString.split('}{');\n\n if (chunks.length <= 1) {\n return [jsonString];\n }\n\n return chunks.map((chunk, index, arr) => {\n if (index === 0) {\n return `${chunk}}`;\n } else if (index === arr.length - 1) {\n return `{${chunk}`;\n }\n return `{${chunk}}`;\n });\n};\n\ntype MessageProps = {\n content: string;\n timestamp: string;\n name?: string;\n avatar?: string | any;\n isLoading?: boolean;\n error?: {\n title: string;\n };\n};\n\nexport const createMessage = ({\n role,\n name = 'Guest',\n avatar,\n isLoading = false,\n content,\n timestamp,\n error,\n}: MessageProps & { role: 'user' | 'bot' }) => ({\n role,\n name,\n avatar,\n isLoading,\n content,\n timestamp,\n error,\n});\n\nexport const createUserMessage = (props: MessageProps) =>\n createMessage({\n ...props,\n role: 'user',\n name: props.name ?? 'Guest',\n });\n\nexport const createBotMessage = (props: MessageProps) =>\n createMessage({\n ...props,\n role: 'bot',\n });\n\nexport const getMessageData = (message: BaseMessage) => {\n return {\n model: message?.response_metadata?.model,\n content: message?.content || '',\n timestamp: getTimestamp(message?.response_metadata?.created_at * 1000),\n };\n};\n\nexport const getDayDifference = (sourceTime: number, targetTime: number) => {\n const sourceDate = new Date(sourceTime);\n const targetDate = new Date(targetTime);\n\n sourceDate.setHours(0, 0, 0, 0);\n targetDate.setHours(0, 0, 0, 0);\n\n const timeDifference = sourceDate.getTime() - targetDate.getTime();\n\n return Math.floor(timeDifference / (1000 * 60 * 60 * 24));\n};\n\nexport const getCategorizeMessages = (\n messages: ConversationList,\n addProps: (c: ConversationSummary) => { [k: string]: any },\n): { [k: string]: Conversation[] } => {\n const now: any = new Date();\n const today = now.toDateString();\n\n const categorizedMessages: { [k: string]: Conversation[] } = {\n Today: [],\n Yesterday: [],\n 'Previous 7 Days': [],\n 'Previous 30 Days': [],\n };\n messages\n .sort((a, b) => b.last_message_timestamp - a.last_message_timestamp)\n .forEach(c => {\n const messageDate = new Date(c.last_message_timestamp * 1000);\n const messageDayString = messageDate.toDateString();\n const dayDifference = getDayDifference(\n now,\n c.last_message_timestamp * 1000,\n );\n const message: Conversation = {\n id: c.conversation_id,\n text: c.topic_summary,\n label: 'Options',\n ...addProps(c),\n };\n\n if (messageDayString === today) {\n categorizedMessages.Today.push(message);\n } else if (dayDifference === 1) {\n categorizedMessages.Yesterday.push(message);\n } else if (dayDifference <= 7) {\n categorizedMessages['Previous 7 Days'].push(message);\n } else if (dayDifference <= 30) {\n categorizedMessages['Previous 30 Days'].push(message);\n } else {\n // handle month-wise grouping\n const monthYear = messageDate.toLocaleString('default', {\n month: 'long',\n year: 'numeric',\n });\n if (!categorizedMessages[monthYear]) {\n categorizedMessages[monthYear] = [];\n }\n categorizedMessages[monthYear].push(message);\n }\n });\n\n const filteredCategories = Object.keys(categorizedMessages).reduce(\n (result, category) => {\n if (categorizedMessages[category].length > 0) {\n result[category] = categorizedMessages[category];\n }\n return result;\n },\n {} as any,\n );\n\n return filteredCategories;\n};\n"],"names":[],"mappings":"AAmBO,MAAM,mBAAmB,OAAO;AAAA,EACrC,KAAO,EAAA,yCAAA;AAAA,EACP,OAAS,EAAA;AAAA,IACP,KAAO,EAAA,iBAAA;AAAA,IACP,WAAa,EAAA,CAAA,oNAAA,CAAA;AAAA,IACb,WAAa,EAAA;AAAA,MACX,GAAK,EAAA,iGAAA;AAAA,MACL,GAAK,EAAA;AAAA,KACP;AAAA,IACA,GAAK,EAAA;AAAA,MACH,KAAO,EAAA,QAAA;AAAA,MACP,SAAS,MAAM;AAAA;AAAC,KAClB;AAAA,IACA,IAAM,EAAA;AAAA,MACJ,KAAO,EAAA,YAAA;AAAA,MACP,GAAK,EAAA;AAAA;AACP;AAEJ,CAAA;AAEa,MAAA,2BAAA,GAA8B,CAAC,CAAc,KAAA;AACxD,EAAA,IAAI,IAAI,EAAI,EAAA;AACV,IAAA,OAAO,IAAI,CAAC,CAAA,CAAA;AAAA;AAEd,EAAA,OAAO,GAAG,CAAC,CAAA,CAAA;AACb;AAEa,MAAA,YAAA,GAAe,CAAC,cAA2B,KAAA;AACtD,EAAA,IAAI,OAAO,cAAA,KAAmB,QAAY,IAAA,KAAA,CAAM,cAAc,CAAG,EAAA;AAE/D,IAAA,OAAA,CAAQ,MAAM,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AS,CAAE,CAAA,IAAA,CAAK,OAAO,CAAA;AAAA;AAC7C,GACD,CAAA;AAEH,EAAA,MAAM,kBAAqB,GAAA,MAAA,CAAO,IAAK,CAAA,mBAAmB,CAAE,CAAA,MAAA;AAAA,IAC1D,CAAC,QAAQ,QAAa,KAAA;AACpB,MAAA,IAAI,mBAAoB,CAAA,QAAQ,CAAE,CAAA,MAAA,GAAS,CAAG,EAAA;AAC5C,QAAO,MAAA,CAAA,QAAQ,CAAI,GAAA,mBAAA,CAAoB,QAAQ,CAAA;AAAA;AAEjD,MAAO,OAAA,MAAA;AAAA,KACT;AAAA,IACA;AAAC,GACH;AAEA,EAAO,OAAA,kBAAA;AACT;;;;"}
|
|
1
|
+
{"version":3,"file":"lightspeed-chatbox-utils.esm.js","sources":["../../src/utils/lightspeed-chatbox-utils.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { Conversation, SourcesCardProps } from '@patternfly/chatbot';\nimport { PopoverProps } from '@patternfly/react-core';\n\nimport { BaseMessage, ConversationList, ConversationSummary } from '../types';\n\nexport const getFootnoteProps = (additionalClassName: string) => ({\n label: 'Always check AI/LLM generated responses for accuracy prior to use.',\n popover: {\n popoverProps: {\n className: additionalClassName ?? '',\n } as PopoverProps,\n title: 'Verify accuracy',\n description: `While Lightspeed strives for accuracy, there's always a possibility of errors. It's a good practice to verify critical information from reliable sources, especially if it's crucial for decision-making or actions.`,\n bannerImage: {\n src: 'https://cdn.dribbble.com/userupload/10651749/file/original-8a07b8e39d9e8bf002358c66fce1223e.gif',\n alt: 'Example image for footnote popover',\n },\n cta: {\n label: 'Got it',\n onClick: () => {},\n },\n link: {\n label: 'Learn more',\n url: 'https://www.redhat.com/',\n },\n },\n});\n\nexport const getTimestampVariablesString = (v: number) => {\n if (v < 10) {\n return `0${v}`;\n }\n return `${v}`;\n};\n\nexport const getTimestamp = (unix_timestamp: number) => {\n if (typeof unix_timestamp !== 'number' || isNaN(unix_timestamp)) {\n // eslint-disable-next-line no-console\n console.error('Invalid Unix timestamp provided');\n return '';\n }\n\n const a = new Date(unix_timestamp);\n const month = getTimestampVariablesString(a.getMonth() + 1);\n const year = a.getFullYear();\n const date = getTimestampVariablesString(a.getDate());\n const hour = getTimestampVariablesString(a.getHours());\n const min = getTimestampVariablesString(a.getMinutes());\n const sec = getTimestampVariablesString(a.getSeconds());\n const time = `${date}/${month}/${year}, ${hour}:${min}:${sec}`;\n return time;\n};\n\nexport const splitJsonStrings = (jsonString: string): string[] => {\n const chunks = jsonString.split('}{');\n\n if (chunks.length <= 1) {\n return [jsonString];\n }\n\n return chunks.map((chunk, index, arr) => {\n if (index === 0) {\n return `${chunk}}`;\n } else if (index === arr.length - 1) {\n return `{${chunk}`;\n }\n return `{${chunk}}`;\n });\n};\n\ntype MessageProps = {\n content: string;\n timestamp: string;\n name?: string;\n avatar?: string | any;\n isLoading?: boolean;\n error?: {\n title: string;\n };\n sources?: SourcesCardProps;\n};\n\nexport const createMessage = ({\n role,\n name = 'Guest',\n avatar,\n isLoading = false,\n content,\n timestamp,\n error,\n sources,\n}: MessageProps & { role: 'user' | 'bot' }) => ({\n role,\n name,\n avatar,\n isLoading,\n content,\n timestamp,\n error,\n sources,\n});\n\nexport const createUserMessage = (props: MessageProps) =>\n createMessage({\n ...props,\n role: 'user',\n name: props.name ?? 'Guest',\n });\n\nexport const createBotMessage = (props: MessageProps) =>\n createMessage({\n ...props,\n role: 'bot',\n });\n\nexport const getMessageData = (message: BaseMessage) => {\n return {\n model: message?.response_metadata?.model,\n content: message?.content || '',\n timestamp: getTimestamp(message?.response_metadata?.created_at * 1000),\n };\n};\n\nexport const getDayDifference = (sourceTime: number, targetTime: number) => {\n const sourceDate = new Date(sourceTime);\n const targetDate = new Date(targetTime);\n\n sourceDate.setHours(0, 0, 0, 0);\n targetDate.setHours(0, 0, 0, 0);\n\n const timeDifference = sourceDate.getTime() - targetDate.getTime();\n\n return Math.floor(timeDifference / (1000 * 60 * 60 * 24));\n};\n\nexport const getCategorizeMessages = (\n messages: ConversationList,\n addProps: (c: ConversationSummary) => { [k: string]: any },\n): { [k: string]: Conversation[] } => {\n const now: any = new Date();\n const today = now.toDateString();\n\n const categorizedMessages: { [k: string]: Conversation[] } = {\n Today: [],\n Yesterday: [],\n 'Previous 7 Days': [],\n 'Previous 30 Days': [],\n };\n messages\n .sort((a, b) => b.last_message_timestamp - a.last_message_timestamp)\n .forEach(c => {\n const messageDate = new Date(c.last_message_timestamp * 1000);\n const messageDayString = messageDate.toDateString();\n const dayDifference = getDayDifference(\n now,\n c.last_message_timestamp * 1000,\n );\n const message: Conversation = {\n id: c.conversation_id,\n text: c.topic_summary,\n label: 'Options',\n ...addProps(c),\n };\n\n if (messageDayString === today) {\n categorizedMessages.Today.push(message);\n } else if (dayDifference === 1) {\n categorizedMessages.Yesterday.push(message);\n } else if (dayDifference <= 7) {\n categorizedMessages['Previous 7 Days'].push(message);\n } else if (dayDifference <= 30) {\n categorizedMessages['Previous 30 Days'].push(message);\n } else {\n // handle month-wise grouping\n const monthYear = messageDate.toLocaleString('default', {\n month: 'long',\n year: 'numeric',\n });\n if (!categorizedMessages[monthYear]) {\n categorizedMessages[monthYear] = [];\n }\n categorizedMessages[monthYear].push(message);\n }\n });\n\n const filteredCategories = Object.keys(categorizedMessages).reduce(\n (result, category) => {\n if (categorizedMessages[category].length > 0) {\n result[category] = categorizedMessages[category];\n }\n return result;\n },\n {} as any,\n );\n\n return filteredCategories;\n};\n"],"names":[],"mappings":"AAoBa,MAAA,gBAAA,GAAmB,CAAC,mBAAiC,MAAA;AAAA,EAChE,K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OAAA,kBAAA;AACT;;;;"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
const getRandomPrompts = (prompts, n) => {
|
|
2
|
+
const shuffled = prompts.slice().sort(() => 0.5 - Math.random());
|
|
3
|
+
return shuffled.slice(0, Math.min(n, prompts.length));
|
|
4
|
+
};
|
|
5
|
+
const getRandomSamplePrompts = (userPrompts = [], defaultPrompts = [], numberOfPrompts = 3) => {
|
|
6
|
+
const userCount = userPrompts.length;
|
|
7
|
+
if (userCount >= numberOfPrompts) {
|
|
8
|
+
return getRandomPrompts(userPrompts, numberOfPrompts);
|
|
9
|
+
}
|
|
10
|
+
const userSelected = getRandomPrompts(userPrompts, userCount);
|
|
11
|
+
const remaining = numberOfPrompts - userSelected.length;
|
|
12
|
+
const defaultSelected = getRandomPrompts(defaultPrompts, remaining);
|
|
13
|
+
return [...userSelected, ...defaultSelected];
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export { getRandomSamplePrompts };
|
|
17
|
+
//# sourceMappingURL=prompt-utils.esm.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt-utils.esm.js","sources":["../../src/utils/prompt-utils.ts"],"sourcesContent":["/*\n * Copyright Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { SamplePrompts } from '../types';\n\nconst getRandomPrompts = (prompts: SamplePrompts, n: number) => {\n const shuffled = prompts.slice().sort(() => 0.5 - Math.random()); // NOSONAR\n return shuffled.slice(0, Math.min(n, prompts.length));\n};\n\nexport const getRandomSamplePrompts = (\n userPrompts: SamplePrompts = [],\n defaultPrompts: SamplePrompts = [],\n numberOfPrompts: number = 3,\n) => {\n const userCount = userPrompts.length;\n\n if (userCount >= numberOfPrompts) {\n return getRandomPrompts(userPrompts, numberOfPrompts);\n }\n const userSelected = getRandomPrompts(userPrompts, userCount);\n const remaining = numberOfPrompts - userSelected.length;\n const defaultSelected = getRandomPrompts(defaultPrompts, remaining);\n return [...userSelected, ...defaultSelected];\n};\n"],"names":[],"mappings":"AAiBA,MAAM,gBAAA,GAAmB,CAAC,OAAA,EAAwB,CAAc,KAAA;AAC9D,EAAM,MAAA,QAAA,GAAW,QAAQ,KAAM,EAAA,CAAE,KAAK,MAAM,GAAA,GAAM,IAAK,CAAA,MAAA,EAAQ,CAAA;AAC/D,EAAO,OAAA,QAAA,CAAS,MAAM,CAAG,EAAA,IAAA,CAAK,IAAI,CAAG,EAAA,OAAA,CAAQ,MAAM,CAAC,CAAA;AACtD,CAAA;AAEa,MAAA,sBAAA,GAAyB,CACpC,WAA6B,GAAA,IAC7B,cAAgC,GAAA,EAChC,EAAA,eAAA,GAA0B,CACvB,KAAA;AACH,EAAA,MAAM,YAAY,WAAY,CAAA,MAAA;AAE9B,EAAA,IAAI,aAAa,eAAiB,EAAA;AAChC,IAAO,OAAA,gBAAA,CAAiB,aAAa,eAAe,CAAA;AAAA;AAEtD,EAAM,MAAA,YAAA,GAAe,gBAAiB,CAAA,WAAA,EAAa,SAAS,CAAA;AAC5D,EAAM,MAAA,SAAA,GAAY,kBAAkB,YAAa,CAAA,MAAA;AACjD,EAAM,MAAA,eAAA,GAAkB,gBAAiB,CAAA,cAAA,EAAgB,SAAS,CAAA;AAClE,EAAA,OAAO,CAAC,GAAG,YAAc,EAAA,GAAG,eAAe,CAAA;AAC7C;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@red-hat-developer-hub/backstage-plugin-lightspeed",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.2",
|
|
4
4
|
"main": "dist/index.esm.js",
|
|
5
5
|
"types": "dist/index.d.ts",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -44,9 +44,9 @@
|
|
|
44
44
|
"@material-ui/core": "^4.9.13",
|
|
45
45
|
"@material-ui/lab": "^4.0.0-alpha.61",
|
|
46
46
|
"@mui/icons-material": "^6.1.8",
|
|
47
|
-
"@patternfly/chatbot": "
|
|
48
|
-
"@patternfly/react-core": "6.
|
|
49
|
-
"@red-hat-developer-hub/backstage-plugin-lightspeed-common": "^0.3.
|
|
47
|
+
"@patternfly/chatbot": "6.3.0-prerelease.17",
|
|
48
|
+
"@patternfly/react-core": "6.3.0-prerelease.4",
|
|
49
|
+
"@red-hat-developer-hub/backstage-plugin-lightspeed-common": "^0.3.1",
|
|
50
50
|
"@tanstack/react-query": "^5.59.15",
|
|
51
51
|
"openai": "^4.52.6",
|
|
52
52
|
"react-markdown": "^9.0.1",
|
|
@@ -67,9 +67,9 @@
|
|
|
67
67
|
"@testing-library/dom": "^10.0.0",
|
|
68
68
|
"@testing-library/jest-dom": "^6.0.0",
|
|
69
69
|
"@testing-library/react": "^15.0.0",
|
|
70
|
-
"@testing-library/user-event": "14.
|
|
70
|
+
"@testing-library/user-event": "14.6.1",
|
|
71
71
|
"msw": "1.3.5",
|
|
72
|
-
"prettier": "3.
|
|
72
|
+
"prettier": "3.5.3",
|
|
73
73
|
"react": "16.13.1 || ^17.0.0 || ^18.0.0",
|
|
74
74
|
"react-dom": "16.13.1 || ^17.0.0 || ^18.0.0",
|
|
75
75
|
"react-router-dom": "^6.0.0"
|