openkbs 0.0.26 → 0.0.28
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/README.md +140 -1
- package/package.json +1 -1
- package/src/utils.js +7 -3
- package/Docs.md +0 -766
package/README.md
CHANGED
|
@@ -673,6 +673,11 @@ $InputLabel = """Let me Search in Google!"""
|
|
|
673
673
|
$InputValue = """Search in google for the latest news"""
|
|
674
674
|
|
|
675
675
|
/someCommand("param")
|
|
676
|
+
|
|
677
|
+
$Comment = """
|
|
678
|
+
Any instructions or comments placed here will be removed before sending to the LLM.
|
|
679
|
+
These can span multiple lines and contain any characters, code, or formatting.
|
|
680
|
+
"""
|
|
676
681
|
...
|
|
677
682
|
|
|
678
683
|
```
|
|
@@ -685,10 +690,30 @@ Command definitions may include \$InputLabel and \$InputValue which are invisiab
|
|
|
685
690
|
|
|
686
691
|
These features provide quick command access and pre-populate inputs, enhancing user interaction.
|
|
687
692
|
|
|
693
|
+
`zipMessages` and `unzipMessages` command instructions allow the LLM to manage the chat size by summarizing or restoring portions of the conversation, optimizing context retention and token usage.
|
|
694
|
+
|
|
695
|
+
Instructions:
|
|
696
|
+
```
|
|
697
|
+
/zipMessages([{"MSG_ID": 1234567890123, "zipSummary": "Optional summary"}])
|
|
698
|
+
|
|
699
|
+
Description: """
|
|
700
|
+
Compresses specified messages to optimize chat memory and reduce costs.
|
|
701
|
+
Include message IDs with optional summaries to maintain context while using fewer tokens.
|
|
702
|
+
"""
|
|
703
|
+
```
|
|
704
|
+
|
|
705
|
+
```
|
|
706
|
+
/unzipMessages([{ "MSG_ID" : 1234567890123 }])
|
|
707
|
+
Description: """
|
|
708
|
+
Uncompresses the message associated with the provided `MSG_ID`, restoring its original content to the chat.
|
|
709
|
+
"""
|
|
710
|
+
```
|
|
711
|
+
|
|
712
|
+
**Important:** `MSG_ID` value must be a unique identifier present anywhere in the message content. The OpenKBS platform automatically handles the zipping and unzipping of messages based on these commands. No custom implementation is required.
|
|
688
713
|
|
|
689
714
|
#### Execution Environment
|
|
690
715
|
|
|
691
|
-
The OpenKBS backend provides a pre-configured execution environment for your event handlers, including a set of globally available objects and libraries. This eliminates the need to explicitly declare these as dependencies in your `onRequest.json` or `onResponse.json` files. These predefined resources facilitate various operations
|
|
716
|
+
The OpenKBS backend provides a pre-configured execution environment for your event handlers, including a set of globally available objects and libraries. This eliminates the need to explicitly declare these as dependencies in your `onRequest.json` or `onResponse.json` files. These predefined resources facilitate various operations:
|
|
692
717
|
|
|
693
718
|
Here's a breakdown of the key objects and utilities available within the OpenKBS backend environment:
|
|
694
719
|
|
|
@@ -1203,6 +1228,120 @@ This endpoint allows adding messages to a specified chat, which is useful for in
|
|
|
1203
1228
|
}
|
|
1204
1229
|
```
|
|
1205
1230
|
|
|
1231
|
+
#### createPublicChatToken
|
|
1232
|
+
|
|
1233
|
+
This endpoint allows third-party systems (like WordPress, e-commerce platforms, etc.) to generate signed JWT tokens for their users to interact with the OpenKBS agent. This enables secure, limited access to the agent while maintaining user context and authorization.
|
|
1234
|
+
|
|
1235
|
+
- **Endpoint:** `https://chat.openkbs.com/`
|
|
1236
|
+
- **Method:** `POST`
|
|
1237
|
+
- **Request Body (JSON):**
|
|
1238
|
+
|
|
1239
|
+
For new chat session:
|
|
1240
|
+
```json
|
|
1241
|
+
{
|
|
1242
|
+
"action": "createPublicChatToken",
|
|
1243
|
+
"kbId": "YOUR_KB_ID",
|
|
1244
|
+
"apiKey": "YOUR_API_KEY",
|
|
1245
|
+
"title": "Chat Title (must be encrypted)",
|
|
1246
|
+
"variables": {
|
|
1247
|
+
"publicUserName": "User's Name",
|
|
1248
|
+
"publicUserId": "User's ID",
|
|
1249
|
+
"publicUserEmail": "User's Email (optional)",
|
|
1250
|
+
// Additional custom variables can be added here
|
|
1251
|
+
},
|
|
1252
|
+
"maxMessages": 50, // Limit messages per chat session
|
|
1253
|
+
"maxTokens": 64000, // Limit token usage
|
|
1254
|
+
"tokenExpiration": 3600000, // Token validity period in milliseconds
|
|
1255
|
+
"messages": [
|
|
1256
|
+
{
|
|
1257
|
+
"msgId": "unique_message_id",
|
|
1258
|
+
"role": "assistant",
|
|
1259
|
+
"content": "Welcome message"
|
|
1260
|
+
}
|
|
1261
|
+
]
|
|
1262
|
+
}
|
|
1263
|
+
```
|
|
1264
|
+
|
|
1265
|
+
For existing chat:
|
|
1266
|
+
```json
|
|
1267
|
+
{
|
|
1268
|
+
"action": "createPublicChatToken",
|
|
1269
|
+
"kbId": "YOUR_KB_ID",
|
|
1270
|
+
"apiKey": "YOUR_API_KEY",
|
|
1271
|
+
"chatId": "EXISTING_CHAT_ID",
|
|
1272
|
+
"variables": {
|
|
1273
|
+
"publicUserName": "User's Name",
|
|
1274
|
+
"publicUserId": "User's ID",
|
|
1275
|
+
"publicUserEmail": "User's Email (optional)"
|
|
1276
|
+
},
|
|
1277
|
+
"maxMessages": 50,
|
|
1278
|
+
"maxTokens": 64000,
|
|
1279
|
+
"tokenExpiration": 3600000
|
|
1280
|
+
}
|
|
1281
|
+
```
|
|
1282
|
+
|
|
1283
|
+
**Parameters:**
|
|
1284
|
+
- `title`: (Required for new chat) Encrypted chat title
|
|
1285
|
+
- `chatId`: (Required for existing chat) ID of existing chat session
|
|
1286
|
+
- `variables`: Object containing user information
|
|
1287
|
+
- `maxMessages`: Maximum number of messages allowed in the chat
|
|
1288
|
+
- `maxTokens`: Maximum number of tokens allowed for LLM processing
|
|
1289
|
+
- `tokenExpiration`: Token expiration time in milliseconds
|
|
1290
|
+
- `messages`: (Optional) Initial messages for new chat sessions
|
|
1291
|
+
|
|
1292
|
+
**Key Features:**
|
|
1293
|
+
- Enables third-party systems to create authorized chat sessions for their users
|
|
1294
|
+
- Variables passed in the token can be accessed in agent event handlers using `{{variables.variableName}}`
|
|
1295
|
+
- Enforces usage limits per user/session
|
|
1296
|
+
- Maintains security by signing user context in JWT
|
|
1297
|
+
|
|
1298
|
+
This token can be used for subsequent client-side interactions with the chat system.
|
|
1299
|
+
|
|
1300
|
+
### OpenKBS Chat Widget Integration
|
|
1301
|
+
|
|
1302
|
+
#### Basic Setup
|
|
1303
|
+
|
|
1304
|
+
First, include the OpenKBS Chat Widget script in your HTML:
|
|
1305
|
+
|
|
1306
|
+
```html
|
|
1307
|
+
<script src="https://openkbs.com/widget.js"></script>
|
|
1308
|
+
```
|
|
1309
|
+
|
|
1310
|
+
#### Widget Initialization
|
|
1311
|
+
|
|
1312
|
+
```javascript
|
|
1313
|
+
openkbsWidget('init', {
|
|
1314
|
+
app: 'YOUR_KB_ID', // Your Knowledge Base ID
|
|
1315
|
+
endChatMessage: 'Are you sure you want to end this chat session?',
|
|
1316
|
+
|
|
1317
|
+
// Optional prompt configuration
|
|
1318
|
+
promptTitle: "Can't find what you're looking for?",
|
|
1319
|
+
promptDescription: "Let me help!",
|
|
1320
|
+
showPromptAfter: 5000, // Show prompt after 5 seconds
|
|
1321
|
+
removePromptAfter: 10000, // Remove prompt after 10 seconds
|
|
1322
|
+
|
|
1323
|
+
// Session management
|
|
1324
|
+
initSession: async () => {
|
|
1325
|
+
// Initialize or retrieve chat session (use createPublicChatToken to generate the session)
|
|
1326
|
+
const chatSession = {
|
|
1327
|
+
token: 'JWT_TOKEN_FROM_SERVER',
|
|
1328
|
+
chatId: 'CHAT_ID',
|
|
1329
|
+
kbId: 'YOUR_KB_ID'
|
|
1330
|
+
};
|
|
1331
|
+
localStorage.setItem('openkbsChatSession', JSON.stringify(chatSession));
|
|
1332
|
+
return;
|
|
1333
|
+
},
|
|
1334
|
+
|
|
1335
|
+
// Custom actions that can be triggered by the agent
|
|
1336
|
+
actions: {
|
|
1337
|
+
setFormValue: (data) => {
|
|
1338
|
+
const element = document.querySelector(data.selector);
|
|
1339
|
+
if (element) {
|
|
1340
|
+
element.value = data.value;
|
|
1341
|
+
}
|
|
1342
|
+
},
|
|
1343
|
+
}
|
|
1344
|
+
});
|
|
1206
1345
|
|
|
1207
1346
|
|
|
1208
1347
|
## License
|
package/package.json
CHANGED
package/src/utils.js
CHANGED
|
@@ -652,6 +652,7 @@ async function fetchAndSaveSettings(localKBData, kbId, kbToken) {
|
|
|
652
652
|
chatVendor, kbDescription, kbTitle, model, kbInstructions, inputTools,
|
|
653
653
|
installation,
|
|
654
654
|
itemTypes,
|
|
655
|
+
options,
|
|
655
656
|
embeddingModel, embeddingDimension, searchEngine
|
|
656
657
|
} = decryptKBFields(KBData);
|
|
657
658
|
|
|
@@ -666,13 +667,14 @@ async function fetchAndSaveSettings(localKBData, kbId, kbToken) {
|
|
|
666
667
|
installation,
|
|
667
668
|
}
|
|
668
669
|
|
|
669
|
-
if (embeddingModel && embeddingDimension && searchEngine) {
|
|
670
|
+
if (embeddingModel !== undefined && embeddingDimension !== undefined && searchEngine !== undefined) {
|
|
670
671
|
params.embeddingModel = embeddingModel;
|
|
671
672
|
params.embeddingDimension = embeddingDimension;
|
|
672
673
|
params.searchEngine = searchEngine;
|
|
673
674
|
}
|
|
674
675
|
|
|
675
676
|
if (itemTypes) params.itemTypes = itemTypes;
|
|
677
|
+
if (options) params.options = options;
|
|
676
678
|
|
|
677
679
|
await saveLocalKBData(params);
|
|
678
680
|
console.log(`Downloading: app/settings.json`);
|
|
@@ -752,7 +754,7 @@ async function buildFilesMap(namespaces, kbId, kbToken) {
|
|
|
752
754
|
async function createKB(localKBData, AESKey, isSelfManagedKey = false) {
|
|
753
755
|
const {
|
|
754
756
|
kbId, chatVendor, kbDescription, kbTitle, model, kbInstructions, inputTools, installation,
|
|
755
|
-
itemTypes, embeddingModel, embeddingDimension, searchEngine
|
|
757
|
+
itemTypes, options, embeddingModel, embeddingDimension, searchEngine
|
|
756
758
|
} = localKBData;
|
|
757
759
|
|
|
758
760
|
const token = await getClientJWT();
|
|
@@ -790,6 +792,7 @@ async function createKB(localKBData, AESKey, isSelfManagedKey = false) {
|
|
|
790
792
|
if (!isSelfManagedKey) params.key = AESKey;
|
|
791
793
|
|
|
792
794
|
if (itemTypes) params.itemTypes = itemTypes;
|
|
795
|
+
if (options) params.options = options;
|
|
793
796
|
|
|
794
797
|
if (embeddingModel !== undefined && embeddingDimension !== undefined && searchEngine !== undefined) {
|
|
795
798
|
params.embeddingModel = embeddingModel;
|
|
@@ -803,7 +806,7 @@ async function createKB(localKBData, AESKey, isSelfManagedKey = false) {
|
|
|
803
806
|
async function updateKB(localKBData, KBData, kbToken, withIcon = true) {
|
|
804
807
|
const {
|
|
805
808
|
kbId, chatVendor, kbDescription, kbTitle, model, kbInstructions, inputTools, installation,
|
|
806
|
-
itemTypes, embeddingModel, embeddingDimension, searchEngine
|
|
809
|
+
itemTypes, options, embeddingModel, embeddingDimension, searchEngine
|
|
807
810
|
} = localKBData;
|
|
808
811
|
|
|
809
812
|
// Read and encode the icon file
|
|
@@ -825,6 +828,7 @@ async function updateKB(localKBData, KBData, kbToken, withIcon = true) {
|
|
|
825
828
|
};
|
|
826
829
|
|
|
827
830
|
if (itemTypes) params.itemTypes = itemTypes;
|
|
831
|
+
if (options) params.options = options;
|
|
828
832
|
|
|
829
833
|
if (embeddingModel !== undefined && embeddingDimension !== undefined && searchEngine !== undefined) {
|
|
830
834
|
params.embeddingModel = embeddingModel;
|
package/Docs.md
DELETED
|
@@ -1,766 +0,0 @@
|
|
|
1
|
-
# OpenKBS Framework Documentation
|
|
2
|
-
|
|
3
|
-
## Directory Structure
|
|
4
|
-
|
|
5
|
-
```
|
|
6
|
-
src/
|
|
7
|
-
├── Events/
|
|
8
|
-
│ ├── actions.js // Common actions for onRequest and onResponse
|
|
9
|
-
│ ├── onRequest.js // Handles incoming user messages
|
|
10
|
-
│ ├── onResponse.js // Handles outgoing LLM messages
|
|
11
|
-
│ ├── onPublicAPIRequest.js // Handles public API requests
|
|
12
|
-
│ ├── onAddMessages.js // Handles messages added to the chat (NEW)
|
|
13
|
-
│ ├── onRequest.json // Dependencies for onRequest handler
|
|
14
|
-
│ ├── onResponse.json // Dependencies for onResponse handler
|
|
15
|
-
│ ├── onPublicAPIRequest.json // Dependencies for onPublicAPIRequest handler
|
|
16
|
-
│ └── onAddMessages.json // Dependencies for onAddMessages handler (NEW)
|
|
17
|
-
│── Frontend/
|
|
18
|
-
│ ├── contentRender.js // Custom rendering logic for chat messages
|
|
19
|
-
│ └── contentRender.json // Dependencies for the contentRender module
|
|
20
|
-
|
|
21
|
-
app/
|
|
22
|
-
├── icon.png // Application icon
|
|
23
|
-
├── settings.json // Application settings
|
|
24
|
-
└── instructions.txt // LLM instructions
|
|
25
|
-
```
|
|
26
|
-
|
|
27
|
-
## Backend
|
|
28
|
-
The OpenKBS backend framework provides a powerful system for developing AI agents with custom functionalities. It leverages a Node.js environment and offers hooks into the chat service through `onRequest` and `onResponse` event handlers. These handlers allow developers to process user input and LLM output, respectively, enabling the execution of custom actions and integration with external services.
|
|
29
|
-
|
|
30
|
-
### 1. Event Handlers
|
|
31
|
-
|
|
32
|
-
The core of the OpenKBS backend framework revolves around the `onRequest` and `onResponse` event handlers. These handlers act as middleware, intercepting messages before and after they are processed by the LLM.
|
|
33
|
-
|
|
34
|
-
* **`onRequest` Handler:** This handler is invoked every time a user sends a message to the chat. It provides an opportunity to pre-process the user's input, extract commands, perform actions, and modify the message before it's sent to the LLM.
|
|
35
|
-
|
|
36
|
-
* **`onResponse` Handler:** This handler is invoked after the LLM generates a response. It allows post-processing of the LLM's output, execution of commands based on the LLM's intentions, and modification of the final message presented to the user.
|
|
37
|
-
|
|
38
|
-
* **`onPublicAPIRequest` Handler:** This handler allows public access to certain actions via API requests, even without authentication. This is useful for form submissions and webhooks. It receives a payload containing the action, item type, attributes, and item data.
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
**Example `onRequest` and `onResponse` Handlers Structure (using common actions):**
|
|
42
|
-
|
|
43
|
-
```javascript
|
|
44
|
-
// src/Events/actions.js
|
|
45
|
-
export const getActions = (meta) => {
|
|
46
|
-
return [
|
|
47
|
-
// Define your regular expressions and corresponding actions here
|
|
48
|
-
[/\/?yourCommand\("(.*)"\)/, async (match, event) => {
|
|
49
|
-
// Access match groups, event payload, and openkbs object
|
|
50
|
-
// Execute custom logic, API calls, etc.
|
|
51
|
-
// Return an object with action results and meta information
|
|
52
|
-
return { result: 'Your command executed', ...meta };
|
|
53
|
-
}],
|
|
54
|
-
// ... more actions
|
|
55
|
-
];
|
|
56
|
-
};
|
|
57
|
-
|
|
58
|
-
// src/Events/onRequest.js
|
|
59
|
-
import {getActions} from './actions.js';
|
|
60
|
-
export const handler = async (event) => {
|
|
61
|
-
const actions = getActions({ _meta_actions: [] }); // Initialize meta actions if needed
|
|
62
|
-
for (let [regex, action] of actions) {
|
|
63
|
-
const lastMessage = event.payload.messages[event.payload.messages.length - 1].content;
|
|
64
|
-
const match = lastMessage?.match(regex);
|
|
65
|
-
if (match) return await action(match, event); // Execute matching action
|
|
66
|
-
}
|
|
67
|
-
return { type: 'CONTINUE' }; // Continue to the next handler or LLM
|
|
68
|
-
};
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
// src/Events/onResponse.js
|
|
72
|
-
import {getActions} from './actions.js';
|
|
73
|
-
|
|
74
|
-
export const handler = async (event) => {
|
|
75
|
-
// Example of conditional meta actions based on message count:
|
|
76
|
-
const maxSelfInvokeMessagesCount = 30;
|
|
77
|
-
const actions = getActions({
|
|
78
|
-
_meta_actions: event?.payload?.messages?.length > maxSelfInvokeMessagesCount
|
|
79
|
-
? ["REQUEST_CHAT_MODEL_EXCEEDED"]
|
|
80
|
-
: ["REQUEST_CHAT_MODEL"]
|
|
81
|
-
});
|
|
82
|
-
|
|
83
|
-
for (let [regex, action] of actions) {
|
|
84
|
-
const lastMessage = event.payload.messages[event.payload.messages.length - 1].content;
|
|
85
|
-
const match = lastMessage?.match(regex);
|
|
86
|
-
if (match) return await action(match, event);
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
return { type: 'CONTINUE' }
|
|
90
|
-
};
|
|
91
|
-
|
|
92
|
-
```
|
|
93
|
-
|
|
94
|
-
The `onRequest` and `onResponse` handlers are the core of customizing your OpenKBS agent's behavior. They act as middleware, intercepting messages before they reach the LLM (`onRequest`) and after the LLM generates a response (`onResponse`). This enables you to implement custom logic, interact with external APIs, and control the flow of the conversation.
|
|
95
|
-
|
|
96
|
-
### Example:
|
|
97
|
-
|
|
98
|
-
```javascript
|
|
99
|
-
// src/Events/actions.js
|
|
100
|
-
export const getActions = (meta) => [
|
|
101
|
-
|
|
102
|
-
[/\/?textToImage\("(.*)"\)/, async (match) => {
|
|
103
|
-
const response = await openkbs.textToImage(match[1], { serviceId: 'stability.sd3Medium' });
|
|
104
|
-
const imageSrc = `data:${response.ContentType};base64,${response.base64Data}`;
|
|
105
|
-
return { type: 'SAVED_CHAT_IMAGE', imageSrc, ...meta };
|
|
106
|
-
}],
|
|
107
|
-
|
|
108
|
-
[/\/?googleSearch\("(.*)"\)/, async (match) => {
|
|
109
|
-
const q = match[1];
|
|
110
|
-
const searchParams = match[2] && JSON.parse(match[2]) || {};
|
|
111
|
-
const params = {
|
|
112
|
-
q,
|
|
113
|
-
...searchParams,
|
|
114
|
-
key: '{{secrets.googlesearch_api_key}}',
|
|
115
|
-
cx: '{{secrets.googlesearch_engine_id}}'
|
|
116
|
-
};
|
|
117
|
-
const response = (await axios.get('https://www.googleapis.com/customsearch/v1', { params }))?.data?.items;
|
|
118
|
-
const data = response?.map(({ title, link, snippet, pagemap }) => ({
|
|
119
|
-
title,
|
|
120
|
-
link,
|
|
121
|
-
snippet,
|
|
122
|
-
image: pagemap?.metatags?.[0]?.["og:image"]
|
|
123
|
-
}));
|
|
124
|
-
return { data, ...meta };
|
|
125
|
-
}],
|
|
126
|
-
|
|
127
|
-
[/\/?webpageToText\("(.*)"\)/, async (match) => {
|
|
128
|
-
let response = await openkbs.webpageToText(match[1]);
|
|
129
|
-
if (response?.content?.length > 5000) {
|
|
130
|
-
response.content = response.content.substring(0, 5000);
|
|
131
|
-
}
|
|
132
|
-
return { data: response, ...meta };
|
|
133
|
-
}],
|
|
134
|
-
|
|
135
|
-
[/\/?documentToText\("(.*)"\)/, async (match) => {
|
|
136
|
-
let response = await openkbs.documentToText(match[1]);
|
|
137
|
-
if (response?.text?.length > 5000) {
|
|
138
|
-
response.text = response.text.substring(0, 5000);
|
|
139
|
-
}
|
|
140
|
-
return { data: response, ...meta };
|
|
141
|
-
}],
|
|
142
|
-
|
|
143
|
-
[/\/?imageToText\("(.*)"\)/, async (match) => {
|
|
144
|
-
let response = await openkbs.imageToText(match[1]);
|
|
145
|
-
if (response?.detections?.[0]?.txt) {
|
|
146
|
-
response = { detections: response?.detections?.[0]?.txt };
|
|
147
|
-
}
|
|
148
|
-
return { data: response, ...meta };
|
|
149
|
-
}],
|
|
150
|
-
|
|
151
|
-
[/\/?textToSpeech\("(.*)"\s*,\s*"(.*)"\)/, async (match) => {
|
|
152
|
-
const response = await openkbs.textToSpeech(match[2], {
|
|
153
|
-
languageCode: match[1]
|
|
154
|
-
});
|
|
155
|
-
return { data: response, ...meta };
|
|
156
|
-
}],
|
|
157
|
-
];
|
|
158
|
-
```
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
```javascript
|
|
162
|
-
// src/Events/onRequest.js
|
|
163
|
-
import {getActions} from './actions.js';
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
export const handler = async (event) => {
|
|
167
|
-
const actions = getActions({});
|
|
168
|
-
for (let [regex, action] of actions) {
|
|
169
|
-
const lastMessage = event.payload.messages[event.payload.messages.length - 1].content;
|
|
170
|
-
const match = lastMessage?.match(regex);
|
|
171
|
-
if (match) return await action(match);
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
return { type: 'CONTINUE' }
|
|
175
|
-
};
|
|
176
|
-
```
|
|
177
|
-
|
|
178
|
-
```javascript
|
|
179
|
-
// src/Events/onResponse.js
|
|
180
|
-
import {getActions} from './actions.js';
|
|
181
|
-
|
|
182
|
-
export const handler = async (event) => {
|
|
183
|
-
const actions = getActions({_meta_actions: ["REQUEST_CHAT_MODEL"]});
|
|
184
|
-
|
|
185
|
-
for (let [regex, action] of actions) {
|
|
186
|
-
const lastMessage = event.payload.messages[event.payload.messages.length - 1].content;
|
|
187
|
-
const match = lastMessage?.match(regex);
|
|
188
|
-
if (match) return await action(match);
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
return { type: 'CONTINUE' }
|
|
192
|
-
};
|
|
193
|
-
```
|
|
194
|
-
|
|
195
|
-
### `onPublicAPIRequest` Handler and Public API Integration:
|
|
196
|
-
|
|
197
|
-
The `onPublicAPIRequest` handler serves as a bridge between publicly accessible APIs and your OpenKBS application. This enables external systems, webhooks, or even client-side JavaScript to interact with your application's backend, particularly for storing data in the OpenKBS NoSQL Items service via `openkbs.items`. This is achieved without requiring authentication for these specific API requests.
|
|
198
|
-
|
|
199
|
-
**How it works:**
|
|
200
|
-
|
|
201
|
-
1. **Public API Endpoint:** The `onPublicAPIRequest` handler is associated with a dedicated public API endpoint (e.g., `/publicAPIRequest`). This endpoint can be called directly from any external system without needing to provide an authentication token.
|
|
202
|
-
2. **Payload Structure:** Requests to this endpoint must include a specifically formatted payload in JSON. This payload must contain the following keys:
|
|
203
|
-
* `action`: The action to perform (e.g., "createItem", "updateItem", "deleteItem").
|
|
204
|
-
* `itemType`: The type of item to interact with (as defined in your `settings.json`).
|
|
205
|
-
* `attributes`: An array defining the attributes of the item type (as defined in your `settings.json`).
|
|
206
|
-
* `item`: An object containing the data for the item itself. The keys of this object should correspond to the `attrName` properties defined in the `attributes` array.
|
|
207
|
-
* `kbId`: The ID of the knowledge base.
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
3. **Handler Logic:** Inside the `onPublicAPIRequest` handler, you receive this payload as an argument. Your code then processes the payload and performs the necessary actions using the OpenKBS SDK.
|
|
211
|
-
4. **Data Storage:** The `openkbs.items` function is typically used within this handler to create, update, or delete items in the OpenKBS NoSQL Items service. You can use encryption for sensitive data within this handler.
|
|
212
|
-
5. **Response:** The handler returns a response to the external system that initiated the request.
|
|
213
|
-
|
|
214
|
-
**Example `onPublicAPIRequest` Handler:**
|
|
215
|
-
|
|
216
|
-
```javascript
|
|
217
|
-
// src/Events/onPublicAPIRequest.js
|
|
218
|
-
module.exports = {
|
|
219
|
-
handler: async ({ payload }) => {
|
|
220
|
-
const { item, attributes, itemType, action, kbId } = payload;
|
|
221
|
-
|
|
222
|
-
if (!kbId) return { error: "kbId is not provided" }
|
|
223
|
-
|
|
224
|
-
try {
|
|
225
|
-
const myItem = {};
|
|
226
|
-
for (const attribute of attributes) {
|
|
227
|
-
const { attrName, encrypted } = attribute;
|
|
228
|
-
if (encrypted && item[attrName] !== undefined) {
|
|
229
|
-
myItem[attrName] = await openkbs.encrypt(item[attrName]);
|
|
230
|
-
} else {
|
|
231
|
-
myItem[attrName] = item[attrName];
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
// Perform the action on the Items API
|
|
236
|
-
return await openkbs.items({ action, itemType, attributes, item: myItem, kbId });
|
|
237
|
-
|
|
238
|
-
} catch (error) {
|
|
239
|
-
console.error("Error in onPublicAPIRequest:", error);
|
|
240
|
-
return { error: error.message }; // Return error information
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
};
|
|
244
|
-
|
|
245
|
-
```
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
**Example Client-Side JavaScript to Create an Item:**
|
|
249
|
-
|
|
250
|
-
```javascript
|
|
251
|
-
// Example creating a "feedback" item
|
|
252
|
-
const createFeedback = async (kbId, name, text) => (
|
|
253
|
-
await fetch('https://chat.openkbs.com/publicAPIRequest', {
|
|
254
|
-
method: 'POST',
|
|
255
|
-
headers: { 'Content-Type': 'application/json' },
|
|
256
|
-
body: JSON.stringify({
|
|
257
|
-
action: "createItem",
|
|
258
|
-
kbId,
|
|
259
|
-
itemType: "feedback",
|
|
260
|
-
attributes: [
|
|
261
|
-
{ attrType: "keyword1", attrName: "name", encrypted: true },
|
|
262
|
-
{ attrType: "text1", attrName: "feedbackText", encrypted: false }
|
|
263
|
-
],
|
|
264
|
-
item: { name, feedbackText: text }
|
|
265
|
-
})
|
|
266
|
-
})
|
|
267
|
-
).json();
|
|
268
|
-
```
|
|
269
|
-
|
|
270
|
-
By utilizing `onPublicAPIRequest` and `openkbs.items`, you can build powerful integrations that allow external systems to store and manage data within your OpenKBS application without compromising security. This approach is especially valuable for scenarios like form submissions, webhooks, or any situation where direct, unauthenticated access to data storage is required. Remember to carefully consider security implications and implement necessary precautions.
|
|
271
|
-
|
|
272
|
-
### `onAddMessages` Event Handler:
|
|
273
|
-
|
|
274
|
-
The `onAddMessages` handler allows you to intercept and process messages *as they are added to the chat*. This handler is triggered *after* the `onRequest` handler but *before* the message is sent to the LLM. It's particularly useful for scenarios where a third-party system or service sends messages directly to your OpenKBS application to perform an action.
|
|
275
|
-
|
|
276
|
-
**Example: User moderation:**
|
|
277
|
-
|
|
278
|
-
**1. Third-Party Service API request:**
|
|
279
|
-
|
|
280
|
-
```javascript
|
|
281
|
-
// Example of a third-party system sending a chat message to OpenKBS
|
|
282
|
-
axios.post('https://chat.openkbs.com/', {
|
|
283
|
-
action: "chatAddMessages",
|
|
284
|
-
chatId: 'NSFW_CHAT_ID', // the chat id created to log and process NSFW message
|
|
285
|
-
messages: [{
|
|
286
|
-
role: "system",
|
|
287
|
-
content: JSON.stringify({
|
|
288
|
-
labels: ['adult', 'explicit'],
|
|
289
|
-
fileName: 'image.jpg',
|
|
290
|
-
path: '/uploads/image.jpg'
|
|
291
|
-
}),
|
|
292
|
-
msgId: `${Date.now()}-000000`
|
|
293
|
-
}],
|
|
294
|
-
apiKey: "YOUR_API_KEY",
|
|
295
|
-
kbId: "YOUR_KB_ID"
|
|
296
|
-
}, {
|
|
297
|
-
headers: { 'Content-Type': 'application/json' }
|
|
298
|
-
});
|
|
299
|
-
```
|
|
300
|
-
|
|
301
|
-
**2. `onAddMessages` Handler:**
|
|
302
|
-
|
|
303
|
-
```javascript
|
|
304
|
-
// src/Events/onAddMessages.js
|
|
305
|
-
import * as actions from './actions.js';
|
|
306
|
-
|
|
307
|
-
export const handler = async (event) => {
|
|
308
|
-
const { messages, chatId } = event.payload;
|
|
309
|
-
let msgData;
|
|
310
|
-
|
|
311
|
-
// NSFW Chat Handler
|
|
312
|
-
if (chatId === 'NSFW_CHAT_ID') { // Check if the message is for the NSFW chat
|
|
313
|
-
try {
|
|
314
|
-
msgData = JSON.parse(messages[0].content); // Parse the message content (expecting JSON)
|
|
315
|
-
const { data } = await actions.getUser([null, msgData.kbId]); // Get user information
|
|
316
|
-
await actions.warnAccount([null, data.user.accountId, msgData?.labels]); // Issue a warning
|
|
317
|
-
await actions.deleteFile([null, msgData.path]); // Delete the offending file
|
|
318
|
-
|
|
319
|
-
// Return a system message confirming the action
|
|
320
|
-
return [
|
|
321
|
-
...messages,
|
|
322
|
-
{
|
|
323
|
-
role: 'system',
|
|
324
|
-
msgId: Date.now() + '000000',
|
|
325
|
-
content: `### 👮♀️ System Actions:\nWarning issued and content removed`
|
|
326
|
-
}
|
|
327
|
-
];
|
|
328
|
-
} catch (e) {
|
|
329
|
-
console.error("Error processing NSFW content:", e);
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
return messages; // Return messages unchanged if no action is taken
|
|
334
|
-
};
|
|
335
|
-
|
|
336
|
-
```
|
|
337
|
-
|
|
338
|
-
**Dependencies (onRequest.json, onResponse.json, etc.):**
|
|
339
|
-
|
|
340
|
-
These files specify the NPM package dependencies required for the respective event handlers. They follow the standard `package.json` format.
|
|
341
|
-
|
|
342
|
-
```json
|
|
343
|
-
// src/Events/*.json
|
|
344
|
-
{
|
|
345
|
-
"dependencies": {
|
|
346
|
-
"your-package": "^1.0.0"
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
```
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
### 2. Meta Actions
|
|
353
|
-
|
|
354
|
-
Meta actions provide a way to control the flow of the conversation and instruct the OpenKBS platform to perform specific actions. These actions are typically triggered within the `onResponse` handler based on the LLM's output. Here are some key meta actions:
|
|
355
|
-
|
|
356
|
-
* **`REQUEST_CHAT_MODEL`:** This meta action instructs the platform to send the current conversation to the LLM for a response after the current event handler execution is completed. It's essential for continuing the conversation loop.
|
|
357
|
-
|
|
358
|
-
* **`REQUEST_CHAT_MODEL_EXCEEDED`:** This meta action should be used when the model has exceeded its self-invoke limit. This prevents infinite loops. It can be used in conjunction with the `suggestion` action to provide suggestions to the user without immediately invoking the LLM.
|
|
359
|
-
|
|
360
|
-
* **`SAVED_CHAT_IMAGE`:** This meta action indicates that the LLM generated or processed an image which should be saved in the chat history. It's used in conjunction with actions that process or generate images. Requires the `imageSrc` in the return object.
|
|
361
|
-
|
|
362
|
-
* other meta actions
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
**Example Meta Action Usage:**
|
|
366
|
-
|
|
367
|
-
```javascript
|
|
368
|
-
// src/Events/onResponse.js
|
|
369
|
-
// ... inside an action ...
|
|
370
|
-
if (someCondition) {
|
|
371
|
-
return { type: 'YourAction', ...meta, _meta_actions: ['REQUEST_CHAT_MODEL'] };
|
|
372
|
-
}
|
|
373
|
-
```
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
### 3. Backend SDK (`openkbs` Object)
|
|
377
|
-
|
|
378
|
-
The `openkbs` object provides a set of utility functions and services to interact with the OpenKBS platform and external APIs. It's available within the event handlers. Here are some commonly used functions:
|
|
379
|
-
|
|
380
|
-
* **`openkbs.textToImage(prompt, params)`:** Generates an image from a text prompt using a specified or default image generation service. Returns an object containing the image content type and base64 encoded data.
|
|
381
|
-
|
|
382
|
-
* **`openkbs.speechToText(audioURL, params)`:** Transcribes audio from a URL to text.
|
|
383
|
-
|
|
384
|
-
* **`openkbs.webpageToText(pageURL, params)`:** Extracts text content from a given webpage URL.
|
|
385
|
-
|
|
386
|
-
* **`openkbs.googleSearch(q, params)`:** Performs a Google search using the provided query and parameters.
|
|
387
|
-
|
|
388
|
-
* **`openkbs.documentToText(documentURL, params)`:** Extracts text from various document formats.
|
|
389
|
-
|
|
390
|
-
* **`openkbs.imageToText(imageUrl, params)`:** Extracts text from an image.
|
|
391
|
-
|
|
392
|
-
* **`openkbs.translate(text, to)`:** Translates text to the specified target language.
|
|
393
|
-
|
|
394
|
-
* **`openkbs.detectLanguage(text, params)`:** Detects the language of the provided text.
|
|
395
|
-
|
|
396
|
-
* **`openkbs.textToSpeech(text, params)`:** Converts text to speech. Returns `response.audioContent` which automatically plays in the chat interface.
|
|
397
|
-
|
|
398
|
-
* **`openkbs.encrypt(plaintext)`:** Encrypts data using the provided AES key.
|
|
399
|
-
|
|
400
|
-
* **`openkbs.decrypt(ciphertext)`:** Decrypts data encrypted with the provided AES key.
|
|
401
|
-
|
|
402
|
-
* **`openkbs.items(data)`:** Interacts with the Items API for creating, updating, and deleting items.
|
|
403
|
-
|
|
404
|
-
* **`openkbs.chats(data)`:** Interacts with the Chats API.
|
|
405
|
-
|
|
406
|
-
* **`openkbs.kb(data)`:** Interacts with the Knowledge Base API.
|
|
407
|
-
|
|
408
|
-
* **`openkbs.clientHeaders`:** Exposes client headers for accessing information like IP address, location, etc. (e.g., `openkbs.clientHeaders['x-forwarded-for']`).
|
|
409
|
-
|
|
410
|
-
**Example SDK Usage:**
|
|
411
|
-
|
|
412
|
-
```javascript
|
|
413
|
-
// ... inside an action ...
|
|
414
|
-
const image = await openkbs.textToImage('a cat sitting on a mat');
|
|
415
|
-
// ... use image.base64Data and image.ContentType ...
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
//Encrypt submitted user data
|
|
419
|
-
const encryptedValue = await openkbs.encrypt(userData);
|
|
420
|
-
|
|
421
|
-
```
|
|
422
|
-
|
|
423
|
-
### 4. Application Settings (app/settings.json)
|
|
424
|
-
|
|
425
|
-
This file contains essential configuration settings for the AI agent.
|
|
426
|
-
|
|
427
|
-
```json
|
|
428
|
-
{
|
|
429
|
-
"kbId": "your-kb-id", // Unique Knowledge Base ID
|
|
430
|
-
"userId": "your-user-id", // User ID associated with the application
|
|
431
|
-
"appId": "your-app-id", // Unique Application ID
|
|
432
|
-
"chatVendor": "your-vendor", // Chat service vendor (e.g., openai, anthropic, google, bedrock, azure)
|
|
433
|
-
"kbDescription": "Description of your KB",
|
|
434
|
-
"kbTitle": "Title of your KB",
|
|
435
|
-
"model": "your-llm-model", // LLM model to use
|
|
436
|
-
"inputTools": [ // Input tools to enable (e.g., "speechToText")
|
|
437
|
-
"speechToText"
|
|
438
|
-
],
|
|
439
|
-
"embeddingModel": "your-embedding-model", // Embedding model for semantic search
|
|
440
|
-
"embeddingDimension": 1536, // Dimension of the embedding vectors
|
|
441
|
-
"searchEngine": "your-search-engine", // Search engine to use
|
|
442
|
-
"itemTypes": { }, // Define your custom item types and their attributes
|
|
443
|
-
"slug": "kb-slug", // URL slug for the knowledge base
|
|
444
|
-
"active": true, // Whether the KB is active
|
|
445
|
-
"category": "Category of kb" // Category of the knowledge base
|
|
446
|
-
}
|
|
447
|
-
```
|
|
448
|
-
|
|
449
|
-
### 5. LLM Instructions (app/instructions.txt)
|
|
450
|
-
|
|
451
|
-
This file contains the instructions provided to the LLM, guiding its behavior and interaction with the custom functionalities implemented through the backend framework. The clearer and more specific the instructions, the more effectively the LLM will utilize the provided actions and commands. Include examples of how to use the actions defined in `actions.js`, demonstrating both successful and unsuccessful executions. Use clear and concise language, focusing on the specific tasks the LLM should perform. Explain the expected format of commands and responses.
|
|
452
|
-
|
|
453
|
-
**Example Instructions:**
|
|
454
|
-
|
|
455
|
-
```
|
|
456
|
-
You are an AI assistant designed to automate WooCommerce tasks.
|
|
457
|
-
|
|
458
|
-
You can execute the following commands:
|
|
459
|
-
|
|
460
|
-
* `/googleSearch("your query")`: Performs a Google search and returns the results.
|
|
461
|
-
* `/webpageToText("url")`: Extracts text content from a webpage.
|
|
462
|
-
// ... other commands
|
|
463
|
-
Use backticks for meta commands (commands that are not part of the user request or LLM output)
|
|
464
|
-
|
|
465
|
-
```
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
### 6. Execution Environment: Predefined Objects and Utilities
|
|
469
|
-
|
|
470
|
-
The OpenKBS backend provides a pre-configured execution environment for your event handlers, including a set of globally available objects and libraries. This eliminates the need to explicitly declare these as dependencies in your `onRequest.json` or `onResponse.json` files. These predefined resources facilitate various operations, from interacting with AWS services to manipulating data and making HTTP requests.
|
|
471
|
-
|
|
472
|
-
Here's a breakdown of the key objects and utilities available within the OpenKBS backend environment:
|
|
473
|
-
|
|
474
|
-
**Key Objects and Utilities:**
|
|
475
|
-
|
|
476
|
-
* **`openkbs`:** The OpenKBS SDK, documented previously, provides utility functions for interacting with the OpenKBS platform and various external services.
|
|
477
|
-
|
|
478
|
-
* **`AWS: AWS_SDK`:** The AWS SDK provides access to a wide range of AWS services
|
|
479
|
-
|
|
480
|
-
* **`axios`:** Powerful HTTP client for making requests to external APIs and services. Simplifies handling responses and errors compared to the built-in `https` module.
|
|
481
|
-
|
|
482
|
-
* **`cheerio`:** A fast and flexible HTML parser implemented on top of the `parse5` parser. Enables server-side DOM manipulation and data extraction from HTML content.
|
|
483
|
-
|
|
484
|
-
* **`Decimal`:** The Decimal.js library enables arbitrary-precision decimal arithmetic, avoiding floating-point inaccuracies common in JavaScript.
|
|
485
|
-
|
|
486
|
-
* **`crypto`:** Node.js crypto module for performing cryptographic operations like hashing, encryption, and decryption.
|
|
487
|
-
|
|
488
|
-
* **`jwt`:** The `jsonwebtoken` library provides functions for creating, signing, and verifying JSON Web Tokens (JWTs), essential for secure authentication and authorization.
|
|
489
|
-
|
|
490
|
-
* **`JSON5`:** A more permissive JSON parser that supports comments, trailing commas, single quotes, and other convenient features not found in standard JSON. Useful for parsing configuration files or user input.
|
|
491
|
-
|
|
492
|
-
## Frontend
|
|
493
|
-
|
|
494
|
-
The OpenKBS frontend framework is built using React and provides a flexible and extensible platform for building custom chat interfaces. It allows developers to customize the appearance and behavior of the chat through a `contentRender` module, which can be dynamically loaded and used to extend the core platform.
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
### 1. Frontend Module Loading
|
|
498
|
-
|
|
499
|
-
The frontend framework dynamically loads the `contentRender.js` module. This module can export several functions and components to customize the chat interface. The framework uses a global variable called `window.contentRender` to access the functions exported by this module.
|
|
500
|
-
|
|
501
|
-
### 2. `contentRender.js` and `contentRender.json`
|
|
502
|
-
|
|
503
|
-
The `contentRender.js` file is the heart of frontend customization. It can export several key functions:
|
|
504
|
-
|
|
505
|
-
- **`onRenderChatMessage(params)`:** This function is called every time a chat message is rendered. It receives an object with various parameters, including:
|
|
506
|
-
- `msgIndex`: The index of the message being rendered.
|
|
507
|
-
- `messages`: The entire array of chat messages.
|
|
508
|
-
- `setMessages`: A function to update the `messages` state.
|
|
509
|
-
- `iframeRef`: A reference to the iframe element.
|
|
510
|
-
- `KB`: The Knowledge Base object containing application settings.
|
|
511
|
-
- `chatContainerRef`: A reference to the chat container element.
|
|
512
|
-
- `RequestChatAPI`: A function to send a message to the chat API.
|
|
513
|
-
- `setSystemAlert`: A function to display system alerts.
|
|
514
|
-
- `setBlockingLoading`: A function to display a loading indicator.
|
|
515
|
-
- `blockingLoading`: A boolean indicating if the loading indicator is active.
|
|
516
|
-
- `sendButtonRef`: A reference to the send button element.
|
|
517
|
-
- `sendButtonRippleRef`: A reference to the send button ripple effect.
|
|
518
|
-
- `setInputValue`: A function to set the value of the input field.
|
|
519
|
-
- `isStreaming`: Returns true if LLM is still generating chat tokens
|
|
520
|
-
- `renderSettings`: An object containing rendering settings.
|
|
521
|
-
- `axios`: The axios library for making HTTP requests.
|
|
522
|
-
- `itemsAPI`: Functions for manipulating KB items.
|
|
523
|
-
- `createEmbeddingItem`: Functions to create embeddings.
|
|
524
|
-
- `indexedDB`: IndexedDB wrapper to access data.
|
|
525
|
-
- `chatAPI`: API to access chat data.
|
|
526
|
-
- `generateMsgId`: Generates a unique message ID.
|
|
527
|
-
- `kbUserData`: Function to get KB user data.
|
|
528
|
-
- `executeNodejs`: Execute custom JavaScript code inside a VM.
|
|
529
|
-
|
|
530
|
-
This function should return a React component representing the rendered message. If not defined, the default rendering mechanism is used.
|
|
531
|
-
|
|
532
|
-
- **`Header(props)`:** This React component is rendered at the top of the chat interface. It receives the same `params` object as `onRenderChatMessage`. It can be used to add custom UI elements or controls to the chat header. If not defined, the standard OpenKBS chat header is displayed.
|
|
533
|
-
|
|
534
|
-
- **`onDeleteChatMessage(params)`:** This async function is triggered when a chat message is deleted. This function receives a `params` object similar to the `onRenderChatMessage` function but also includes `chatId`, `message` (the message being deleted), and can be used to perform cleanup actions related to custom rendered content. If not defined, a default delete message function is executed.
|
|
535
|
-
|
|
536
|
-
**Example `contentRender.js`:**
|
|
537
|
-
|
|
538
|
-
```javascript
|
|
539
|
-
import React from 'react';
|
|
540
|
-
|
|
541
|
-
const onRenderChatMessage = async (params) => {
|
|
542
|
-
const { content, role } = params.messages[params.msgIndex];
|
|
543
|
-
if (role === 'assistant' && content.startsWith('```json')) {
|
|
544
|
-
try {
|
|
545
|
-
const jsonData = JSON.parse(content.replace('```json', '').replace('```', ''));
|
|
546
|
-
return <pre>{JSON.stringify(jsonData, null, 2)}</pre>;
|
|
547
|
-
} catch (e) {
|
|
548
|
-
console.error('Error parsing JSON:', e);
|
|
549
|
-
return null;
|
|
550
|
-
}
|
|
551
|
-
}
|
|
552
|
-
};
|
|
553
|
-
|
|
554
|
-
const Header = ({ setRenderSettings }) => {
|
|
555
|
-
// Custom header content
|
|
556
|
-
return (
|
|
557
|
-
<div>
|
|
558
|
-
<h1>Custom Chat Header</h1>
|
|
559
|
-
</div>
|
|
560
|
-
);
|
|
561
|
-
};
|
|
562
|
-
|
|
563
|
-
const onDeleteChatMessage = async (params) => {
|
|
564
|
-
// Perform cleanup or other actions on chat message delete
|
|
565
|
-
const { chatId, message, itemsAPI, KB, setBlockingLoading } = params;
|
|
566
|
-
// Perform action before the message is deleted
|
|
567
|
-
};
|
|
568
|
-
|
|
569
|
-
const exports = { onRenderChatMessage, Header, onDeleteChatMessage };
|
|
570
|
-
window.contentRender = exports;
|
|
571
|
-
export default exports;
|
|
572
|
-
```
|
|
573
|
-
|
|
574
|
-
`contentRender.json` specifies the dependencies required for the `contentRender.js` module. It's structured like a standard `package.json` file.
|
|
575
|
-
|
|
576
|
-
```json
|
|
577
|
-
{
|
|
578
|
-
"dependencies": {
|
|
579
|
-
"react": "^18.2.0 (fixed)",
|
|
580
|
-
"react-dom": "^18.2.0 (fixed)",
|
|
581
|
-
"@mui/material": "^5.16.1 (fixed)",
|
|
582
|
-
"@mui/icons-material": "^5.16.1 (fixed)",
|
|
583
|
-
"@emotion/react": "^11.10.6 (fixed)",
|
|
584
|
-
"@emotion/styled": "^11.10.6 (fixed)"
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
```
|
|
588
|
-
|
|
589
|
-
### Fixed Dependencies
|
|
590
|
-
|
|
591
|
-
The dependencies marked as `(fixed)` are not installed as additional dependencies but are inherited from the base framework `openkbs-ui`. This ensures consistency across applications and reduces the need for redundant installations. These fixed dependencies include:
|
|
592
|
-
|
|
593
|
-
- **`react` and `react-dom`:** Core libraries for building user interfaces with React.
|
|
594
|
-
- **`@mui/material` and `@mui/icons-material`:** Material-UI components and icons for building modern, responsive UIs.
|
|
595
|
-
- **`@emotion/react` and `@emotion/styled`:** Libraries for writing CSS styles with JavaScript, used by Material-UI for styling components.
|
|
596
|
-
|
|
597
|
-
### 3. Common Frontend Components and Utilities
|
|
598
|
-
|
|
599
|
-
These components and utilities are accessible directly within your `onRenderChatMessage` function, streamlining your custom development process.
|
|
600
|
-
|
|
601
|
-
### msgIndex
|
|
602
|
-
```javascript
|
|
603
|
-
const onRenderChatMessage = async (params) => {
|
|
604
|
-
const { msgIndex, messages } = params;
|
|
605
|
-
console.log(`Rendering message at index: ${msgIndex}`);
|
|
606
|
-
const currentMessage = messages[msgIndex];
|
|
607
|
-
// Further processing...
|
|
608
|
-
};
|
|
609
|
-
```
|
|
610
|
-
|
|
611
|
-
### messages
|
|
612
|
-
```javascript
|
|
613
|
-
const onRenderChatMessage = async (params) => {
|
|
614
|
-
const { messages } = params;
|
|
615
|
-
messages.forEach((message, index) => {
|
|
616
|
-
console.log(`Message ${index}: ${message.content}`);
|
|
617
|
-
});
|
|
618
|
-
// Further processing...
|
|
619
|
-
};
|
|
620
|
-
```
|
|
621
|
-
|
|
622
|
-
### setMessages
|
|
623
|
-
```javascript
|
|
624
|
-
const onRenderChatMessage = async (params) => {
|
|
625
|
-
const { setMessages, messages } = params;
|
|
626
|
-
const newMessage = { content: "New message", role: "user" };
|
|
627
|
-
setMessages([...messages, newMessage]);
|
|
628
|
-
};
|
|
629
|
-
```
|
|
630
|
-
|
|
631
|
-
### KB
|
|
632
|
-
```javascript
|
|
633
|
-
const onRenderChatMessage = async (params) => {
|
|
634
|
-
const { KB } = params;
|
|
635
|
-
console.log(`Knowledge Base ID: ${KB.kbId}`);
|
|
636
|
-
// Use KB settings...
|
|
637
|
-
};
|
|
638
|
-
```
|
|
639
|
-
|
|
640
|
-
### chatContainerRef
|
|
641
|
-
```javascript
|
|
642
|
-
const onRenderChatMessage = async (params) => {
|
|
643
|
-
const { chatContainerRef } = params;
|
|
644
|
-
if (chatContainerRef.current) {
|
|
645
|
-
// ...
|
|
646
|
-
}
|
|
647
|
-
};
|
|
648
|
-
```
|
|
649
|
-
|
|
650
|
-
### RequestChatAPI
|
|
651
|
-
```javascript
|
|
652
|
-
const onRenderChatMessage = async (params) => {
|
|
653
|
-
const { RequestChatAPI, messages } = params;
|
|
654
|
-
const newMessage = { role: "user", content: "Hello, world!" };
|
|
655
|
-
await RequestChatAPI([...messages, newMessage]);
|
|
656
|
-
};
|
|
657
|
-
```
|
|
658
|
-
|
|
659
|
-
### setSystemAlert
|
|
660
|
-
```javascript
|
|
661
|
-
const onRenderChatMessage = async (params) => {
|
|
662
|
-
const { setSystemAlert } = params;
|
|
663
|
-
setSystemAlert({ msg: "This is a system alert", type: "info", duration: 3000 });
|
|
664
|
-
};
|
|
665
|
-
```
|
|
666
|
-
|
|
667
|
-
### setBlockingLoading
|
|
668
|
-
```javascript
|
|
669
|
-
const onRenderChatMessage = async (params) => {
|
|
670
|
-
const { setBlockingLoading } = params;
|
|
671
|
-
setBlockingLoading(true);
|
|
672
|
-
// Perform some async operation...
|
|
673
|
-
setBlockingLoading(false);
|
|
674
|
-
};
|
|
675
|
-
```
|
|
676
|
-
|
|
677
|
-
### blockingLoading
|
|
678
|
-
```javascript
|
|
679
|
-
const onRenderChatMessage = async (params) => {
|
|
680
|
-
const { blockingLoading } = params;
|
|
681
|
-
if (blockingLoading) {
|
|
682
|
-
console.log("Loading is currently active");
|
|
683
|
-
}
|
|
684
|
-
};
|
|
685
|
-
```
|
|
686
|
-
|
|
687
|
-
### sendButtonRef
|
|
688
|
-
```javascript
|
|
689
|
-
const onRenderChatMessage = async (params) => {
|
|
690
|
-
const { sendButtonRef } = params;
|
|
691
|
-
if (sendButtonRef.current) {
|
|
692
|
-
sendButtonRef.current.disabled = true; // Disable the send button
|
|
693
|
-
}
|
|
694
|
-
};
|
|
695
|
-
```
|
|
696
|
-
|
|
697
|
-
### sendButtonRippleRef
|
|
698
|
-
```javascript
|
|
699
|
-
const onRenderChatMessage = async (params) => {
|
|
700
|
-
const { sendButtonRippleRef } = params;
|
|
701
|
-
if (sendButtonRippleRef.current) {
|
|
702
|
-
sendButtonRippleRef.current.pulsate(); // Trigger ripple effect
|
|
703
|
-
}
|
|
704
|
-
};
|
|
705
|
-
```
|
|
706
|
-
|
|
707
|
-
### setInputValue
|
|
708
|
-
```javascript
|
|
709
|
-
const onRenderChatMessage = async (params) => {
|
|
710
|
-
const { setInputValue } = params;
|
|
711
|
-
setInputValue("Pre-filled input value");
|
|
712
|
-
};
|
|
713
|
-
```
|
|
714
|
-
|
|
715
|
-
### renderSettings
|
|
716
|
-
```javascript
|
|
717
|
-
const onRenderChatMessage = async (params) => {
|
|
718
|
-
const { renderSettings } = params;
|
|
719
|
-
console.log(`Current render settings: ${JSON.stringify(renderSettings)}`);
|
|
720
|
-
};
|
|
721
|
-
```
|
|
722
|
-
|
|
723
|
-
### axios
|
|
724
|
-
```javascript
|
|
725
|
-
const onRenderChatMessage = async (params) => {
|
|
726
|
-
const { axios } = params;
|
|
727
|
-
const response = await axios.get("https://api.example.com/data");
|
|
728
|
-
console.log(response.data);
|
|
729
|
-
};
|
|
730
|
-
```
|
|
731
|
-
|
|
732
|
-
### itemsAPI
|
|
733
|
-
```javascript
|
|
734
|
-
const onRenderChatMessage = async (params) => {
|
|
735
|
-
const { itemsAPI } = params;
|
|
736
|
-
const item = await itemsAPI.getItem("itemId");
|
|
737
|
-
console.log(`Fetched item: ${JSON.stringify(item)}`);
|
|
738
|
-
};
|
|
739
|
-
```
|
|
740
|
-
|
|
741
|
-
### indexedDB
|
|
742
|
-
```javascript
|
|
743
|
-
const onRenderChatMessage = async (params) => {
|
|
744
|
-
const { indexedDB } = params;
|
|
745
|
-
const items = await indexedDB.db["items"].toArray();
|
|
746
|
-
console.log(`IndexedDB items: ${JSON.stringify(items)}`);
|
|
747
|
-
};
|
|
748
|
-
```
|
|
749
|
-
|
|
750
|
-
### generateMsgId
|
|
751
|
-
```javascript
|
|
752
|
-
const onRenderChatMessage = async (params) => {
|
|
753
|
-
const { generateMsgId } = params;
|
|
754
|
-
const newMsgId = generateMsgId();
|
|
755
|
-
console.log(`Generated message ID: ${newMsgId}`);
|
|
756
|
-
};
|
|
757
|
-
```
|
|
758
|
-
|
|
759
|
-
### kbUserData
|
|
760
|
-
```javascript
|
|
761
|
-
const onRenderChatMessage = async (params) => {
|
|
762
|
-
const { kbUserData } = params;
|
|
763
|
-
const userData = kbUserData();
|
|
764
|
-
console.log(`User data: ${JSON.stringify(userData)}`);
|
|
765
|
-
};
|
|
766
|
-
```
|