@minded-ai/mindedjs 3.1.31 → 3.1.32

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 (37) hide show
  1. package/dist/agent.d.ts +3 -0
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +20 -0
  4. package/dist/agent.js.map +1 -1
  5. package/dist/index.d.ts +4 -1
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +5 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/platform/mindedConnectionTypes.d.ts +152 -0
  10. package/dist/platform/mindedConnectionTypes.d.ts.map +1 -1
  11. package/dist/platform/mindedConnectionTypes.js +4 -0
  12. package/dist/platform/mindedConnectionTypes.js.map +1 -1
  13. package/dist/toolsLibrary/knowledgeBase.d.ts +123 -0
  14. package/dist/toolsLibrary/knowledgeBase.d.ts.map +1 -0
  15. package/dist/toolsLibrary/knowledgeBase.js +180 -0
  16. package/dist/toolsLibrary/knowledgeBase.js.map +1 -0
  17. package/dist/utils/rag.d.ts +16 -0
  18. package/dist/utils/rag.d.ts.map +1 -0
  19. package/dist/utils/rag.js +206 -0
  20. package/dist/utils/rag.js.map +1 -0
  21. package/docs/SUMMARY.md +8 -2
  22. package/docs/api/analytics.md +132 -0
  23. package/docs/api/knowledge.md +460 -0
  24. package/docs/api/overview.md +78 -0
  25. package/docs/platform/knowledge-bases.md +191 -0
  26. package/docs/platform/security-architecture.md +0 -1
  27. package/docs/sdk/agent-api.md +12 -0
  28. package/docs/sdk/events.md +77 -24
  29. package/docs/sdk/knowledge-base-rag.md +211 -0
  30. package/docs/sdk/vectorstore-query.md +2 -0
  31. package/package.json +1 -1
  32. package/src/agent.ts +33 -2
  33. package/src/index.ts +21 -1
  34. package/src/platform/mindedConnectionTypes.ts +162 -0
  35. package/src/toolsLibrary/knowledgeBase.ts +217 -0
  36. package/src/utils/rag.ts +252 -0
  37. package/docs/platform/api.md +0 -258
