@red-hat-developer-hub/backstage-plugin-lightspeed 0.2.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.
Files changed (55) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +179 -0
  3. package/app-config.dynamic.yaml +14 -0
  4. package/config.d.ts +41 -0
  5. package/dist/api/LightspeedApiClient.esm.js +108 -0
  6. package/dist/api/LightspeedApiClient.esm.js.map +1 -0
  7. package/dist/api/api.esm.js +8 -0
  8. package/dist/api/api.esm.js.map +1 -0
  9. package/dist/components/LightSpeedChat.esm.js +239 -0
  10. package/dist/components/LightSpeedChat.esm.js.map +1 -0
  11. package/dist/components/LightspeedChatBox.esm.js +58 -0
  12. package/dist/components/LightspeedChatBox.esm.js.map +1 -0
  13. package/dist/components/LightspeedChatBoxHeader.esm.js +41 -0
  14. package/dist/components/LightspeedChatBoxHeader.esm.js.map +1 -0
  15. package/dist/components/LightspeedIcon.esm.js +9 -0
  16. package/dist/components/LightspeedIcon.esm.js.map +1 -0
  17. package/dist/components/LightspeedPage.esm.js +71 -0
  18. package/dist/components/LightspeedPage.esm.js.map +1 -0
  19. package/dist/components/PermissionRequiredIcon.esm.js +9 -0
  20. package/dist/components/PermissionRequiredIcon.esm.js.map +1 -0
  21. package/dist/components/PermissionRequiredState.esm.js +42 -0
  22. package/dist/components/PermissionRequiredState.esm.js.map +1 -0
  23. package/dist/hooks/useAllModels.esm.js +19 -0
  24. package/dist/hooks/useAllModels.esm.js.map +1 -0
  25. package/dist/hooks/useBackstageUserIdentity.esm.js +14 -0
  26. package/dist/hooks/useBackstageUserIdentity.esm.js.map +1 -0
  27. package/dist/hooks/useConversationMessages.esm.js +195 -0
  28. package/dist/hooks/useConversationMessages.esm.js.map +1 -0
  29. package/dist/hooks/useConversations.esm.js +19 -0
  30. package/dist/hooks/useConversations.esm.js.map +1 -0
  31. package/dist/hooks/useCreateConversation.esm.js +19 -0
  32. package/dist/hooks/useCreateConversation.esm.js.map +1 -0
  33. package/dist/hooks/useCreateCoversationMessage.esm.js +29 -0
  34. package/dist/hooks/useCreateCoversationMessage.esm.js.map +1 -0
  35. package/dist/hooks/useDeleteConversation.esm.js +37 -0
  36. package/dist/hooks/useDeleteConversation.esm.js.map +1 -0
  37. package/dist/hooks/useLightspeedDeletePermission.esm.js +12 -0
  38. package/dist/hooks/useLightspeedDeletePermission.esm.js.map +1 -0
  39. package/dist/hooks/useLightspeedViewPermission.esm.js +18 -0
  40. package/dist/hooks/useLightspeedViewPermission.esm.js.map +1 -0
  41. package/dist/images/logo-white.svg +16 -0
  42. package/dist/images/logo.svg +1 -0
  43. package/dist/images/permission-required.svg +48 -0
  44. package/dist/index.d.ts +24 -0
  45. package/dist/index.esm.js +3 -0
  46. package/dist/index.esm.js.map +1 -0
  47. package/dist/plugin.esm.js +33 -0
  48. package/dist/plugin.esm.js.map +1 -0
  49. package/dist/routes.esm.js +8 -0
  50. package/dist/routes.esm.js.map +1 -0
  51. package/dist/utils/lightspeed-chatbox-utils.esm.js +146 -0
  52. package/dist/utils/lightspeed-chatbox-utils.esm.js.map +1 -0
  53. package/dist/utils/queryClient.esm.js +6 -0
  54. package/dist/utils/queryClient.esm.js.map +1 -0
  55. package/package.json +108 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,24 @@
