@red-hat-developer-hub/backstage-plugin-lightspeed 0.4.3 → 0.5.0
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 +6 -0
- package/dist/api/LightspeedApiClient.esm.js +38 -25
- package/dist/api/LightspeedApiClient.esm.js.map +1 -1
- package/dist/api/api.esm.js.map +1 -1
- package/dist/components/LightSpeedChat.esm.js +17 -16
- package/dist/components/LightSpeedChat.esm.js.map +1 -1
- package/dist/const.esm.js +4 -0
- package/dist/const.esm.js.map +1 -0
- package/dist/hooks/useConversationMessages.esm.js +73 -41
- package/dist/hooks/useConversationMessages.esm.js.map +1 -1
- package/dist/utils/lightspeed-chatbox-utils.esm.js +15 -24
- package/dist/utils/lightspeed-chatbox-utils.esm.js.map +1 -1
- package/package.json +1 -1
- package/dist/hooks/useCreateConversation.esm.js +0 -19
- package/dist/hooks/useCreateConversation.esm.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { TEMP_CONVERSATION_ID } from '../const.esm.js';
|
|
2
|
+
|
|
1
3
|
class LightspeedApiClient {
|
|
2
4
|
configApi;
|
|
3
5
|
fetchApi;
|
|
@@ -19,20 +21,30 @@ class LightspeedApiClient {
|
|
|
19
21
|
"Content-Type": "application/json"
|
|
20
22
|
},
|
|
21
23
|
body: JSON.stringify({
|
|
22
|
-
conversation_id,
|
|
23
|
-
serverURL: this.getServerUrl(),
|
|
24
|
+
conversation_id: conversation_id === TEMP_CONVERSATION_ID ? undefined : conversation_id,
|
|
24
25
|
model: selectedModel,
|
|
25
|
-
|
|
26
|
-
|
|
26
|
+
provider: this.configApi.getConfigArray("lightspeed.servers")[0].getOptionalString("id"),
|
|
27
|
+
// Currently supports a single llm server
|
|
28
|
+
query: prompt
|
|
27
29
|
})
|
|
28
30
|
});
|
|
29
31
|
if (!response.body) {
|
|
30
32
|
throw new Error("Readable stream is not supported or there is no body.");
|
|
31
33
|
}
|
|
32
34
|
if (!response.ok) {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
);
|
|
35
|
+
const body = await response.body.getReader();
|
|
36
|
+
const reader = body.read();
|
|
37
|
+
const decoder = new TextDecoder("utf-8");
|
|
38
|
+
const text = await reader.then(({ done, value }) => {
|
|
39
|
+
if (done) {
|
|
40
|
+
return "";
|
|
41
|
+
}
|
|
42
|
+
return decoder.decode(value);
|
|
43
|
+
});
|
|
44
|
+
const errorMessage = JSON.parse(text);
|
|
45
|
+
if (errorMessage?.error) {
|
|
46
|
+
throw new Error(`failed to create message: ${errorMessage.error}`);
|
|
47
|
+
}
|
|
36
48
|
}
|
|
37
49
|
return response.body.getReader();
|
|
38
50
|
}
|
|
@@ -52,39 +64,40 @@ class LightspeedApiClient {
|
|
|
52
64
|
async getAllModels() {
|
|
53
65
|
const baseUrl = await this.getBaseUrl();
|
|
54
66
|
const result = await this.fetcher(`${baseUrl}/v1/models`);
|
|
67
|
+
if (!result.ok) {
|
|
68
|
+
throw new Error(
|
|
69
|
+
`failed to get models, status ${result.status}: ${result.statusText}`
|
|
70
|
+
);
|
|
71
|
+
}
|
|
55
72
|
const response = await result.json();
|
|
56
73
|
return response?.data ? response.data : [];
|
|
57
74
|
}
|
|
58
75
|
async getConversationMessages(conversation_id) {
|
|
76
|
+
if (conversation_id === TEMP_CONVERSATION_ID) {
|
|
77
|
+
return [];
|
|
78
|
+
}
|
|
59
79
|
const baseUrl = await this.getBaseUrl();
|
|
60
80
|
const result = await this.fetcher(
|
|
61
81
|
`${baseUrl}/conversations/${encodeURIComponent(conversation_id)}`
|
|
62
82
|
);
|
|
63
|
-
|
|
83
|
+
if (!result.ok) {
|
|
84
|
+
throw new Error(
|
|
85
|
+
`failed to get conversation messages, status ${result.status}: ${result.statusText}`
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
const response = await result.json();
|
|
89
|
+
return response.chat_history ?? [];
|
|
64
90
|
}
|
|
65
91
|
async getConversations() {
|
|
66
92
|
const baseUrl = await this.getBaseUrl();
|
|
67
93
|
const result = await this.fetcher(`${baseUrl}/conversations`);
|
|
68
|
-
|
|
69
|
-
}
|
|
70
|
-
async createConversation() {
|
|
71
|
-
const baseUrl = await this.getBaseUrl();
|
|
72
|
-
const response = await this.fetchApi.fetch(`${baseUrl}/conversations`, {
|
|
73
|
-
method: "POST",
|
|
74
|
-
headers: {
|
|
75
|
-
"Content-Type": "application/json"
|
|
76
|
-
},
|
|
77
|
-
body: JSON.stringify({})
|
|
78
|
-
});
|
|
79
|
-
if (!response.body) {
|
|
80
|
-
throw new Error("Something went wrong.");
|
|
81
|
-
}
|
|
82
|
-
if (!response.ok) {
|
|
94
|
+
if (!result.ok) {
|
|
83
95
|
throw new Error(
|
|
84
|
-
`failed to
|
|
96
|
+
`failed to get conversation, status ${result.status}: ${result.statusText}`
|
|
85
97
|
);
|
|
86
98
|
}
|
|
87
|
-
|
|
99
|
+
const response = await result.json();
|
|
100
|
+
return response.conversations ?? [];
|
|
88
101
|
}
|
|
89
102
|
async deleteConversation(conversation_id) {
|
|
90
103
|
const baseUrl = await this.getBaseUrl();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LightspeedApiClient.esm.js","sources":["../../src/api/LightspeedApiClient.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 { ConfigApi, FetchApi } from '@backstage/core-plugin-api';\n\nimport { LightspeedAPI } from './api';\n\nexport type Options = {\n configApi: ConfigApi;\n fetchApi: FetchApi;\n};\n\nexport class LightspeedApiClient implements LightspeedAPI {\n private readonly configApi: ConfigApi;\n private readonly fetchApi: FetchApi;\n\n constructor(options: Options) {\n this.configApi = options.configApi;\n this.fetchApi = options.fetchApi;\n }\n\n async getBaseUrl() {\n return `${this.configApi.getString('backend.baseUrl')}/api/lightspeed`;\n }\n\n getServerUrl() {\n // Currently supports a single llm server\n return `${this.configApi\n .getConfigArray('lightspeed.servers')[0]\n .getOptionalString('url')}`;\n }\n\n async createMessage(\n prompt: string,\n selectedModel: string,\n conversation_id: string,\n ) {\n const baseUrl = await this.getBaseUrl();\n\n const response = await this.fetchApi.fetch(`${baseUrl}/v1/query`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n conversation_id
|
|
1
|
+
{"version":3,"file":"LightspeedApiClient.esm.js","sources":["../../src/api/LightspeedApiClient.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 { ConfigApi, FetchApi } from '@backstage/core-plugin-api';\n\nimport { TEMP_CONVERSATION_ID } from '../const';\nimport { LightspeedAPI } from './api';\n\nexport type Options = {\n configApi: ConfigApi;\n fetchApi: FetchApi;\n};\n\nexport class LightspeedApiClient implements LightspeedAPI {\n private readonly configApi: ConfigApi;\n private readonly fetchApi: FetchApi;\n\n constructor(options: Options) {\n this.configApi = options.configApi;\n this.fetchApi = options.fetchApi;\n }\n\n async getBaseUrl() {\n return `${this.configApi.getString('backend.baseUrl')}/api/lightspeed`;\n }\n\n getServerUrl() {\n // Currently supports a single llm server\n return `${this.configApi\n .getConfigArray('lightspeed.servers')[0]\n .getOptionalString('url')}`;\n }\n\n async createMessage(\n prompt: string,\n selectedModel: string,\n conversation_id: string,\n ) {\n const baseUrl = await this.getBaseUrl();\n\n const response = await this.fetchApi.fetch(`${baseUrl}/v1/query`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n conversation_id:\n conversation_id === TEMP_CONVERSATION_ID\n ? undefined\n : conversation_id,\n model: selectedModel,\n provider: this.configApi\n .getConfigArray('lightspeed.servers')[0]\n .getOptionalString('id'), // Currently supports a single llm server\n query: prompt,\n }),\n });\n\n if (!response.body) {\n throw new Error('Readable stream is not supported or there is no body.');\n }\n\n if (!response.ok) {\n const body = await response.body.getReader();\n const reader = body.read();\n const decoder = new TextDecoder('utf-8');\n const text = await reader.then(({ done, value }) => {\n if (done) {\n return '';\n }\n return decoder.decode(value);\n });\n const errorMessage = JSON.parse(text);\n if (errorMessage?.error) {\n throw new Error(`failed to create message: ${errorMessage.error}`);\n }\n }\n return response.body.getReader();\n }\n\n private async fetcher(url: string) {\n const response = await this.fetchApi.fetch(url, {\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n if (!response.ok) {\n throw new Error(\n `failed to fetch data, status ${response.status}: ${response.statusText}`,\n );\n }\n return response;\n }\n\n async getAllModels() {\n const baseUrl = await this.getBaseUrl();\n const result = await this.fetcher(`${baseUrl}/v1/models`);\n\n if (!result.ok) {\n throw new Error(\n `failed to get models, status ${result.status}: ${result.statusText}`,\n );\n }\n\n const response = await result.json();\n return response?.data ? response.data : [];\n }\n\n async getConversationMessages(conversation_id: string) {\n if (conversation_id === TEMP_CONVERSATION_ID) {\n return [];\n }\n const baseUrl = await this.getBaseUrl();\n const result = await this.fetcher(\n `${baseUrl}/conversations/${encodeURIComponent(conversation_id)}`,\n );\n if (!result.ok) {\n throw new Error(\n `failed to get conversation messages, status ${result.status}: ${result.statusText}`,\n );\n }\n const response = await result.json();\n return response.chat_history ?? [];\n }\n\n async getConversations() {\n const baseUrl = await this.getBaseUrl();\n const result = await this.fetcher(`${baseUrl}/conversations`);\n\n if (!result.ok) {\n throw new Error(\n `failed to get conversation, status ${result.status}: ${result.statusText}`,\n );\n }\n\n const response = await result.json();\n return response.conversations ?? [];\n }\n\n async deleteConversation(conversation_id: string) {\n const baseUrl = await this.getBaseUrl();\n\n const response = await this.fetchApi.fetch(\n `${baseUrl}/conversations/${encodeURIComponent(conversation_id)}`,\n {\n method: 'DELETE',\n headers: {},\n },\n );\n\n if (!response.ok) {\n throw new Error(\n `failed to delete conversation, status ${response.status}: ${response.statusText}`,\n );\n }\n return { success: true };\n }\n}\n"],"names":[],"mappings":";;AA0BO,MAAM,mBAA6C,CAAA;AAAA,EACvC,SAAA;AAAA,EACA,QAAA;AAAA,EAEjB,YAAY,OAAkB,EAAA;AAC5B,IAAA,IAAA,CAAK,YAAY,OAAQ,CAAA,SAAA;AACzB,IAAA,IAAA,CAAK,WAAW,OAAQ,CAAA,QAAA;AAAA;AAC1B,EAEA,MAAM,UAAa,GAAA;AACjB,IAAA,OAAO,CAAG,EAAA,IAAA,CAAK,SAAU,CAAA,SAAA,CAAU,iBAAiB,CAAC,CAAA,eAAA,CAAA;AAAA;AACvD,EAEA,YAAe,GAAA;AAEb,IAAO,OAAA,CAAA,EAAG,IAAK,CAAA,SAAA,CACZ,cAAe,CAAA,oBAAoB,EAAE,CAAC,CAAA,CACtC,iBAAkB,CAAA,KAAK,CAAC,CAAA,CAAA;AAAA;AAC7B,EAEA,MAAM,aAAA,CACJ,MACA,EAAA,aAAA,EACA,eACA,EAAA;AACA,IAAM,MAAA,OAAA,GAAU,MAAM,IAAA,CAAK,UAAW,EAAA;AAEtC,IAAA,MAAM,WAAW,MAAM,IAAA,CAAK,SAAS,KAAM,CAAA,CAAA,EAAG,OAAO,CAAa,SAAA,CAAA,EAAA;AAAA,MAChE,MAAQ,EAAA,MAAA;AAAA,MACR,OAAS,EAAA;AAAA,QACP,cAAgB,EAAA;AAAA,OAClB;AAAA,MACA,IAAA,EAAM,KAAK,SAAU,CA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.js","sources":["../../src/api/api.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 { createApiRef } from '@backstage/core-plugin-api';\n\nimport OpenAI from 'openai';\n\nimport { BaseMessage, ConversationList } from '../types';\n\nexport type LightspeedAPI = {\n getAllModels: () => Promise<OpenAI.Models.Model[]>;\n getConversationMessages: (conversation_id: string) => Promise<BaseMessage[]>;\n
|
|
1
|
+
{"version":3,"file":"api.esm.js","sources":["../../src/api/api.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 { createApiRef } from '@backstage/core-plugin-api';\n\nimport OpenAI from 'openai';\n\nimport { BaseMessage, ConversationList } from '../types';\n\nexport type LightspeedAPI = {\n getAllModels: () => Promise<OpenAI.Models.Model[]>;\n getConversationMessages: (conversation_id: string) => Promise<BaseMessage[]>;\n createMessage: (\n prompt: string,\n selectedModel: string,\n conversation_id: string,\n ) => Promise<ReadableStreamDefaultReader>;\n deleteConversation: (\n conversation_id: string,\n ) => Promise<{ success: boolean }>;\n getConversations: () => Promise<ConversationList>;\n};\n\nexport const lightspeedApiRef = createApiRef<LightspeedAPI>({\n id: 'plugin.lightspeed.service',\n});\n"],"names":[],"mappings":";;AAoCO,MAAM,mBAAmB,YAA4B,CAAA;AAAA,EAC1D,EAAI,EAAA;AACN,CAAC;;;;"}
|
|
@@ -5,12 +5,12 @@ import { Chatbot, ChatbotDisplayMode, ChatbotHeader, ChatbotHeaderMain, ChatbotH
|
|
|
5
5
|
import ChatbotConversationHistoryNav from '@patternfly/chatbot/dist/dynamic/ChatbotConversationHistoryNav';
|
|
6
6
|
import { DropdownItem, Title } from '@patternfly/react-core';
|
|
7
7
|
import { useQueryClient } from '@tanstack/react-query';
|
|
8
|
+
import { TEMP_CONVERSATION_ID } from '../const.esm.js';
|
|
8
9
|
import '@backstage/core-plugin-api';
|
|
9
10
|
import '../api/api.esm.js';
|
|
10
11
|
import { useBackstageUserIdentity } from '../hooks/useBackstageUserIdentity.esm.js';
|
|
11
12
|
import { useConversationMessages } from '../hooks/useConversationMessages.esm.js';
|
|
12
13
|
import { useConversations } from '../hooks/useConversations.esm.js';
|
|
13
|
-
import { useCreateConversation } from '../hooks/useCreateConversation.esm.js';
|
|
14
14
|
import { useDeleteConversation } from '../hooks/useDeleteConversation.esm.js';
|
|
15
15
|
import { useIsMobile } from '../hooks/useIsMobile.esm.js';
|
|
16
16
|
import { useLastOpenedConversation } from '../hooks/useLastOpenedConversation.esm.js';
|
|
@@ -78,38 +78,37 @@ const LightspeedChat = ({
|
|
|
78
78
|
}, [lastOpenedId, isReady]);
|
|
79
79
|
const queryClient = useQueryClient();
|
|
80
80
|
const { data: conversations = [] } = useConversations();
|
|
81
|
-
const { mutateAsync: createConversation } = useCreateConversation();
|
|
82
81
|
const { mutateAsync: deleteConversation } = useDeleteConversation();
|
|
83
82
|
const { allowed: hasDeleteAccess } = useLightspeedDeletePermission();
|
|
84
83
|
React__default.useEffect(() => {
|
|
85
84
|
if (user && lastOpenedId === null && isReady) {
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
setNewChatCreated(true);
|
|
89
|
-
}).catch((e) => {
|
|
90
|
-
console.warn(e);
|
|
91
|
-
setError(e);
|
|
92
|
-
});
|
|
85
|
+
setConversationId(TEMP_CONVERSATION_ID);
|
|
86
|
+
setNewChatCreated(true);
|
|
93
87
|
}
|
|
94
|
-
}, [user, isReady, lastOpenedId, setConversationId
|
|
88
|
+
}, [user, isReady, lastOpenedId, setConversationId]);
|
|
95
89
|
React__default.useEffect(() => {
|
|
96
90
|
if (conversationId) {
|
|
97
91
|
setLastOpenedId(conversationId);
|
|
98
92
|
}
|
|
99
93
|
}, [conversationId, setLastOpenedId]);
|
|
94
|
+
const onStart = (conv_id) => {
|
|
95
|
+
setConversationId(conv_id);
|
|
96
|
+
};
|
|
100
97
|
const onComplete = (message) => {
|
|
101
98
|
setIsSendButtonDisabled(false);
|
|
102
99
|
setAnnouncement(`Message from Bot: ${message}`);
|
|
103
100
|
queryClient.invalidateQueries({
|
|
104
101
|
queryKey: ["conversations"]
|
|
105
102
|
});
|
|
103
|
+
setNewChatCreated(false);
|
|
106
104
|
};
|
|
107
105
|
const { conversationMessages, handleInputPrompt, scrollToBottomRef } = useConversationMessages(
|
|
108
106
|
conversationId,
|
|
109
107
|
userName,
|
|
110
108
|
selectedModel,
|
|
111
109
|
avatar,
|
|
112
|
-
onComplete
|
|
110
|
+
onComplete,
|
|
111
|
+
onStart
|
|
113
112
|
);
|
|
114
113
|
const [messages, setMessages] = React__default.useState(conversationMessages);
|
|
115
114
|
React__default.useEffect(() => {
|
|
@@ -118,7 +117,9 @@ const LightspeedChat = ({
|
|
|
118
117
|
}, 10);
|
|
119
118
|
}, [messages, scrollToBottomRef.current]);
|
|
120
119
|
const sendMessage = (message) => {
|
|
121
|
-
|
|
120
|
+
if (conversationId !== TEMP_CONVERSATION_ID) {
|
|
121
|
+
setNewChatCreated(false);
|
|
122
|
+
}
|
|
122
123
|
setAnnouncement(
|
|
123
124
|
`Message from User: ${prompt}. Message from Bot is loading.`
|
|
124
125
|
);
|
|
@@ -128,11 +129,10 @@ const LightspeedChat = ({
|
|
|
128
129
|
const onNewChat = React__default.useCallback(() => {
|
|
129
130
|
(async () => {
|
|
130
131
|
setMessages([]);
|
|
131
|
-
|
|
132
|
-
setConversationId(conversation_id);
|
|
132
|
+
setConversationId(TEMP_CONVERSATION_ID);
|
|
133
133
|
setNewChatCreated(true);
|
|
134
134
|
})();
|
|
135
|
-
}, [
|
|
135
|
+
}, [setConversationId, setMessages]);
|
|
136
136
|
const openDeleteModal = (conversation_id) => {
|
|
137
137
|
setTargetConversationId(conversation_id);
|
|
138
138
|
setIsDeleteModalOpen(true);
|
|
@@ -151,6 +151,7 @@ const LightspeedChat = ({
|
|
|
151
151
|
setIsDeleteModalOpen(false);
|
|
152
152
|
} catch (e) {
|
|
153
153
|
console.warn(e);
|
|
154
|
+
setError(e);
|
|
154
155
|
}
|
|
155
156
|
})();
|
|
156
157
|
}, [
|
|
@@ -213,7 +214,7 @@ const LightspeedChat = ({
|
|
|
213
214
|
const conversationFound = !!conversations.find(
|
|
214
215
|
(c) => c.conversation_id === conversationId
|
|
215
216
|
);
|
|
216
|
-
const welcomePrompts = newChatCreated || !conversationFound && conversationMessages.length === 0 ? [
|
|
217
|
+
const welcomePrompts = newChatCreated && conversationMessages.length === 0 || !conversationFound && conversationMessages.length === 0 ? [
|
|
217
218
|
{
|
|
218
219
|
title: "Topic 1",
|
|
219
220
|
message: "Helpful prompt for Topic 1",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"LightSpeedChat.esm.js","sources":["../../src/components/LightSpeedChat.tsx"],"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 { ErrorPanel } from '@backstage/core-components';\n\nimport { Box, makeStyles } from '@material-ui/core';\nimport {\n Chatbot,\n ChatbotContent,\n ChatbotDisplayMode,\n ChatbotFooter,\n ChatbotFootnote,\n ChatbotHeader,\n ChatbotHeaderMain,\n ChatbotHeaderMenu,\n ChatbotHeaderTitle,\n MessageBar,\n MessageProps,\n} from '@patternfly/chatbot';\nimport ChatbotConversationHistoryNav from '@patternfly/chatbot/dist/dynamic/ChatbotConversationHistoryNav';\nimport { DropdownItem, Title } from '@patternfly/react-core';\nimport { useQueryClient } from '@tanstack/react-query';\n\nimport {\n useBackstageUserIdentity,\n useConversationMessages,\n useConversations,\n useCreateConversation,\n useDeleteConversation,\n useIsMobile,\n useLastOpenedConversation,\n useLightspeedDeletePermission,\n} from '../hooks';\nimport { ConversationSummary } from '../types';\nimport {\n getCategorizeMessages,\n getFootnoteProps,\n} from '../utils/lightspeed-chatbox-utils';\nimport { DeleteModal } from './DeleteModal';\nimport { LightspeedChatBox } from './LightspeedChatBox';\nimport { LightspeedChatBoxHeader } from './LightspeedChatBoxHeader';\n\nconst useStyles = makeStyles(theme => ({\n body: {\n // remove default margin and padding from common elements\n '& h1, & h2, & h3, & h4, & h5, & h6, & p, & ul, & ol, & li': {\n margin: 0,\n padding: 0,\n },\n },\n header: {\n padding: `${theme.spacing(3)}px !important`,\n },\n headerMenu: {\n // align hamburger icon with title\n '& .pf-v6-c-button': {\n display: 'flex',\n alignItems: 'center',\n },\n },\n headerTitle: {\n justifyContent: 'left !important',\n },\n footer: {\n '&>.pf-chatbot__footer-container': {\n width: '95% !important',\n maxWidth: 'unset !important',\n },\n },\n}));\n\ntype LightspeedChatProps = {\n selectedModel: string;\n userName?: string;\n avatar?: string;\n profileLoading: boolean;\n handleSelectedModel: (item: string) => void;\n models: { label: string; value: string }[];\n};\n\nexport const LightspeedChat = ({\n selectedModel,\n userName,\n avatar,\n profileLoading,\n handleSelectedModel,\n models,\n}: LightspeedChatProps) => {\n const isMobile = useIsMobile();\n const classes = useStyles();\n const user = useBackstageUserIdentity();\n const [filterValue, setFilterValue] = React.useState<string>('');\n const [announcement, setAnnouncement] = React.useState<string>('');\n const [conversationId, setConversationId] = React.useState<string>('');\n const [isDrawerOpen, setIsDrawerOpen] = React.useState<boolean>(!isMobile);\n const [newChatCreated, setNewChatCreated] = React.useState<boolean>(false);\n const [isSendButtonDisabled, setIsSendButtonDisabled] =\n React.useState<boolean>(false);\n const [error, setError] = React.useState<Error | null>(null);\n const [targetConversationId, setTargetConversationId] =\n React.useState<string>('');\n const [isDeleteModalOpen, setIsDeleteModalOpen] =\n React.useState<boolean>(false);\n const { isReady, lastOpenedId, setLastOpenedId, clearLastOpenedId } =\n useLastOpenedConversation(user);\n\n // Sync conversationId with lastOpenedId whenever lastOpenedId changes\n React.useEffect(() => {\n if (isReady && lastOpenedId !== null) {\n setConversationId(lastOpenedId);\n }\n }, [lastOpenedId, isReady]);\n\n const queryClient = useQueryClient();\n\n const { data: conversations = [] } = useConversations();\n const { mutateAsync: createConversation } = useCreateConversation();\n const { mutateAsync: deleteConversation } = useDeleteConversation();\n const { allowed: hasDeleteAccess } = useLightspeedDeletePermission();\n\n React.useEffect(() => {\n if (user && lastOpenedId === null && isReady) {\n createConversation()\n .then(({ conversation_id }) => {\n setConversationId(conversation_id);\n setNewChatCreated(true);\n })\n .catch(e => {\n // eslint-disable-next-line\n console.warn(e);\n setError(e);\n });\n }\n }, [user, isReady, lastOpenedId, setConversationId, createConversation]);\n\n React.useEffect(() => {\n // Update last opened conversation whenever `conversationId` changes\n if (conversationId) {\n setLastOpenedId(conversationId);\n }\n }, [conversationId, setLastOpenedId]);\n\n const onComplete = (message: string) => {\n setIsSendButtonDisabled(false);\n setAnnouncement(`Message from Bot: ${message}`);\n queryClient.invalidateQueries({\n queryKey: ['conversations'],\n });\n };\n\n const { conversationMessages, handleInputPrompt, scrollToBottomRef } =\n useConversationMessages(\n conversationId,\n userName,\n selectedModel,\n avatar,\n onComplete,\n );\n\n const [messages, setMessages] =\n React.useState<MessageProps[]>(conversationMessages);\n\n // Auto-scrolls to the latest message\n React.useEffect(() => {\n setTimeout(() => {\n scrollToBottomRef.current?.scrollIntoView({ behavior: 'auto' });\n }, 10);\n // eslint-disable-next-line\n }, [messages, scrollToBottomRef.current]);\n\n const sendMessage = (message: string | number) => {\n setNewChatCreated(false);\n setAnnouncement(\n `Message from User: ${prompt}. Message from Bot is loading.`,\n );\n handleInputPrompt(message.toString());\n setIsSendButtonDisabled(true);\n };\n\n const onNewChat = React.useCallback(() => {\n (async () => {\n setMessages([]);\n const { conversation_id } = await createConversation();\n setConversationId(conversation_id);\n setNewChatCreated(true);\n })();\n }, [createConversation, setConversationId, setMessages]);\n\n const openDeleteModal = (conversation_id: string) => {\n setTargetConversationId(conversation_id);\n setIsDeleteModalOpen(true);\n };\n\n const handleDeleteConversation = React.useCallback(() => {\n (async () => {\n try {\n await deleteConversation({\n conversation_id: targetConversationId,\n invalidateCache: false,\n });\n if (targetConversationId === lastOpenedId) {\n onNewChat();\n clearLastOpenedId();\n }\n setIsDeleteModalOpen(false);\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(e);\n }\n })();\n }, [\n deleteConversation,\n clearLastOpenedId,\n lastOpenedId,\n onNewChat,\n targetConversationId,\n ]);\n\n const additionalMessageProps = React.useCallback(\n (conversationSummary: ConversationSummary) => ({\n menuItems: (\n <DropdownItem\n isDisabled={!hasDeleteAccess}\n onClick={() => openDeleteModal(conversationSummary.conversation_id)}\n >\n Delete\n </DropdownItem>\n ),\n }),\n [hasDeleteAccess],\n );\n const categorizedMessages = getCategorizeMessages(\n conversations,\n additionalMessageProps,\n );\n\n const filterConversations = React.useCallback(\n (targetValue: string) => {\n const filteredConversations = Object.entries(categorizedMessages).reduce(\n (acc, [key, items]) => {\n const filteredItems = items.filter(item =>\n item.text\n .toLocaleLowerCase('en-US')\n .includes(targetValue.toLocaleLowerCase('en-US')),\n );\n if (filteredItems.length > 0) {\n acc[key] = filteredItems;\n }\n return acc;\n },\n {} as any,\n );\n return filteredConversations;\n },\n [categorizedMessages],\n );\n\n React.useEffect(() => {\n setMessages(conversationMessages);\n }, [conversationMessages]);\n\n const onSelectActiveItem = React.useCallback(\n (\n _: React.MouseEvent | undefined,\n selectedItem: string | number | undefined,\n ) => {\n setNewChatCreated(false);\n setConversationId((c_id: string) => {\n if (c_id !== selectedItem) {\n return String(selectedItem);\n }\n return c_id;\n });\n },\n [setConversationId],\n );\n\n const conversationFound = !!conversations.find(\n c => c.conversation_id === conversationId,\n );\n\n const welcomePrompts =\n newChatCreated || (!conversationFound && conversationMessages.length === 0)\n ? [\n {\n title: 'Topic 1',\n message: 'Helpful prompt for Topic 1',\n onClick: () => sendMessage('Helpful prompt for Topic 1'),\n },\n {\n title: 'Topic 2',\n message: 'Helpful prompt for Topic 2',\n onClick: () => sendMessage('Helpful prompt for Topic 2'),\n },\n ]\n : [];\n\n const handleFilter = React.useCallback((value: string) => {\n setFilterValue(value);\n }, []);\n\n const onDrawerToggle = React.useCallback(() => {\n setIsDrawerOpen(isOpen => !isOpen);\n }, []);\n\n if (error) {\n return (\n <Box padding={1}>\n <ErrorPanel error={error} />\n </Box>\n );\n }\n\n return (\n <>\n {isDeleteModalOpen && (\n <DeleteModal\n isOpen={isDeleteModalOpen}\n onClose={() => setIsDeleteModalOpen(false)}\n onConfirm={handleDeleteConversation}\n />\n )}\n <Chatbot\n displayMode={ChatbotDisplayMode.embedded}\n className={classes.body}\n >\n <ChatbotHeader className={classes.header}>\n <ChatbotHeaderMain>\n <ChatbotHeaderMenu\n aria-expanded={isDrawerOpen}\n onMenuToggle={() => setIsDrawerOpen(!isDrawerOpen)}\n className={classes.headerMenu}\n />\n <ChatbotHeaderTitle className={classes.headerTitle}>\n <Title headingLevel=\"h1\" size=\"3xl\">\n Developer Hub Lightspeed\n </Title>\n </ChatbotHeaderTitle>\n </ChatbotHeaderMain>\n\n <LightspeedChatBoxHeader\n selectedModel={selectedModel}\n handleSelectedModel={item => handleSelectedModel(item)}\n models={models}\n />\n </ChatbotHeader>\n <ChatbotConversationHistoryNav\n drawerPanelContentProps={{ isResizable: true, minSize: '200px' }}\n reverseButtonOrder\n displayMode={ChatbotDisplayMode.embedded}\n onDrawerToggle={onDrawerToggle}\n isDrawerOpen={isDrawerOpen}\n setIsDrawerOpen={setIsDrawerOpen}\n activeItemId={conversationId}\n onSelectActiveItem={onSelectActiveItem}\n conversations={filterConversations(filterValue)}\n onNewChat={newChatCreated ? undefined : onNewChat}\n handleTextInputChange={handleFilter}\n drawerContent={\n <>\n <ChatbotContent>\n <LightspeedChatBox\n userName={userName}\n messages={messages}\n profileLoading={profileLoading}\n announcement={announcement}\n ref={scrollToBottomRef}\n welcomePrompts={welcomePrompts}\n />\n </ChatbotContent>\n <ChatbotFooter className={classes.footer}>\n <MessageBar\n onSendMessage={sendMessage}\n isSendButtonDisabled={isSendButtonDisabled}\n hasAttachButton={false}\n hasMicrophoneButton\n />\n <ChatbotFootnote {...getFootnoteProps()} />\n </ChatbotFooter>\n </>\n }\n />\n </Chatbot>\n </>\n );\n};\n"],"names":["React"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyDA,MAAM,SAAA,GAAY,WAAW,CAAU,KAAA,MAAA;AAAA,EACrC,IAAM,EAAA;AAAA;AAAA,IAEJ,2DAA6D,EAAA;AAAA,MAC3D,MAAQ,EAAA,CAAA;AAAA,MACR,OAAS,EAAA;AAAA;AACX,GACF;AAAA,EACA,MAAQ,EAAA;AAAA,IACN,OAAS,EAAA,CAAA,EAAG,KAAM,CAAA,OAAA,CAAQ,CAAC,CAAC,CAAA,aAAA;AAAA,GAC9B;AAAA,EACA,UAAY,EAAA;AAAA;AAAA,IAEV,mBAAqB,EAAA;AAAA,MACnB,OAAS,EAAA,MAAA;AAAA,MACT,UAAY,EAAA;AAAA;AACd,GACF;AAAA,EACA,WAAa,EAAA;AAAA,IACX,cAAgB,EAAA;AAAA,GAClB;AAAA,EACA,MAAQ,EAAA;AA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AA,YACC,QAAA;AAAA,YACA,QAAA;AAAA,YACA,cAAA;AAAA,YACA,YAAA;AAAA,YACA,GAAK,EAAA,iBAAA;AAAA,YACL;AAAA;AAAA,SAEJ,CACA,kBAAAA,cAAA,CAAA,aAAA,CAAC,aAAc,EAAA,EAAA,SAAA,EAAW,QAAQ,MAChC,EAAA,kBAAAA,cAAA,CAAA,aAAA;AAAA,UAAC,UAAA;AAAA,UAAA;AAAA,YACC,aAAe,EAAA,WAAA;AAAA,YACf,oBAAA;AAAA,YACA,eAAiB,EAAA,KAAA;AAAA,YACjB,mBAAmB,EAAA;AAAA;AAAA,2BAEpBA,cAAA,CAAA,aAAA,CAAA,eAAA,EAAA,EAAiB,GAAG,gBAAiB,EAAA,EAAG,CAC3C,CACF;AAAA;AAAA;AAEJ,GAEJ,CAAA;AAEJ;;;;"}
|
|
1
|
+
{"version":3,"file":"LightSpeedChat.esm.js","sources":["../../src/components/LightSpeedChat.tsx"],"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 { ErrorPanel } from '@backstage/core-components';\n\nimport { Box, makeStyles } from '@material-ui/core';\nimport {\n Chatbot,\n ChatbotContent,\n ChatbotDisplayMode,\n ChatbotFooter,\n ChatbotFootnote,\n ChatbotHeader,\n ChatbotHeaderMain,\n ChatbotHeaderMenu,\n ChatbotHeaderTitle,\n MessageBar,\n MessageProps,\n} from '@patternfly/chatbot';\nimport ChatbotConversationHistoryNav from '@patternfly/chatbot/dist/dynamic/ChatbotConversationHistoryNav';\nimport { DropdownItem, Title } from '@patternfly/react-core';\nimport { useQueryClient } from '@tanstack/react-query';\n\nimport { TEMP_CONVERSATION_ID } from '../const';\nimport {\n useBackstageUserIdentity,\n useConversationMessages,\n useConversations,\n useDeleteConversation,\n useIsMobile,\n useLastOpenedConversation,\n useLightspeedDeletePermission,\n} from '../hooks';\nimport { ConversationSummary } from '../types';\nimport {\n getCategorizeMessages,\n getFootnoteProps,\n} from '../utils/lightspeed-chatbox-utils';\nimport { DeleteModal } from './DeleteModal';\nimport { LightspeedChatBox } from './LightspeedChatBox';\nimport { LightspeedChatBoxHeader } from './LightspeedChatBoxHeader';\n\nconst useStyles = makeStyles(theme => ({\n body: {\n // remove default margin and padding from common elements\n '& h1, & h2, & h3, & h4, & h5, & h6, & p, & ul, & ol, & li': {\n margin: 0,\n padding: 0,\n },\n },\n header: {\n padding: `${theme.spacing(3)}px !important`,\n },\n headerMenu: {\n // align hamburger icon with title\n '& .pf-v6-c-button': {\n display: 'flex',\n alignItems: 'center',\n },\n },\n headerTitle: {\n justifyContent: 'left !important',\n },\n footer: {\n '&>.pf-chatbot__footer-container': {\n width: '95% !important',\n maxWidth: 'unset !important',\n },\n },\n}));\n\ntype LightspeedChatProps = {\n selectedModel: string;\n userName?: string;\n avatar?: string;\n profileLoading: boolean;\n handleSelectedModel: (item: string) => void;\n models: { label: string; value: string }[];\n};\n\nexport const LightspeedChat = ({\n selectedModel,\n userName,\n avatar,\n profileLoading,\n handleSelectedModel,\n models,\n}: LightspeedChatProps) => {\n const isMobile = useIsMobile();\n const classes = useStyles();\n const user = useBackstageUserIdentity();\n const [filterValue, setFilterValue] = React.useState<string>('');\n const [announcement, setAnnouncement] = React.useState<string>('');\n const [conversationId, setConversationId] = React.useState<string>('');\n const [isDrawerOpen, setIsDrawerOpen] = React.useState<boolean>(!isMobile);\n const [newChatCreated, setNewChatCreated] = React.useState<boolean>(false);\n const [isSendButtonDisabled, setIsSendButtonDisabled] =\n React.useState<boolean>(false);\n const [error, setError] = React.useState<Error | null>(null);\n const [targetConversationId, setTargetConversationId] =\n React.useState<string>('');\n const [isDeleteModalOpen, setIsDeleteModalOpen] =\n React.useState<boolean>(false);\n const { isReady, lastOpenedId, setLastOpenedId, clearLastOpenedId } =\n useLastOpenedConversation(user);\n\n // Sync conversationId with lastOpenedId whenever lastOpenedId changes\n React.useEffect(() => {\n if (isReady && lastOpenedId !== null) {\n setConversationId(lastOpenedId);\n }\n }, [lastOpenedId, isReady]);\n\n const queryClient = useQueryClient();\n\n const { data: conversations = [] } = useConversations();\n const { mutateAsync: deleteConversation } = useDeleteConversation();\n const { allowed: hasDeleteAccess } = useLightspeedDeletePermission();\n\n React.useEffect(() => {\n if (user && lastOpenedId === null && isReady) {\n setConversationId(TEMP_CONVERSATION_ID);\n setNewChatCreated(true);\n }\n }, [user, isReady, lastOpenedId, setConversationId]);\n\n React.useEffect(() => {\n // Update last opened conversation whenever `conversationId` changes\n if (conversationId) {\n setLastOpenedId(conversationId);\n }\n }, [conversationId, setLastOpenedId]);\n\n const onStart = (conv_id: string) => {\n setConversationId(conv_id);\n };\n\n const onComplete = (message: string) => {\n setIsSendButtonDisabled(false);\n setAnnouncement(`Message from Bot: ${message}`);\n queryClient.invalidateQueries({\n queryKey: ['conversations'],\n });\n setNewChatCreated(false);\n };\n\n const { conversationMessages, handleInputPrompt, scrollToBottomRef } =\n useConversationMessages(\n conversationId,\n userName,\n selectedModel,\n avatar,\n onComplete,\n onStart,\n );\n\n const [messages, setMessages] =\n React.useState<MessageProps[]>(conversationMessages);\n\n // Auto-scrolls to the latest message\n React.useEffect(() => {\n setTimeout(() => {\n scrollToBottomRef.current?.scrollIntoView({ behavior: 'auto' });\n }, 10);\n // eslint-disable-next-line\n }, [messages, scrollToBottomRef.current]);\n\n const sendMessage = (message: string | number) => {\n if (conversationId !== TEMP_CONVERSATION_ID) {\n setNewChatCreated(false);\n }\n setAnnouncement(\n `Message from User: ${prompt}. Message from Bot is loading.`,\n );\n handleInputPrompt(message.toString());\n setIsSendButtonDisabled(true);\n };\n\n const onNewChat = React.useCallback(() => {\n (async () => {\n setMessages([]);\n setConversationId(TEMP_CONVERSATION_ID);\n setNewChatCreated(true);\n })();\n }, [setConversationId, setMessages]);\n\n const openDeleteModal = (conversation_id: string) => {\n setTargetConversationId(conversation_id);\n setIsDeleteModalOpen(true);\n };\n\n const handleDeleteConversation = React.useCallback(() => {\n (async () => {\n try {\n await deleteConversation({\n conversation_id: targetConversationId,\n invalidateCache: false,\n });\n if (targetConversationId === lastOpenedId) {\n onNewChat();\n clearLastOpenedId();\n }\n setIsDeleteModalOpen(false);\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(e);\n setError(e);\n }\n })();\n }, [\n deleteConversation,\n clearLastOpenedId,\n lastOpenedId,\n onNewChat,\n targetConversationId,\n ]);\n\n const additionalMessageProps = React.useCallback(\n (conversationSummary: ConversationSummary) => ({\n menuItems: (\n <DropdownItem\n isDisabled={!hasDeleteAccess}\n onClick={() => openDeleteModal(conversationSummary.conversation_id)}\n >\n Delete\n </DropdownItem>\n ),\n }),\n [hasDeleteAccess],\n );\n const categorizedMessages = getCategorizeMessages(\n conversations,\n additionalMessageProps,\n );\n\n const filterConversations = React.useCallback(\n (targetValue: string) => {\n const filteredConversations = Object.entries(categorizedMessages).reduce(\n (acc, [key, items]) => {\n const filteredItems = items.filter(item =>\n item.text\n .toLocaleLowerCase('en-US')\n .includes(targetValue.toLocaleLowerCase('en-US')),\n );\n if (filteredItems.length > 0) {\n acc[key] = filteredItems;\n }\n return acc;\n },\n {} as any,\n );\n return filteredConversations;\n },\n [categorizedMessages],\n );\n\n React.useEffect(() => {\n setMessages(conversationMessages);\n }, [conversationMessages]);\n\n const onSelectActiveItem = React.useCallback(\n (\n _: React.MouseEvent | undefined,\n selectedItem: string | number | undefined,\n ) => {\n setNewChatCreated(false);\n setConversationId((c_id: string) => {\n if (c_id !== selectedItem) {\n return String(selectedItem);\n }\n return c_id;\n });\n },\n [setConversationId],\n );\n\n const conversationFound = !!conversations.find(\n c => c.conversation_id === conversationId,\n );\n\n const welcomePrompts =\n (newChatCreated && conversationMessages.length === 0) ||\n (!conversationFound && conversationMessages.length === 0)\n ? [\n {\n title: 'Topic 1',\n message: 'Helpful prompt for Topic 1',\n onClick: () => sendMessage('Helpful prompt for Topic 1'),\n },\n {\n title: 'Topic 2',\n message: 'Helpful prompt for Topic 2',\n onClick: () => sendMessage('Helpful prompt for Topic 2'),\n },\n ]\n : [];\n\n const handleFilter = React.useCallback((value: string) => {\n setFilterValue(value);\n }, []);\n\n const onDrawerToggle = React.useCallback(() => {\n setIsDrawerOpen(isOpen => !isOpen);\n }, []);\n\n if (error) {\n return (\n <Box padding={1}>\n <ErrorPanel error={error} />\n </Box>\n );\n }\n\n return (\n <>\n {isDeleteModalOpen && (\n <DeleteModal\n isOpen={isDeleteModalOpen}\n onClose={() => setIsDeleteModalOpen(false)}\n onConfirm={handleDeleteConversation}\n />\n )}\n <Chatbot\n displayMode={ChatbotDisplayMode.embedded}\n className={classes.body}\n >\n <ChatbotHeader className={classes.header}>\n <ChatbotHeaderMain>\n <ChatbotHeaderMenu\n aria-expanded={isDrawerOpen}\n onMenuToggle={() => setIsDrawerOpen(!isDrawerOpen)}\n className={classes.headerMenu}\n />\n <ChatbotHeaderTitle className={classes.headerTitle}>\n <Title headingLevel=\"h1\" size=\"3xl\">\n Developer Hub Lightspeed\n </Title>\n </ChatbotHeaderTitle>\n </ChatbotHeaderMain>\n\n <LightspeedChatBoxHeader\n selectedModel={selectedModel}\n handleSelectedModel={item => handleSelectedModel(item)}\n models={models}\n />\n </ChatbotHeader>\n <ChatbotConversationHistoryNav\n drawerPanelContentProps={{ isResizable: true, minSize: '200px' }}\n reverseButtonOrder\n displayMode={ChatbotDisplayMode.embedded}\n onDrawerToggle={onDrawerToggle}\n isDrawerOpen={isDrawerOpen}\n setIsDrawerOpen={setIsDrawerOpen}\n activeItemId={conversationId}\n onSelectActiveItem={onSelectActiveItem}\n conversations={filterConversations(filterValue)}\n onNewChat={newChatCreated ? undefined : onNewChat}\n handleTextInputChange={handleFilter}\n drawerContent={\n <>\n <ChatbotContent>\n <LightspeedChatBox\n userName={userName}\n messages={messages}\n profileLoading={profileLoading}\n announcement={announcement}\n ref={scrollToBottomRef}\n welcomePrompts={welcomePrompts}\n />\n </ChatbotContent>\n <ChatbotFooter className={classes.footer}>\n <MessageBar\n onSendMessage={sendMessage}\n isSendButtonDisabled={isSendButtonDisabled}\n hasAttachButton={false}\n hasMicrophoneButton\n />\n <ChatbotFootnote {...getFootnoteProps()} />\n </ChatbotFooter>\n </>\n }\n />\n </Chatbot>\n </>\n );\n};\n"],"names":["React"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyDA,MAAM,SAAA,GAAY,WAAW,CAAU,KAAA,MAAA;AAAA,EACrC,IAAM,EAAA;AAAA;AAAA,IAEJ,2DAA6D,EAAA;AAAA,MAC3D,MAAQ,EAAA,CAAA;AAAA,MACR,OAAS,EAAA;AAAA;AACX,GACF;AAAA,EACA,MAAQ,EAAA;AAAA,IACN,OAAS,EAAA,CAAA,EAAG,KAAM,CAAA,OAAA,CAAQ,CAAC,CAAC,CAAA,aAAA;AAAA,GAC9B;AAAA,EACA,UAAY,EAAA;AAAA;AAAA,IAEV,mBAAqB,EAAA;AAAA,MACnB,OAAS,EAAA,MAAA;AAAA,MACT,UAAY,EAAA;AAAA;AACd,GACF;AAAA,EACA,WAAa,EAAA;AAAA,IACX,cAAgB,EAAA;AAAA,GAClB;AAAA,EACA,MAAQ,EAAA;AAAA,IACN,iCAAmC,EAAA;AAAA,MACjC,KAAO,EAAA,gBAAA;AAAA,MACP,QAAU,EAAA;AAAA;AACZ;AAEJ,CAAE,CAAA,CAAA;AAWK,MAAM,iBAAiB,CAAC;AAAA,EAC7B,aAAA;AAAA,EACA,QAAA;AAAA,EACA,MAAA;AAAA,EACA,cAAA;AAAA,EACA,mBAAA;AAAA,EACA;AACF,CAA2B,KAAA;AACzB,EAAA,MAAM,WAAW,WAAY,EAAA;AAC7B,EAAA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A,CAAA,aAAA,CAAA,eAAA,EAAA,EAAiB,GAAG,gBAAiB,EAAA,EAAG,CAC3C,CACF;AAAA;AAAA;AAEJ,GAEJ,CAAA;AAEJ;;;;"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"const.esm.js","sources":["../src/const.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 */\nexport const TEMP_CONVERSATION_ID = 'temp-conversation-id';\n"],"names":[],"mappings":"AAeO,MAAM,oBAAuB,GAAA;;;;"}
|
|
@@ -2,8 +2,9 @@ import React__default from 'react';
|
|
|
2
2
|
import { useApi } from '@backstage/core-plugin-api';
|
|
3
3
|
import { useQuery } from '@tanstack/react-query';
|
|
4
4
|
import { lightspeedApiRef } from '../api/api.esm.js';
|
|
5
|
+
import { TEMP_CONVERSATION_ID } from '../const.esm.js';
|
|
5
6
|
import logo from '../images/logo.svg';
|
|
6
|
-
import { getMessageData, createUserMessage, createBotMessage, getTimestamp
|
|
7
|
+
import { getMessageData, createUserMessage, createBotMessage, getTimestamp } from '../utils/lightspeed-chatbox-utils.esm.js';
|
|
7
8
|
import { useCreateConversationMessage } from './useCreateCoversationMessage.esm.js';
|
|
8
9
|
|
|
9
10
|
const useFetchConversationMessages = (currentConversation) => {
|
|
@@ -18,7 +19,7 @@ const useFetchConversationMessages = (currentConversation) => {
|
|
|
18
19
|
});
|
|
19
20
|
};
|
|
20
21
|
const defaultAvatar = "https://img.freepik.com/premium-photo/graphic-designer-digital-avatar-generative-ai_934475-9292.jpg";
|
|
21
|
-
const useConversationMessages = (conversationId, userName, selectedModel, avatar = defaultAvatar, onComplete) => {
|
|
22
|
+
const useConversationMessages = (conversationId, userName, selectedModel, avatar = defaultAvatar, onComplete, onStart) => {
|
|
22
23
|
const { mutateAsync: createMessage } = useCreateConversationMessage();
|
|
23
24
|
const scrollToBottomRef = React__default.useRef(null);
|
|
24
25
|
const [currentConversation, setCurrentConversation] = React__default.useState(conversationId);
|
|
@@ -31,8 +32,12 @@ const useConversationMessages = (conversationId, userName, selectedModel, avatar
|
|
|
31
32
|
React__default.useEffect(() => {
|
|
32
33
|
if (currentConversation !== conversationId) {
|
|
33
34
|
setCurrentConversation(conversationId);
|
|
34
|
-
setConversations({
|
|
35
|
-
[conversationId]
|
|
35
|
+
setConversations((prev) => {
|
|
36
|
+
if (prev[conversationId]) return prev;
|
|
37
|
+
return {
|
|
38
|
+
...prev,
|
|
39
|
+
[conversationId]: []
|
|
40
|
+
};
|
|
36
41
|
});
|
|
37
42
|
}
|
|
38
43
|
}, [currentConversation, conversationId]);
|
|
@@ -88,6 +93,7 @@ const useConversationMessages = (conversationId, userName, selectedModel, avatar
|
|
|
88
93
|
]);
|
|
89
94
|
const handleInputPrompt = React__default.useCallback(
|
|
90
95
|
async (prompt) => {
|
|
96
|
+
let newConversationId = "";
|
|
91
97
|
const conversationTuple = [
|
|
92
98
|
createUserMessage({
|
|
93
99
|
avatar,
|
|
@@ -120,6 +126,7 @@ const useConversationMessages = (conversationId, userName, selectedModel, avatar
|
|
|
120
126
|
scrollToBottomRef.current?.scrollIntoView({ behavior: "auto" });
|
|
121
127
|
}, 0);
|
|
122
128
|
const finalMessages = [];
|
|
129
|
+
let buffer = "";
|
|
123
130
|
try {
|
|
124
131
|
const reader = await createMessage({
|
|
125
132
|
prompt,
|
|
@@ -129,51 +136,59 @@ const useConversationMessages = (conversationId, userName, selectedModel, avatar
|
|
|
129
136
|
const decoder = new TextDecoder("utf-8");
|
|
130
137
|
const keepGoing = true;
|
|
131
138
|
while (keepGoing) {
|
|
132
|
-
const {
|
|
139
|
+
const { value, done } = await reader.read();
|
|
133
140
|
if (done) break;
|
|
134
|
-
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
141
|
+
buffer += decoder.decode(value, { stream: true });
|
|
142
|
+
const parts = buffer.split("\n\n");
|
|
143
|
+
buffer = parts.pop();
|
|
144
|
+
for (const part of parts) {
|
|
145
|
+
const lines = part.split("\n").filter((line) => line.startsWith("data:"));
|
|
146
|
+
const jsonString = lines.map((line) => line.trim().slice(5).trim()).join("");
|
|
139
147
|
try {
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
const
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
content:
|
|
153
|
-
timestamp: getTimestamp(Date.now())
|
|
154
|
-
}) : { ...conversation[lastMessageIndex] };
|
|
155
|
-
lastMessage.isLoading = false;
|
|
156
|
-
lastMessage.content += content;
|
|
157
|
-
lastMessage.name = jsonData?.response?.kwargs?.response_metadata?.model;
|
|
158
|
-
lastMessage.timestamp = getTimestamp(
|
|
159
|
-
jsonData?.response?.kwargs?.response_metadata?.created_at || Date.now()
|
|
160
|
-
);
|
|
161
|
-
const updatedConversation = [
|
|
162
|
-
...conversation.slice(0, lastMessageIndex),
|
|
163
|
-
lastMessage
|
|
148
|
+
const { event, data } = JSON.parse(jsonString);
|
|
149
|
+
if (event === "start") {
|
|
150
|
+
if (currentConversation === TEMP_CONVERSATION_ID) {
|
|
151
|
+
newConversationId = data?.conversation_id;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
if (event === "token") {
|
|
155
|
+
const content = data?.token || "";
|
|
156
|
+
finalMessages.push(content);
|
|
157
|
+
const [humanMessage, aiMessage] = streamingConversations.current[currentConversation];
|
|
158
|
+
streamingConversations.current[currentConversation] = [
|
|
159
|
+
humanMessage,
|
|
160
|
+
{ ...aiMessage, content: aiMessage.content + content }
|
|
164
161
|
];
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
162
|
+
setConversations((prevConversations) => {
|
|
163
|
+
const conversation = prevConversations[currentConversation] ?? [];
|
|
164
|
+
const lastMessageIndex = conversation.length - 1;
|
|
165
|
+
const lastMessage = conversation.length === 0 ? createBotMessage({
|
|
166
|
+
content: "",
|
|
167
|
+
timestamp: getTimestamp(Date.now())
|
|
168
|
+
}) : { ...conversation[lastMessageIndex] };
|
|
169
|
+
lastMessage.isLoading = false;
|
|
170
|
+
lastMessage.content += content;
|
|
171
|
+
lastMessage.name = data?.response_metadata?.model || selectedModel;
|
|
172
|
+
lastMessage.timestamp = getTimestamp(
|
|
173
|
+
data?.response_metadata?.created_at || Date.now()
|
|
174
|
+
);
|
|
175
|
+
const updatedConversation = [
|
|
176
|
+
...conversation.slice(0, lastMessageIndex),
|
|
177
|
+
lastMessage
|
|
178
|
+
];
|
|
179
|
+
return {
|
|
180
|
+
...prevConversations,
|
|
181
|
+
[currentConversation]: updatedConversation
|
|
182
|
+
};
|
|
183
|
+
});
|
|
184
|
+
}
|
|
170
185
|
} catch (error) {
|
|
171
186
|
console.warn("Error parsing JSON:", error);
|
|
172
187
|
if (typeof onComplete === "function") {
|
|
173
188
|
onComplete("Invalid JSON received");
|
|
174
189
|
}
|
|
175
190
|
}
|
|
176
|
-
}
|
|
191
|
+
}
|
|
177
192
|
}
|
|
178
193
|
} catch (e) {
|
|
179
194
|
setConversations((prevConversations) => {
|
|
@@ -185,6 +200,9 @@ const useConversationMessages = (conversationId, userName, selectedModel, avatar
|
|
|
185
200
|
}) : { ...conversation[lastMessageIndex] };
|
|
186
201
|
lastMessage.isLoading = false;
|
|
187
202
|
lastMessage.content += e;
|
|
203
|
+
lastMessage.error = {
|
|
204
|
+
title: e.message
|
|
205
|
+
};
|
|
188
206
|
lastMessage.timestamp = getTimestamp(Date.now());
|
|
189
207
|
const updatedConversation = [
|
|
190
208
|
...conversation.slice(0, lastMessageIndex),
|
|
@@ -193,7 +211,7 @@ const useConversationMessages = (conversationId, userName, selectedModel, avatar
|
|
|
193
211
|
finalMessages.push(`${e}`);
|
|
194
212
|
return {
|
|
195
213
|
...prevConversations,
|
|
196
|
-
[currentConversation]: updatedConversation
|
|
214
|
+
[newConversationId.length > 0 ? newConversationId : currentConversation]: updatedConversation
|
|
197
215
|
};
|
|
198
216
|
});
|
|
199
217
|
}
|
|
@@ -201,11 +219,25 @@ const useConversationMessages = (conversationId, userName, selectedModel, avatar
|
|
|
201
219
|
if (typeof onComplete === "function") {
|
|
202
220
|
onComplete(finalMessages.join(""));
|
|
203
221
|
}
|
|
222
|
+
if (currentConversation === TEMP_CONVERSATION_ID && newConversationId) {
|
|
223
|
+
setConversations((prevConversations) => {
|
|
224
|
+
return {
|
|
225
|
+
...prevConversations,
|
|
226
|
+
[newConversationId]: prevConversations[TEMP_CONVERSATION_ID]
|
|
227
|
+
};
|
|
228
|
+
});
|
|
229
|
+
onStart?.(newConversationId);
|
|
230
|
+
setConversations((prev) => {
|
|
231
|
+
const { temp, ...rest } = prev;
|
|
232
|
+
return rest;
|
|
233
|
+
});
|
|
234
|
+
}
|
|
204
235
|
},
|
|
205
236
|
[
|
|
206
237
|
avatar,
|
|
207
238
|
userName,
|
|
208
239
|
onComplete,
|
|
240
|
+
onStart,
|
|
209
241
|
selectedModel,
|
|
210
242
|
createMessage,
|
|
211
243
|
currentConversation
|
|
@@ -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 logo from '../images/logo.svg';\nimport {\n createBotMessage,\n createUserMessage,\n getMessageData,\n getTimestamp,\n splitJsonStrings,\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) => {\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({\n [conversationId]: [],\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 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\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 while (keepGoing) {\n const { done, value } = await reader.read();\n if (done) break;\n\n const chunk = decoder.decode(value, { stream: true });\n\n const data = splitJsonStrings(chunk) ?? [];\n data?.forEach(line => {\n const trimmedLine = line.trim();\n // Ignore empty lines\n if (!trimmedLine) return;\n try {\n const jsonData = JSON.parse(line);\n const content = jsonData?.response?.kwargs?.content || '';\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 jsonData?.response?.kwargs?.response_metadata?.model;\n lastMessage.timestamp = getTimestamp(\n jsonData?.response?.kwargs?.response_metadata?.created_at ||\n 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 } 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.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 [currentConversation]: updatedConversation,\n };\n });\n }\n // reset current streaming\n streamingConversations.current[currentConversation] = [];\n if (typeof onComplete === 'function') {\n onComplete(finalMessages.join(''));\n }\n },\n\n [\n avatar,\n userName,\n onComplete,\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":";;;;;;;;AAmCa,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;AASK,MAAM,0BAA0B,CACrC,cAAA,EACA,UACA,aACA,EAAA,MAAA,GAAiB,eACjB,UACG,KAAA;AACH,EAAA,MAAM,EAAE,WAAA,EAAa,aAAc,EAAA,GAAI,4BAA6B,EAAA;AACpE,EAAM,MAAA,iBAAA,GAAoBA,cAAM,CAAA,MAAA,CAAuB,IAAI,CAAA;AAE3D,EAAA,MAAM,CAAC,mBAAqB,EAAA,sBAAsB,CAChD,GAAAA,cAAA,CAAM,SAAS,cAAc,CAAA;AAC/B,EAAA,MAAM,CAAC,aAAA,EAAe,gBAAgB,CAAA,GAAIA,eAAM,QAAwB,CAAA;AAAA,IACtE,CAAC,mBAAmB,GAAG;AAAC,GACzB,CAAA;AACD,EAAM,MAAA,sBAAA,GAAyBA,eAAM,MAAsB,CAAA;AAAA,IACzD,CAAC,mBAAmB,GAAG;AAAC,GAC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AW,UAAA,CAAA,aAAA,CAAc,IAAK,CAAA,EAAE,CAAC,CAAA;AAAA;AACnC,KACF;AAAA,IAEA;AAAA,MACE,MAAA;AAAA,MACA,QAAA;AAAA,MACA,UAAA;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;;;;"}
|
|
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 };\n};\n"],"names":["React"],"mappings":";;;;;;;;;AAmCa,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,CAAuB,IAAI,CAAA;AAE3D,EAAA,MAAM,CAAC,mBAAqB,EAAA,sBAAsB,CAChD,GAAAA,cAAA,CAAM,SAAS,cAAc,CAAA;AAC/B,EAAA,MAAM,CAAC,aAAA,EAAe,gBAAgB,CAAA,GAAIA,eAAM,QAAwB,CAAA;AAAA,IACtE,CAAC,mBAAmB,GAAG;AAAC,GACzB,CAAA;AACD,EAAM,MAAA,sBAAA,GAAyBA,eAAM,MAAsB,CAAA;AAAA,IACzD,CAAC,mBAAm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AAA;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;;;;"}
|
|
@@ -39,34 +39,22 @@ const getTimestamp = (unix_timestamp) => {
|
|
|
39
39
|
const time = `${date}/${month}/${year}, ${hour}:${min}:${sec}`;
|
|
40
40
|
return time;
|
|
41
41
|
};
|
|
42
|
-
const splitJsonStrings = (jsonString) => {
|
|
43
|
-
const chunks = jsonString.split("}{");
|
|
44
|
-
if (chunks.length <= 1) {
|
|
45
|
-
return [jsonString];
|
|
46
|
-
}
|
|
47
|
-
return chunks.map((chunk, index, arr) => {
|
|
48
|
-
if (index === 0) {
|
|
49
|
-
return `${chunk}}`;
|
|
50
|
-
} else if (index === arr.length - 1) {
|
|
51
|
-
return `{${chunk}`;
|
|
52
|
-
}
|
|
53
|
-
return `{${chunk}}`;
|
|
54
|
-
});
|
|
55
|
-
};
|
|
56
42
|
const createMessage = ({
|
|
57
43
|
role,
|
|
58
44
|
name = "Guest",
|
|
59
45
|
avatar,
|
|
60
46
|
isLoading = false,
|
|
61
47
|
content,
|
|
62
|
-
timestamp
|
|
48
|
+
timestamp,
|
|
49
|
+
error
|
|
63
50
|
}) => ({
|
|
64
51
|
role,
|
|
65
52
|
name,
|
|
66
53
|
avatar,
|
|
67
54
|
isLoading,
|
|
68
55
|
content,
|
|
69
|
-
timestamp
|
|
56
|
+
timestamp,
|
|
57
|
+
error
|
|
70
58
|
});
|
|
71
59
|
const createUserMessage = (props) => createMessage({
|
|
72
60
|
...props,
|
|
@@ -79,9 +67,9 @@ const createBotMessage = (props) => createMessage({
|
|
|
79
67
|
});
|
|
80
68
|
const getMessageData = (message) => {
|
|
81
69
|
return {
|
|
82
|
-
model: message?.
|
|
83
|
-
content: message?.
|
|
84
|
-
timestamp: getTimestamp(message?.
|
|
70
|
+
model: message?.response_metadata?.model,
|
|
71
|
+
content: message?.content || "",
|
|
72
|
+
timestamp: getTimestamp(message?.response_metadata?.created_at * 1e3)
|
|
85
73
|
};
|
|
86
74
|
};
|
|
87
75
|
const getDayDifference = (sourceTime, targetTime) => {
|
|
@@ -101,13 +89,16 @@ const getCategorizeMessages = (messages, addProps) => {
|
|
|
101
89
|
"Previous 7 Days": [],
|
|
102
90
|
"Previous 30 Days": []
|
|
103
91
|
};
|
|
104
|
-
messages.forEach((c) => {
|
|
105
|
-
const messageDate = new Date(c.
|
|
92
|
+
messages.sort((a, b) => b.last_message_timestamp - a.last_message_timestamp).forEach((c) => {
|
|
93
|
+
const messageDate = new Date(c.last_message_timestamp * 1e3);
|
|
106
94
|
const messageDayString = messageDate.toDateString();
|
|
107
|
-
const dayDifference = getDayDifference(
|
|
95
|
+
const dayDifference = getDayDifference(
|
|
96
|
+
now,
|
|
97
|
+
c.last_message_timestamp * 1e3
|
|
98
|
+
);
|
|
108
99
|
const message = {
|
|
109
100
|
id: c.conversation_id,
|
|
110
|
-
text: c.
|
|
101
|
+
text: c.topic_summary,
|
|
111
102
|
label: "Options",
|
|
112
103
|
...addProps(c)
|
|
113
104
|
};
|
|
@@ -142,5 +133,5 @@ const getCategorizeMessages = (messages, addProps) => {
|
|
|
142
133
|
return filteredCategories;
|
|
143
134
|
};
|
|
144
135
|
|
|
145
|
-
export { createBotMessage, createMessage, createUserMessage, getCategorizeMessages, getDayDifference, getFootnoteProps, getMessageData, getTimestamp, getTimestampVariablesString
|
|
136
|
+
export { createBotMessage, createMessage, createUserMessage, getCategorizeMessages, getDayDifference, getFootnoteProps, getMessageData, getTimestamp, getTimestampVariablesString };
|
|
146
137
|
//# sourceMappingURL=lightspeed-chatbox-utils.esm.js.map
|
|
@@ -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};\n\nexport const createMessage = ({\n role,\n name = 'Guest',\n avatar,\n isLoading = false,\n content,\n timestamp,\n}: MessageProps & { role: 'user' | 'bot' }) => ({\n role,\n name,\n avatar,\n isLoading,\n content,\n timestamp,\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?.kwargs?.response_metadata?.model,\n content: message?.kwargs?.content || '',\n timestamp: getTimestamp(message?.kwargs?.response_metadata?.created_at),\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\n messages.forEach(c => {\n const messageDate = new Date(c.lastMessageTimestamp);\n const messageDayString = messageDate.toDateString();\n const dayDifference = getDayDifference(now, c.lastMessageTimestamp);\n\n const message: Conversation = {\n id: c.conversation_id,\n text: c.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,EA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KAAK,OAAO,CAAA;AAAA,KAC5C,MAAA,IAAW,iBAAiB,CAAG,EAAA;AAC7B,MAAoB,mBAAA,CAAA,iBAAiB,CAAE,CAAA,IAAA,CAAK,OAAO,CAAA;AAAA,KACrD,MAAA,IAAW,iBAAiB,EAAI,EAAA;AAC9B,MAAoB,mBAAA,CAAA,kBAAkB,CAAE,CAAA,IAAA,CAAK,OAAO,CAAA;AAAA,KAC/C,MAAA;AAEL,MAAM,MAAA,SAAA,GAAY,WAAY,CAAA,cAAA,CAAe,SAAW,EAAA;AAAA,QACtD,KAAO,EAAA,MAAA;AAAA,QACP,IAAM,EAAA;AAAA,OACP,CAAA;AACD,MAAI,IAAA,CAAC,mBAAoB,CAAA,SAAS,CAAG,EAAA;AACnC,QAAoB,mBAAA,CAAA,SAAS,IAAI,EAAC;AAAA;AAEpC,MAAoB,mBAAA,CAAA,SAAS,CAAE,CAAA,IAAA,CAAK,OAAO,CAAA;AAAA;AAC7C,GACD,CAAA;AAED,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 } 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,iCAAiC,CAAA;AAC/C,IAAO,OAAA,EAAA;AAAA;AAGT,EAAM,MAAA,CAAA,GAAI,IAAI,IAAA,CAAK,cAAc,CAAA;AACjC,EAA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AAA,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;;;;"}
|
package/package.json
CHANGED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import { useApi } from '@backstage/core-plugin-api';
|
|
2
|
-
import { useQueryClient, useMutation } from '@tanstack/react-query';
|
|
3
|
-
import { lightspeedApiRef } from '../api/api.esm.js';
|
|
4
|
-
|
|
5
|
-
const useCreateConversation = () => {
|
|
6
|
-
const lightspeedApi = useApi(lightspeedApiRef);
|
|
7
|
-
const queryClient = useQueryClient();
|
|
8
|
-
return useMutation({
|
|
9
|
-
mutationFn: () => {
|
|
10
|
-
return lightspeedApi.createConversation();
|
|
11
|
-
},
|
|
12
|
-
onSuccess: () => {
|
|
13
|
-
queryClient.invalidateQueries({ queryKey: ["conversations"] });
|
|
14
|
-
}
|
|
15
|
-
});
|
|
16
|
-
};
|
|
17
|
-
|
|
18
|
-
export { useCreateConversation };
|
|
19
|
-
//# sourceMappingURL=useCreateConversation.esm.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"useCreateConversation.esm.js","sources":["../../src/hooks/useCreateConversation.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, useQueryClient } from '@tanstack/react-query';\n\nimport { lightspeedApiRef } from '../api/api';\n\nexport const useCreateConversation = () => {\n const lightspeedApi = useApi(lightspeedApiRef);\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationFn: () => {\n return lightspeedApi.createConversation();\n },\n onSuccess: () => {\n queryClient.invalidateQueries({ queryKey: ['conversations'] });\n },\n });\n};\n"],"names":[],"mappings":";;;;AAsBO,MAAM,wBAAwB,MAAM;AACzC,EAAM,MAAA,aAAA,GAAgB,OAAO,gBAAgB,CAAA;AAC7C,EAAA,MAAM,cAAc,cAAe,EAAA;AAEnC,EAAA,OAAO,WAAY,CAAA;AAAA,IACjB,YAAY,MAAM;AAChB,MAAA,OAAO,cAAc,kBAAmB,EAAA;AAAA,KAC1C;AAAA,IACA,WAAW,MAAM;AACf,MAAA,WAAA,CAAY,kBAAkB,EAAE,QAAA,EAAU,CAAC,eAAe,GAAG,CAAA;AAAA;AAC/D,GACD,CAAA;AACH;;;;"}
|