@@ -0,0 +1,191 @@
1
+ # Knowledge Bases
2
+
3
+ Knowledge bases let you upload documents (with metadata), keep them synced per environment, and query them at runtime from your agent.
4
+
5
+ ## Concepts
6
+
7
+ - **Knowledge base**: A named container of documents that belongs to a specific agent.
8
+ - **Document**: A file (PDF, TXT, DOCX, etc.) plus optional metadata used for filtering.
9
+ - **Environment**: Separate datasets per environment: `development`, `staging`, `production`.
10
+
11
+ ## Manage knowledge bases in the platform (UI)
12
+
13
+ ### Create a knowledge base
14
+
15
+ 1. Open your agent in the Minded dashboard
16
+ 2. Navigate to **Knowledge Bases**
17
+ 3. Click **Create knowledge base**
18
+ 4. Set a **name** (and optional description) and save
19
+
20
+ ### Update a knowledge base
21
+
22
+ You can update a knowledge base’s **name** and **description** from the knowledge base settings/details view.
23
+
24
+ ### Delete a knowledge base
25
+
26
+ Deleting a knowledge base removes it from the agent and triggers cleanup of its documents across environments.
27
+
28
+ ## Upload and manage documents (UI)
29
+
30
+ From the knowledge base view, you can upload documents and set metadata for filtering.
31
+
32
+ Typical flow:
33
+
34
+ - Upload a document (and optionally add metadata)
35
+ - Wait for ingestion/sync to complete
36
+ - Use the platform “Query” / “Generate” actions to test retrieval and citations
37
+
38
+ ## Manage documents via API
39
+
40
+ For programmatic document management (upload, update, metadata, delete), use the Knowledge API:
41
+
42
+ - Base URL: `https://api.minded.com/api/v1`
43
+ - Scope required: `knowledge-management`
44
+
45
+ See the full reference in [Knowledge API](../api/knowledge.md).
46
+
47
+ ## Platform knowledge APIs (advanced)
48
+
49
+ These endpoints are used by the Minded dashboard. They are helpful for internal automation and debugging.
50
+
51
+ > **Note:** The dashboard APIs are not the same as the customer-facing `/api/v1/*` APIs. They require dashboard authentication and are mounted under the dashboard service.
52
+
53
+ ### Knowledge base CRUD
54
+
55
+ All routes are scoped to an agent via `:agentId`.
56
+
57
+ - **List knowledge bases**
58
+ - **GET** `/dashboard/agents/:agentId/knowledge/bases`
59
+ - **Create a knowledge base**
60
+ - **POST** `/dashboard/agents/:agentId/knowledge/bases`
61
+ - Body:
62
+ ```json
63
+ {
64
+ "name": "Support KB",
65
+ "description": "Policies and FAQs"
66
+ }
67
+ ```
68
+ - **Get a knowledge base**
69
+ - **GET** `/dashboard/agents/:agentId/knowledge/bases/:knowledgeBaseId`
70
+ - **Update a knowledge base**
71
+ - **PATCH** `/dashboard/agents/:agentId/knowledge/bases/:knowledgeBaseId`
72
+ - Body:
73
+ ```json
74
+ {
75
+ "name": "Support KB (v2)",
76
+ "description": "Updated description"
77
+ }
78
+ ```
79
+ - **Delete a knowledge base**
80
+ - **DELETE** `/dashboard/agents/:agentId/knowledge/bases/:knowledgeBaseId`
81
+
82
+ ### Query and generate (platform testing endpoints)
83
+
84
+ These endpoints are commonly used by the dashboard UI to test retrieval and “retrieve + generate”.
85
+
86
+ - **Retrieve only**
87
+ - **POST** `/dashboard/agents/:agentId/knowledge/:environment/kb/:knowledgeBaseId/query`
88
+ - Body:
89
+ ```json
90
+ {
91
+ "query": "What is the refund policy?",
92
+ "numberOfResults": 5
93
+ }
94
+ ```
95
+
96
+ - **Retrieve and generate (with citations)**
97
+ - **POST** `/dashboard/agents/:agentId/knowledge/:environment/kb/:knowledgeBaseId/generate`
98
+ - Body:
99
+ ```json
100
+ {
101
+ "query": "Summarize the refund policy",
102
+ "numberOfResults": 5,
103
+ "modelArn": "optional-model-identifier",
104
+ "filters": {
105
+ "equals": { "key": "category", "value": "policy" }
106
+ }
107
+ }
108
+ ```
109
+
110
+ If you want to query from agent code (recommended for runtime usage), use the SDK methods documented in [Knowledge Base RAG API](../sdk/knowledge-base-rag.md).
111
+
112
+ ## Enable knowledge base usage in an agent
113
+
114
+ There are two common patterns: **automatic default retrieval** configured from the platform, and **manual retrieval** from code.
115
+
116
+ ### Option A: Automatic default retrieval (platform configuration)
117
+
118
+ The platform can configure “RAG defaults” for your agent. When enabled, MindedJS will:
119
+
120
+ - Run retrieval automatically **after `TRIGGER_EVENT`**
121
+ - Retrieve from one or more configured knowledge bases
122
+ - Filter by `minScore` (if provided)
123
+ - Inject the retrieved context into the conversation as a **system message**
124
+
125
+ #### Default retrieval settings
126
+
127
+ Default retrieval is configured **per environment** (`development`, `staging`, `production`). Each environment can include:
128
+
129
+ - `enabled`: turn default retrieval on/off
130
+ - `knowledgeBases`: list of knowledge bases to query on every trigger
131
+ - `knowledgeBaseId`: the KB ID to query
132
+ - `environment` (optional): override which KB environment to query (defaults to the current environment)
133
+ - `numberOfResults` (optional): how many chunks to retrieve
134
+ - `minScore` (optional): discard results below this similarity score threshold
135
+ - `filters` (optional): metadata filters applied to retrieval
136
+
137
+ #### Filter operators and templating
138
+
139
+ Default retrieval filters support these operators:
140
+
141
+ - `equals`
142
+ - `notEquals`
143
+ - `greaterThan`
144
+ - `lessThan`
145
+
146
+ Filter values can be either:
147
+
148
+ - A **plain string** (example: `"policy"`)
149
+ - A **memory chip pattern** in the exact form: `{state.memory.<path>}`
150
+ - Example: `{state.memory.language}`
151
+ - Nested values are supported with dot notation: `{state.memory.user.locale}`
152
+ - If the memory value is missing (`null`/`undefined`), that filter entry is **skipped**
153
+
154
+ Multiple filter entries are combined with **AND** semantics.
155
+
156
+ #### Example default retrieval configuration
157
+
158
+ This is an example of the underlying shape (shown here for clarity; in practice it’s configured via the platform UI):
159
+
160
+ ```json
161
+ {
162
+ "production": {
163
+ "enabled": true,
164
+ "knowledgeBases": [
165
+ {
166
+ "knowledgeBaseId": "kb-abc123",
167
+ "numberOfResults": 5,
168
+ "minScore": 0.6,
169
+ "filters": [
170
+ { "key": "category", "operator": "equals", "value": "policy" },
171
+ { "key": "language", "operator": "equals", "value": "{state.memory.language}" }
172
+ ]
173
+ }
174
+ ]
175
+ }
176
+ }
177
+ ```
178
+
179
+ ### Option B: Manual retrieval from code (e.g., in `TRIGGER_EVENT`)
180
+
181
+ If you need full control over _when_ retrieval happens and _how_ results are applied, you can:
182
+
183
+ Import directly from the SDK:
184
+
185
+ - `retrieveFromKnowledgeBase(...)`
186
+ - `retrieveAndGenerateFromKnowledgeBase(...)`
187
+
188
+ See:
189
+
190
+ - [Knowledge Base RAG API](../sdk/knowledge-base-rag.md)
191
+ - [Events → TRIGGER_EVENT](../sdk/events.md#trigger_event) (includes an example of querying a knowledge base during trigger qualification)
@@ -316,7 +316,6 @@ For more information on related security and operational topics, see:
316
316
  - **[Secrets Management](secrets.md)** - Detailed guide on storing and managing credentials securely
317
317
  - **[Operator Documentation](operator.md)** - Operational procedures and best practices for running agents
318
318
  - **[On-Premise Deployment](on-prem.md)** - Security considerations for self-hosted Minded installations
319
- - **[Browser Task (RPA)](browserTask.md)** - Technical details on RPA capabilities and configurations
320
319
 
321
320
  ---
322
321
 
@@ -218,6 +218,18 @@ await agent.compiledGraph.updateState(agent.getLangraphConfig(sessionId), {
218
218
  });
219
219
  ```
220
220
 
221
+ ### Knowledge Base RAG
222
+
223
+ You can query knowledge bases directly from code by importing the RAG utilities:
224
+
225
+ ```typescript
226
+ import { retrieveFromKnowledgeBase, retrieveAndGenerateFromKnowledgeBase } from '@minded-ai/mindedjs';
227
+ ```
228
+
229
+ These functions are useful when you want full control over retrieval timing (for example in `TRIGGER_EVENT`) and how the retrieved context is applied.
230
+
231
+ See [Knowledge Base RAG API](./knowledge-base-rag.md) for function signatures, filtering, and citations.
232
+
221
233
  ## State Management Best Practices
222
234
 
223
235
  ### 1. Partial Updates
@@ -16,6 +16,7 @@ All events provide access to `state.history`, an array of `HistoryStep` objects
16
16
  - `messageIds`: Associated message IDs
17
17
 
18
18
  Additional fields:
19
+
19
20
  - `APP_TRIGGER_NODE`: `appName` identifies source application
20
21
  - `TOOL_NODE`: Contains tool input/output information
21
22
 
@@ -23,9 +24,7 @@ Additional fields:
23
24
 
24
25
  ```typescript
25
26
  agent.on(events.AI_MESSAGE, async ({ state }) => {
26
- const triggerStep = state.history.find((step) =>
27
- step.type === 'TRIGGER_NODE' || step.type === 'APP_TRIGGER_NODE'
28
- );
27
+ const triggerStep = state.history.find((step) => step.type === 'TRIGGER_NODE' || step.type === 'APP_TRIGGER_NODE');
29
28
  const toolSteps = state.history.filter((step) => step.type === 'TOOL_NODE');
30
29
  console.log(`Trigger: ${triggerStep?.nodeDisplayName}, Tools used: ${toolSteps.length}`);
31
30
  });
@@ -36,6 +35,7 @@ agent.on(events.AI_MESSAGE, async ({ state }) => {
36
35
  Emitted when agent's graph state is initialized (new session begins).
37
36
 
38
37
  **Input:**
38
+
39
39
  ```typescript
40
40
  {
41
41
  state: {
@@ -51,6 +51,7 @@ Emitted when agent's graph state is initialized (new session begins).
51
51
  **Return:** `void` (handlers for side effects only)
52
52
 
53
53
  **Example:**
54
+
54
55
  ```typescript
55
56
  agent.on(events.INIT, async ({ state }) => {
56
57
  await initializeSessionResources(state.sessionId);
@@ -68,6 +69,7 @@ agent.on(events.INIT, async ({ state }) => {
68
69
  Emitted when AI generates a message for the user.
69
70
 
70
71
  **Input:**
72
+
71
73
  ```typescript
72
74
  {
73
75
  message: string;
@@ -83,14 +85,17 @@ Emitted when AI generates a message for the user.
83
85
  **Return:** `void` (handlers for side effects only)
84
86
 
85
87
  **Example:**
88
+
86
89
  ```typescript
87
90
  agent.on(events.AI_MESSAGE, async ({ message, state }) => {
88
91
  await sendMessageToUser(message, state.sessionId);
89
- await websocket.send(JSON.stringify({
90
- type: 'ai_message',
91
- content: message,
92
- sessionId: state.sessionId
93
- }));
92
+ await websocket.send(
93
+ JSON.stringify({
94
+ type: 'ai_message',
95
+ content: message,
96
+ sessionId: state.sessionId,
97
+ }),
98
+ );
94
99
  });
95
100
  ```
96
101
 
@@ -101,11 +106,12 @@ agent.on(events.AI_MESSAGE, async ({ message, state }) => {
101
106
  Emitted when a trigger node is executed. Allows qualifying triggers and modifying state before processing.
102
107
 
103
108
  **Input:**
109
+
104
110
  ```typescript
105
111
  {
106
112
  triggerName: string;
107
113
  triggerBody: any;
108
- state: State<Memory>; // Current state (can be modified by reference)
114
+ state: State<Memory>; // Current state (can be modified by reference)
109
115
  }
110
116
  ```
111
117
 
@@ -114,6 +120,7 @@ Emitted when a trigger node is executed. Allows qualifying triggers and modifyin
114
120
  **Important:** State is modified by reference (v2.0). Modify `state` directly, don't return state updates.
115
121
 
116
122
  **Return patterns:**
123
+
117
124
  ```typescript
118
125
  // Qualify
119
126
  return { isQualified: true };
@@ -136,6 +143,43 @@ agent.on(events.TRIGGER_EVENT, async ({ triggerBody, state }) => {
136
143
  });
137
144
  ```
138
145
 
146
+ ```typescript
147
+ // Query a knowledge base during trigger qualification
148
+ //
149
+ // Use this pattern when you want full control over *when* retrieval happens
150
+ // and *how* the retrieved context is applied to the conversation.
151
+ import { SystemMessage } from '@langchain/core/messages';
152
+ import { v4 as uuidv4 } from 'uuid';
153
+ import { retrieveFromKnowledgeBase } from '@minded-ai/mindedjs';
154
+
155
+ agent.on(events.TRIGGER_EVENT, async ({ triggerBody, state }) => {
156
+ const query = typeof triggerBody?.content === 'string' ? triggerBody.content : JSON.stringify(triggerBody);
157
+
158
+ // knowledgeBaseId is optional - backend auto-selects if agent has exactly 1 KB
159
+ // Pass knowledgeBaseId explicitly if you have multiple KBs
160
+ const { retrievalResults } = await retrieveFromKnowledgeBase({
161
+ environment: 'production',
162
+ query,
163
+ numberOfResults: 5,
164
+ });
165
+
166
+ if (retrievalResults.length > 0) {
167
+ const context = retrievalResults.map((r) => `#### ${r.location.s3Location.uri}\n${r.content.text}`).join('\n\n');
168
+
169
+ state.messages.push(
170
+ new SystemMessage({
171
+ id: uuidv4(),
172
+ content: `### Knowledge Base Context\n\n${context}`,
173
+ }),
174
+ );
175
+ }
176
+
177
+ return { isQualified: true };
178
+ });
179
+ ```
180
+
181
+ > **Tip:** If you want retrieval to happen automatically after `TRIGGER_EVENT`, enable “default retrieval” from the platform. See [Knowledge Bases](../platform/knowledge-bases.md#enable-knowledge-base-usage-in-an-agent).
182
+
139
183
  > **Note:** `goto` jump occurs after current invocation completes.
140
184
 
141
185
  **Use cases:** Input validation, data transformation, context setting, access control, routing logic
@@ -145,6 +189,7 @@ agent.on(events.TRIGGER_EVENT, async ({ triggerBody, state }) => {
145
189
  Emitted when an error occurs during execution. Control whether error is thrown or caught.
146
190
 
147
191
  **Input:**
192
+
148
193
  ```typescript
149
194
  {
150
195
  error: Error;
@@ -153,21 +198,23 @@ Emitted when an error occurs during execution. Control whether error is thrown o
153
198
  ```
154
199
 
155
200
  **Return:**
201
+
156
202
  ```typescript
157
203
  {
158
- throwError: boolean; // true = throw error and stop, false = catch and continue
204
+ throwError: boolean; // true = throw error and stop, false = catch and continue
159
205
  }
160
206
  ```
161
207
 
162
208
  **Important:** State is modified by reference (v2.0).
163
209
 
164
210
  **Example:**
211
+
165
212
  ```typescript
166
213
  agent.on(events.ERROR, async ({ error, state }) => {
167
214
  await logger.error({
168
215
  message: 'Agent execution error',
169
216
  error: error.message,
170
- sessionId: state.sessionId
217
+ sessionId: state.sessionId,
171
218
  });
172
219
 
173
220
  if (error.message.includes('rate limit')) {
@@ -191,6 +238,7 @@ agent.on(events.ERROR, async ({ error, state }) => {
191
238
  Emitted before evaluating a logical condition on an edge.
192
239
 
193
240
  **Input:**
241
+
194
242
  ```typescript
195
243
  {
196
244
  edge: LogicalConditionEdge;
@@ -202,13 +250,14 @@ Emitted before evaluating a logical condition on an edge.
202
250
  **Return:** `void` (handlers for debugging/logging only)
203
251
 
204
252
  **Example:**
253
+
205
254
  ```typescript
206
255
  agent.on(events.ON_LOGICAL_CONDITION, async ({ edge, condition, state }) => {
207
256
  await logger.debug({
208
257
  event: 'condition_evaluation_start',
209
258
  condition,
210
259
  edge: { source: edge.source, target: edge.target },
211
- sessionId: state.sessionId
260
+ sessionId: state.sessionId,
212
261
  });
213
262
  });
214
263
  ```
@@ -220,6 +269,7 @@ agent.on(events.ON_LOGICAL_CONDITION, async ({ edge, condition, state }) => {
220
269
  Emitted after a logical condition is evaluated, providing result and execution metrics.
221
270
 
222
271
  **Input:**
272
+
223
273
  ```typescript
224
274
  {
225
275
  edge: LogicalConditionEdge;
@@ -234,6 +284,7 @@ Emitted after a logical condition is evaluated, providing result and execution m
234
284
  **Return:** `void` (handlers for logging/monitoring only)
235
285
 
236
286
  **Example:**
287
+
237
288
  ```typescript
238
289
  agent.on(events.ON_LOGICAL_CONDITION_RESULT, async ({ condition, result, executionTimeMs, error }) => {
239
290
  if (error) {
@@ -255,15 +306,13 @@ agent.on(events.ON_LOGICAL_CONDITION_RESULT, async ({ condition, result, executi
255
306
  Emitted when you call `trackAnalyticsEvent()` to send custom analytics data.
256
307
 
257
308
  **Function signature:**
309
+
258
310
  ```typescript
259
- async function trackAnalyticsEvent(
260
- eventName: string,
261
- payload: Record<string, any>,
262
- sessionId: string
263
- ): Promise<void>;
311
+ async function trackAnalyticsEvent(eventName: string, payload: Record<string, any>, sessionId: string): Promise<void>;
264
312
  ```
265
313
 
266
314
  **Handler input:**
315
+
267
316
  ```typescript
268
317
  {
269
318
  eventName: string;
@@ -275,6 +324,7 @@ async function trackAnalyticsEvent(
275
324
  **Return:** `void`
276
325
 
277
326
  **Example:**
327
+
278
328
  ```typescript
279
329
  import { trackAnalyticsEvent } from '@minded-ai/mindedjs';
280
330
 
@@ -285,9 +335,9 @@ agent.on(events.AI_MESSAGE, async ({ state }) => {
285
335
  'booking_completed',
286
336
  {
287
337
  bookingId: state.memory.bookingId,
288
- amount: state.memory.totalAmount
338
+ amount: state.memory.totalAmount,
289
339
  },
290
- state.sessionId
340
+ state.sessionId,
291
341
  );
292
342
  }
293
343
  });
@@ -298,13 +348,14 @@ agent.on(events.ANALYTICS_EVENT, async ({ eventName, payload, sessionId }) => {
298
348
  });
299
349
  ```
300
350
 
301
- **Query analytics:** Use the [REST API](../platform/api.md)
351
+ **Query analytics:** Use the [Analytics API](../api/analytics.md)
302
352
 
303
353
  ## TURN_END
304
354
 
305
355
  Emitted when a trigger invocation completes, just before returning the result. Allows customizing the return value.
306
356
 
307
357
  **Input:**
358
+
308
359
  ```typescript
309
360
  {
310
361
  state: State<Memory>;
@@ -312,13 +363,15 @@ Emitted when a trigger invocation completes, just before returning the result. A
312
363
  ```
313
364
 
314
365
  **Return:**
366
+
315
367
  ```typescript
316
368
  {
317
- returnValue: any; // Custom return value (optional)
369
+ returnValue: any; // Custom return value (optional)
318
370
  }
319
371
  ```
320
372
 
321
373
  **Example:**
374
+
322
375
  ```typescript
323
376
  agent.on(events.TURN_END, async ({ state }) => {
324
377
  return {
@@ -328,9 +381,9 @@ agent.on(events.TURN_END, async ({ state }) => {
328
381
  message: 'Operation completed',
329
382
  metadata: {
330
383
  executionTime: state.memory.executionTime,
331
- stepsExecuted: state.history.length
332
- }
333
- }
384
+ stepsExecuted: state.history.length,
385
+ },
386
+ },
334
387
  };
335
388
  });
336
389
  ```