1
+ ## @red-hat-developer-hub/backstage-plugin-lightspeed
2
+
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - c113d1a: - add RBAC permission support.
8
+ - add multiple chats, chat creation, deletion and searching. [#2501](https://github.com/janus-idp/backstage-plugins/pull/2501)
9
+
10
+ ### Patch Changes
11
+
12
+ - Updated dependencies [c113d1a]
13
+ - @red-hat-developer-hub/backstage-plugin-lightspeed-common@0.1.1
14
+
15
+ ## 0.1.3
16
+
17
+ ### Patch Changes
18
+
19
+ - 9fccf3f: Migrated from [janus-idp/backstage-plugins](https://github.com/janus-idp/backstage-plugins).
20
+
21
+ ### Features
22
+
23
+ - **lightspeed:** add a new lightspeed plugin with basic implementation of chat ([#1889](https://github.com/janus-idp/backstage-plugins/issues/1889)) ([cb80e38](https://github.com/janus-idp/backstage-plugins/commit/cb80e38d4d35a8097cd84b57c1b8eb12ec5af6b4))
24
+ - **lightspeed:** add api client ([#2020](https://github.com/janus-idp/backstage-plugins/issues/2020)) ([ff09574](https://github.com/janus-idp/backstage-plugins/commit/ff095742c542869c7a330d391bd619e97473218c))
package/README.md ADDED
@@ -0,0 +1,179 @@
1
+ # Lightspeed plugin for Backstage
2
+
3
+ The Lightspeed plugin enables you to interact with any LLM server running a model with OpenAI's API compatibility.
4
+
5
+ ## For administrators
6
+
7
+ ### Prerequisites
8
+
9
+ - Follow the lightspeed backend plugin [README](https://github.com/janus-idp/backstage-plugins/tree/main/plugins/lightspeed-backend) to integrate lightspeed backend in your Backstage instance.
10
+
11
+ **Note**
12
+
13
+ ### Permission Framework Support
14
+
15
+ The Lightspeed plugin has support for the permission framework.
16
+
17
+ - When [RBAC permission](https://github.com/backstage/community-plugins/tree/main/workspaces/rbac/plugins/rbac-backend#installation) framework is enabled, for non-admin users to access lightspeed UI, the role associated with your user should have the following permission policies associated with it. Add the following in your permission policies configuration file named `rbac-policy.csv`:
18
+
19
+ ```CSV
20
+ p, role:default/team_a, lightspeed.conversations.read, read, allow
21
+ p, role:default/team_a, lightspeed.conversations.create, create, allow
22
+ p, role:default/team_a, lightspeed.conversations.delete, delete, allow
23
+
24
+ g, user:default/<your-user-name>, role:default/team_a
25
+
26
+ ```
27
+
28
+ You can specify the path to this configuration file in your application configuration:
29
+
30
+ ```yaml
31
+ permission:
32
+ enabled: true
33
+ rbac:
34
+ policies-csv-file: /some/path/rbac-policy.csv
35
+ policyFileReload: true
36
+ ```
37
+
38
+ ### Installation
39
+
40
+ 1. Install the Lightspeed plugin using the following command:
41
+
42
+ ```console
43
+ yarn workspace app add @red-hat-developer-hub/backstage-plugin-lightspeed
44
+ ```
45
+
46
+ ### Configuration
47
+
48
+ 1. Add a new nav item **Lightspeed** in App `packages/app/src/App.tsx`:
49
+
50
+ ```tsx title="packages/app/src/components/App.tsx"
51
+ /* highlight-add-next-line */ import { LightspeedPage } from '@red-hat-developer-hub/backstage-plugin-lightspeed';
52
+
53
+ <Route path="/lightspeed" element={<LightspeedPage />} />;
54
+ ```
55
+
56
+ 2. Enable **Lightspeed** page in `packages/app/src/components/Root/Root.tsx`:
57
+
58
+ ```tsx title="packages/app/src/components/Root/Root.tsx"
59
+ /* highlight-add-next-line */ import { LightspeedIcon } from '@red-hat-developer-hub/backstage-plugin-lightspeed';
60
+
61
+ <SidebarItem
62
+ icon={LightspeedIcon as IconComponent}
63
+ to="lightspeed"
64
+ text="Lightspeed"
65
+ />;
66
+ ```
67
+
68
+ ## For users
69
+
70
+ ### Using the Lightspeed plugin in Backstage
71
+
72
+ Lightspeed is a front-end plugin that enables you to interact with any LLM server running a model with OpenAI's API compatibility.
73
+
74
+ #### Prerequisites
75
+
76
+ - Your Backstage application is installed and running.
77
+ - You have installed the Lightspeed plugin. For installation process, see [Installation](#installation).
78
+
79
+ #### Procedure
80
+
81
+ 1. Open your Backstage application and select a Lightspeed nav item from the **Navigation**.
82
+ 2. Ask you questions to the Lightspeed chatbot.
83
+
84
+ ## Loading as Dynamic Plugin
85
+
86
+ #### To install Lightspeed plugin into Red Hat Developer Hub or Janus IDP via Helm use this configuration:
87
+
88
+ - Load the lightspeed plugin from the npm registry
89
+
90
+ ```
91
+ global:
92
+ dynamic:
93
+ includes:
94
+ - dynamic-plugins.default.yaml
95
+ plugins:
96
+ - package: '@red-hat-developer-hub/backstage-plugin-lightspeed@0.1.2'
97
+ integrity: >-
98
+ sha512-bCKETjVhjZFLx7ImSFcptA3yvwJhFLFTFhMo/LvdVc0K5E76/SpEEkYBPup4aEQMivZBJKn0iVQFBuduChCDpA==
99
+ disabled: false
100
+ pluginConfig:
101
+ dynamicPlugins:
102
+ frontend:
103
+ janus-idp.backstage-plugin-lightspeed:
104
+ appIcons:
105
+ - name: LightspeedIcon
106
+ module: LightspeedPlugin
107
+ importName: LightspeedIcon
108
+ dynamicRoutes:
109
+ - path: /lightspeed
110
+ importName: LightspeedPage
111
+ module: LightspeedPlugin
112
+ menuItem:
113
+ icon: LightspeedIcon
114
+ text: Lightspeed
115
+ ```
116
+
117
+ - add the lightspeed configuration in the `app-config.yaml`
118
+
119
+ ```
120
+ lightspeed:
121
+ servers:
122
+ - id: <server_id>
123
+ url: <server_URL>
124
+ token: <api_key>
125
+ ```
126
+
127
+ ---
128
+
129
+ #### To install this plugin locally in [backstage-showcase](https://github.com/janus-idp/backstage-showcase) application as a dynamic plugin.
130
+
131
+ Follow the below steps -
132
+
133
+ - Export dynamic plugin assets. This will build and create the static assets for the plugin and put it inside dist-scalprum folder.
134
+
135
+ `yarn install`
136
+
137
+ `yarn tsc`
138
+
139
+ `yarn build`
140
+
141
+ `yarn export-dynamic`
142
+
143
+ - Package and copy dist-scalprum folder assets to dynamic-plugins-root folder in [backstage-showcase](https://github.com/janus-idp/backstage-showcase) application.
144
+
145
+ To Package the plugin, run the below commands.
146
+
147
+ ```
148
+ pkg=../plugins/lightspeed
149
+ archive=$(npm pack $pkg)
150
+ tar -xzf "$archive" && rm "$archive"
151
+ mv package $(echo $archive | sed -e 's:\.tgz$::')
152
+ ```
153
+
154
+ - Add the extension point inside the `app-config.yaml` or `app-config.local.yaml` file.
155
+
156
+ ```
157
+
158
+ lightspeed:
159
+ servers:
160
+ - id: <server id>
161
+ url: <serverURL>
162
+ token: <api key> # dummy token
163
+
164
+ dynamicPlugins:
165
+ frontend:
166
+ janus-idp.backstage-plugin-lightspeed:
167
+ appIcons:
168
+ - name: LightspeedIcon
169
+ module: LightspeedPlugin
170
+ importName: LightspeedIcon
171
+ dynamicRoutes:
172
+ - path: /lightspeed
173
+ importName: LightspeedPage
174
+ module: LightspeedPlugin
175
+ menuItem:
176
+ icon: LightspeedIcon
177
+ text: Lightspeed
178
+
179
+ ```
@@ -0,0 +1,14 @@
1
+ dynamicPlugins:
2
+ frontend:
3
+ red-hat-developer-hub.backstage-plugin-lightspeed:
4
+ appIcons:
5
+ - name: LightspeedIcon
6
+ module: LightspeedPlugin
7
+ importName: LightspeedIcon
8
+ dynamicRoutes:
9
+ - path: /lightspeed
10
+ importName: LightspeedPage
11
+ module: LightspeedPlugin
12
+ menuItem:
13
+ icon: LightspeedIcon
14
+ text: Lightspeed
package/config.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ /*
2
+ * Copyright 2024 The Backstage Authors
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ export interface Config {
17
+ /**
18
+ * Configuration required for using lightspeed
19
+ * @visibility frontend
20
+ */
21
+ lightspeed: {
22
+ /**
23
+ * @visibility frontend
24
+ */
25
+ servers: Array</**
26
+ * @visibility frontend
27
+ */
28
+ {
29
+ /**
30
+ * The id of the server.
31
+ * @visibility frontend
32
+ */
33
+ id: string;
34
+ /**
35
+ * The url of the server.
36
+ * @visibility frontend
37
+ */
38
+ url: string;
39
+ }>;
40
+ };
41
+ }
@@ -0,0 +1,108 @@
1
+ class LightspeedApiClient {
2
+ configApi;
3
+ fetchApi;
4
+ constructor(options) {
5
+ this.configApi = options.configApi;
6
+ this.fetchApi = options.fetchApi;
7
+ }
8
+ async getBaseUrl() {
9
+ return `${this.configApi.getString("backend.baseUrl")}/api/lightspeed`;
10
+ }
11
+ getServerUrl() {
12
+ return `${this.configApi.getConfigArray("lightspeed.servers")[0].getOptionalString("url")}`;
13
+ }
14
+ async createMessage(prompt, selectedModel, conversation_id) {
15
+ const baseUrl = await this.getBaseUrl();
16
+ const response = await this.fetchApi.fetch(`${baseUrl}/v1/query`, {
17
+ method: "POST",
18
+ headers: {
19
+ "Content-Type": "application/json"
20
+ },
21
+ body: JSON.stringify({
22
+ conversation_id,
23
+ serverURL: this.getServerUrl(),
24
+ model: selectedModel,
25
+ query: prompt,
26
+ historyLength: 10
27
+ })
28
+ });
29
+ if (!response.body) {
30
+ throw new Error("Readable stream is not supported or there is no body.");
31
+ }
32
+ if (!response.ok) {
33
+ throw new Error(
34
+ `failed to fetch data, status ${response.status}: ${response.statusText}`
35
+ );
36
+ }
37
+ return response.body.getReader();
38
+ }
39
+ async fetcher(url) {
40
+ const response = await this.fetchApi.fetch(url, {
41
+ headers: {
42
+ "Content-Type": "application/json"
43
+ }
44
+ });
45
+ if (!response.ok) {
46
+ throw new Error(
47
+ `failed to fetch data, status ${response.status}: ${response.statusText}`
48
+ );
49
+ }
50
+ return response;
51
+ }
52
+ async getAllModels() {
53
+ const baseUrl = await this.getBaseUrl();
54
+ const result = await this.fetcher(`${baseUrl}/v1/models`);
55
+ const response = await result.json();
56
+ return response?.data ? response.data : [];
57
+ }
58
+ async getConversationMessages(conversation_id) {
59
+ const baseUrl = await this.getBaseUrl();
60
+ const result = await this.fetcher(
61
+ `${baseUrl}/conversations/${encodeURIComponent(conversation_id)}`
62
+ );
63
+ return await result.json();
64
+ }
65
+ async getConversations() {
66
+ const baseUrl = await this.getBaseUrl();
67
+ const result = await this.fetcher(`${baseUrl}/conversations`);
68
+ return await result.json();
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) {
83
+ throw new Error(
84
+ `failed to create conversation, status ${response.status}: ${response.statusText}`
85
+ );
86
+ }
87
+ return await response.json();
88
+ }
89
+ async deleteConversation(conversation_id) {
90
+ const baseUrl = await this.getBaseUrl();
91
+ const response = await this.fetchApi.fetch(
92
+ `${baseUrl}/conversations/${encodeURIComponent(conversation_id)}`,
93
+ {
94
+ method: "DELETE",
95
+ headers: {}
96
+ }
97
+ );
98
+ if (!response.ok) {
99
+ throw new Error(
100
+ `failed to delete conversation, status ${response.status}: ${response.statusText}`
101
+ );
102
+ }
103
+ return { success: true };
104
+ }
105
+ }
106
+
107
+ export { LightspeedApiClient };
108
+ //# sourceMappingURL=LightspeedApiClient.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LightspeedApiClient.esm.js","sources":["../../src/api/LightspeedApiClient.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\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 { 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,\n serverURL: this.getServerUrl(),\n model: selectedModel,\n query: prompt,\n historyLength: 10,\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 throw new Error(\n `failed to fetch data, status ${response.status}: ${response.statusText}`,\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 const response = await result.json();\n return response?.data ? response.data : [];\n }\n\n async getConversationMessages(conversation_id: string) {\n const baseUrl = await this.getBaseUrl();\n const result = await this.fetcher(\n `${baseUrl}/conversations/${encodeURIComponent(conversation_id)}`,\n );\n return await result.json();\n }\n\n async getConversations() {\n const baseUrl = await this.getBaseUrl();\n const result = await this.fetcher(`${baseUrl}/conversations`);\n return await result.json();\n }\n\n async createConversation() {\n const baseUrl = await this.getBaseUrl();\n\n const response = await this.fetchApi.fetch(`${baseUrl}/conversations`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({}),\n });\n\n if (!response.body) {\n throw new Error('Something went wrong.');\n }\n\n if (!response.ok) {\n throw new Error(\n `failed to create conversation, status ${response.status}: ${response.statusText}`,\n );\n }\n return await response.json();\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: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AAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAyC,sCAAA,EAAA,QAAA,CAAS,MAAM,CAAA,EAAA,EAAK,SAAS,UAAU,CAAA;AAAA,OAClF;AAAA;AAEF,IAAO,OAAA,EAAE,SAAS,IAAK,EAAA;AAAA;AAE3B;;;;"}
@@ -0,0 +1,8 @@
1
+ import { createApiRef } from '@backstage/core-plugin-api';
2
+
3
+ const lightspeedApiRef = createApiRef({
4
+ id: "plugin.lightspeed.service"
5
+ });
6
+
7
+ export { lightspeedApiRef };
8
+ //# sourceMappingURL=api.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.esm.js","sources":["../../src/api/api.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\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 { 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 createConversation: () => Promise<{ conversation_id: string }>;\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;;;;"}
@@ -0,0 +1,239 @@
1
+ import React__default from 'react';
2
+ import { ErrorPanel } from '@backstage/core-components';
3
+ import { makeStyles, Box } from '@material-ui/core';
4
+ import { DropdownItem, Title } from '@patternfly/react-core';
5
+ import { Chatbot, ChatbotDisplayMode, ChatbotHeader, ChatbotHeaderMain, ChatbotHeaderMenu, ChatbotHeaderTitle, ChatbotContent, ChatbotFooter, MessageBar, ChatbotFootnote } from '@patternfly/virtual-assistant';
6
+ import ChatbotConversationHistoryNav from '@patternfly/virtual-assistant/dist/dynamic/ChatbotConversationHistoryNav';
7
+ import { useQueryClient } from '@tanstack/react-query';
8
+ import { useBackstageUserIdentity } from '../hooks/useBackstageUserIdentity.esm.js';
9
+ import { useConversationMessages } from '../hooks/useConversationMessages.esm.js';
10
+ import { useConversations } from '../hooks/useConversations.esm.js';
11
+ import { useCreateConversation } from '../hooks/useCreateConversation.esm.js';
12
+ import { useDeleteConversation } from '../hooks/useDeleteConversation.esm.js';
13
+ import { useLightspeedDeletePermission } from '../hooks/useLightspeedDeletePermission.esm.js';
14
+ import { getCategorizeMessages, getFootnoteProps } from '../utils/lightspeed-chatbox-utils.esm.js';
15
+ import { LightspeedChatBox } from './LightspeedChatBox.esm.js';
16
+ import { LightspeedChatBoxHeader } from './LightspeedChatBoxHeader.esm.js';
17
+
18
+ const useStyles = makeStyles((theme) => ({
19
+ content: {
20
+ "&.pf-chatbot__content": {
21
+ padding: 0
22
+ }
23
+ },
24
+ header: {
25
+ padding: `${theme.spacing(3)}px !important`
26
+ },
27
+ drawerActions: {
28
+ "&.pf-v6-c-drawer__actions": {
29
+ flexDirection: "row-reverse"
30
+ }
31
+ },
32
+ headerTitle: {
33
+ justifyContent: "left !important"
34
+ },
35
+ footer: {
36
+ "&.pf-chatbot__footer": {
37
+ padding: "0 var(--pf-t--global--spacer--lg) var(--pf-t--global--spacer--lg) var(--pf-t--global--spacer--lg)"
38
+ }
39
+ }
40
+ }));
41
+ const LightspeedChat = ({
42
+ selectedModel,
43
+ userName,
44
+ avatar,
45
+ profileLoading,
46
+ handleSelectedModel,
47
+ models
48
+ }) => {
49
+ const classes = useStyles();
50
+ const user = useBackstageUserIdentity();
51
+ const [filterValue, setFilterValue] = React__default.useState("");
52
+ const [announcement, setAnnouncement] = React__default.useState("");
53
+ const [conversationId, setConversationId] = React__default.useState("");
54
+ const [isDrawerOpen, setIsDrawerOpen] = React__default.useState(true);
55
+ const [newChatCreated, setNewChatCreated] = React__default.useState(true);
56
+ const [isSendButtonDisabled, setIsSendButtonDisabled] = React__default.useState(false);
57
+ const [error, setError] = React__default.useState(null);
58
+ const queryClient = useQueryClient();
59
+ const { data: conversations = [] } = useConversations();
60
+ const { mutateAsync: createConversation } = useCreateConversation();
61
+ const { mutateAsync: deleteConversation } = useDeleteConversation();
62
+ const { allowed: hasDeleteAccess } = useLightspeedDeletePermission();
63
+ React__default.useEffect(() => {
64
+ if (user) {
65
+ createConversation().then(({ conversation_id }) => {
66
+ setConversationId(conversation_id);
67
+ }).catch((e) => {
68
+ console.warn(e);
69
+ setError(e);
70
+ });
71
+ }
72
+ }, [user, setConversationId, createConversation]);
73
+ const onComplete = (message) => {
74
+ setIsSendButtonDisabled(false);
75
+ setAnnouncement(`Message from Bot: ${message}`);
76
+ queryClient.invalidateQueries({
77
+ queryKey: ["conversations"]
78
+ });
79
+ };
80
+ const { conversationMessages, handleInputPrompt, scrollToBottomRef } = useConversationMessages(
81
+ conversationId,
82
+ userName,
83
+ selectedModel,
84
+ avatar,
85
+ onComplete
86
+ );
87
+ const [messages, setMessages] = React__default.useState(conversationMessages);
88
+ React__default.useEffect(() => {
89
+ setTimeout(() => {
90
+ scrollToBottomRef.current?.scrollIntoView({ behavior: "auto" });
91
+ }, 10);
92
+ }, [messages, scrollToBottomRef.current]);
93
+ const sendMessage = (message) => {
94
+ setNewChatCreated(false);
95
+ setAnnouncement(
96
+ `Message from User: ${prompt}. Message from Bot is loading.`
97
+ );
98
+ handleInputPrompt(message);
99
+ setIsSendButtonDisabled(true);
100
+ };
101
+ const onNewChat = React__default.useCallback(() => {
102
+ (async () => {
103
+ setMessages([]);
104
+ const { conversation_id } = await createConversation();
105
+ setConversationId(conversation_id);
106
+ setNewChatCreated(true);
107
+ })();
108
+ }, [createConversation, setConversationId, setMessages]);
109
+ const additionalMessageProps = React__default.useCallback(
110
+ (conversationSummary) => ({
111
+ menuItems: /* @__PURE__ */ React__default.createElement(
112
+ DropdownItem,
113
+ {
114
+ isDisabled: !hasDeleteAccess,
115
+ onClick: async () => {
116
+ try {
117
+ await deleteConversation({
118
+ conversation_id: conversationSummary.conversation_id,
119
+ invalidateCache: false
120
+ });
121
+ onNewChat();
122
+ } catch (e) {
123
+ console.warn(e);
124
+ }
125
+ }
126
+ },
127
+ "Delete"
128
+ )
129
+ }),
130
+ [deleteConversation, onNewChat, hasDeleteAccess]
131
+ );
132
+ const categorizedMessages = getCategorizeMessages(
133
+ conversations,
134
+ additionalMessageProps
135
+ );
136
+ const filterConversations = React__default.useCallback(
137
+ (targetValue) => {
138
+ const filteredConversations = Object.entries(categorizedMessages).reduce(
139
+ (acc, [key, items]) => {
140
+ const filteredItems = items.filter(
141
+ (item) => item.text.toLocaleLowerCase("en-US").includes(targetValue.toLocaleLowerCase("en-US"))
142
+ );
143
+ if (filteredItems.length > 0) {
144
+ acc[key] = filteredItems;
145
+ }
146
+ return acc;
147
+ },
148
+ {}
149
+ );
150
+ return filteredConversations;
151
+ },
152
+ [categorizedMessages]
153
+ );
154
+ React__default.useEffect(() => {
155
+ setMessages(conversationMessages);
156
+ }, [conversationMessages]);
157
+ const onSelectActiveItem = React__default.useCallback(
158
+ (_, selectedItem) => {
159
+ setNewChatCreated(false);
160
+ setConversationId((c_id) => {
161
+ if (c_id !== selectedItem) {
162
+ return String(selectedItem);
163
+ }
164
+ return c_id;
165
+ });
166
+ },
167
+ [setConversationId]
168
+ );
169
+ const welcomePrompts = newChatCreated ? [
170
+ {
171
+ title: "Topic 1",
172
+ message: "Helpful prompt for Topic 1",
173
+ onClick: () => sendMessage("Helpful prompt for Topic 1")
174
+ },
175
+ {
176
+ title: "Topic 2",
177
+ message: "Helpful prompt for Topic 2",
178
+ onClick: () => sendMessage("Helpful prompt for Topic 2")
179
+ }
180
+ ] : [];
181
+ const handleFilter = React__default.useCallback((value) => {
182
+ setFilterValue(value);
183
+ }, []);
184
+ const onDrawerToggle = React__default.useCallback(() => {
185
+ setIsDrawerOpen((isOpen) => !isOpen);
186
+ }, []);
187
+ if (error) {
188
+ return /* @__PURE__ */ React__default.createElement(Box, { padding: 1 }, /* @__PURE__ */ React__default.createElement(ErrorPanel, { error }));
189
+ }
190
+ return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, /* @__PURE__ */ React__default.createElement(Chatbot, { displayMode: ChatbotDisplayMode.embedded }, /* @__PURE__ */ React__default.createElement(ChatbotHeader, { className: classes.header }, /* @__PURE__ */ React__default.createElement(ChatbotHeaderMain, null, /* @__PURE__ */ React__default.createElement(
191
+ ChatbotHeaderMenu,
192
+ {
193
+ "aria-expanded": isDrawerOpen,
194
+ onMenuToggle: () => setIsDrawerOpen(!isDrawerOpen)
195
+ }
196
+ ), /* @__PURE__ */ React__default.createElement(ChatbotHeaderTitle, { className: classes.headerTitle }, /* @__PURE__ */ React__default.createElement(Title, { headingLevel: "h1", size: "3xl" }, "Developer Hub Lightspeed"))), /* @__PURE__ */ React__default.createElement(
197
+ LightspeedChatBoxHeader,
198
+ {
199
+ selectedModel,
200
+ handleSelectedModel: (item) => handleSelectedModel(item),
201
+ models
202
+ }
203
+ )), /* @__PURE__ */ React__default.createElement(
204
+ ChatbotConversationHistoryNav,
205
+ {
206
+ displayMode: ChatbotDisplayMode.embedded,
207
+ onDrawerToggle,
208
+ isDrawerOpen,
209
+ setIsDrawerOpen,
210
+ activeItemId: conversationId,
211
+ onSelectActiveItem,
212
+ conversations: filterConversations(filterValue),
213
+ onNewChat: newChatCreated ? void 0 : onNewChat,
214
+ handleTextInputChange: handleFilter,
215
+ drawerContent: /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, /* @__PURE__ */ React__default.createElement(ChatbotContent, { className: classes.content }, /* @__PURE__ */ React__default.createElement(
216
+ LightspeedChatBox,
217
+ {
218
+ userName,
219
+ messages,
220
+ profileLoading,
221
+ announcement,
222
+ ref: scrollToBottomRef,
223
+ welcomePrompts
224
+ }
225
+ )), /* @__PURE__ */ React__default.createElement(ChatbotFooter, { className: classes.footer }, /* @__PURE__ */ React__default.createElement(
226
+ MessageBar,
227
+ {
228
+ onSendMessage: sendMessage,
229
+ isSendButtonDisabled,
230
+ hasAttachButton: false,
231
+ hasMicrophoneButton: true
232
+ }
233
+ ), /* @__PURE__ */ React__default.createElement(ChatbotFootnote, { ...getFootnoteProps() })))
234
+ }
235
+ )));
236
+ };
237
+
238
+ export { LightspeedChat };
239
+ //# sourceMappingURL=LightSpeedChat.esm.js.map