@minded-ai/mindedjs 1.0.90 → 1.0.91
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/docs/.gitbook/assets/ADLC.png +0 -0
- package/docs/.gitbook/assets/PII-masking.png +0 -0
- package/docs/.gitbook/assets/image.png +0 -0
- package/docs/README.md +54 -0
- package/docs/SUMMARY.md +39 -0
- package/docs/examples/order-refund-flow.md +566 -0
- package/docs/getting-started/environment-configuration.md +98 -0
- package/docs/getting-started/installation.md +44 -0
- package/docs/getting-started/project-configuration.md +206 -0
- package/docs/getting-started/quick-start.md +262 -0
- package/docs/integrations/zendesk.md +554 -0
- package/docs/low-code-editor/edges.md +392 -0
- package/docs/low-code-editor/flows.md +74 -0
- package/docs/low-code-editor/nodes.md +331 -0
- package/docs/low-code-editor/playbooks.md +262 -0
- package/docs/low-code-editor/tools.md +303 -0
- package/docs/low-code-editor/triggers.md +156 -0
- package/docs/platform/events.md +374 -0
- package/docs/platform/logging.md +72 -0
- package/docs/platform/memory.md +219 -0
- package/docs/platform/pii-masking.md +220 -0
- package/docs/platform/secrets.md +99 -0
- package/docs/resources/your-first-eval.md +108 -0
- package/docs-structure.md +141 -0
- package/package.json +4 -2
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
# Events
|
|
2
|
+
|
|
3
|
+
Events are messages that flow through your agent during execution, providing visibility into what's happening and enabling reactive behavior.
|
|
4
|
+
|
|
5
|
+
MindedJS currently supports multiple main event types. Each event type has its own specific input structure, output requirements, and use cases.
|
|
6
|
+
|
|
7
|
+
## History Structure
|
|
8
|
+
|
|
9
|
+
All events provide access to the agent's history, which is a crucial part of understanding and tracking the execution flow. The history is an array of `HistoryStep` objects that represent each step the agent has taken during execution.
|
|
10
|
+
|
|
11
|
+
### HistoryStep Structure
|
|
12
|
+
|
|
13
|
+
Each history step contains the following information:
|
|
14
|
+
|
|
15
|
+
- `step`: Sequential step number in the agent's execution flow
|
|
16
|
+
- `type`: Type of the step (e.g., TRIGGER_NODE, APP_TRIGGER_NODE, TOOL_NODE, LLM_NODE)
|
|
17
|
+
- `nodeId`: ID of the node that was executed
|
|
18
|
+
- `nodeDisplayName`: Human-readable name of the node
|
|
19
|
+
- `raw`: Raw data associated with the step (e.g., trigger input, tool output)
|
|
20
|
+
- `messageIds`: IDs of messages associated with this step
|
|
21
|
+
|
|
22
|
+
Additional fields are available depending on the step type:
|
|
23
|
+
|
|
24
|
+
- For `APP_TRIGGER_NODE` steps: `appName` identifies the source application
|
|
25
|
+
- For `TOOL_NODE` steps: Contains tool input and output information
|
|
26
|
+
|
|
27
|
+
### Example Usage
|
|
28
|
+
|
|
29
|
+
```typescript
|
|
30
|
+
agent.on(events.AI_MESSAGE, async ({ message, state }) => {
|
|
31
|
+
// Access the complete execution history
|
|
32
|
+
const history = state.history;
|
|
33
|
+
|
|
34
|
+
// Find the initial trigger that started this conversation
|
|
35
|
+
const triggerStep = history.find((step) => step.type === 'TRIGGER_NODE' || step.type === 'APP_TRIGGER_NODE');
|
|
36
|
+
|
|
37
|
+
// Find all tool executions in this conversation
|
|
38
|
+
const toolSteps = history.filter((step) => step.type === 'TOOL_NODE');
|
|
39
|
+
|
|
40
|
+
// Get the last executed node
|
|
41
|
+
const lastStep = history[history.length - 1];
|
|
42
|
+
|
|
43
|
+
console.log(`Conversation started with trigger: ${triggerStep?.nodeDisplayName}`);
|
|
44
|
+
console.log(`Used ${toolSteps.length} tools so far`);
|
|
45
|
+
console.log(`Last executed node: ${lastStep?.nodeDisplayName}`);
|
|
46
|
+
});
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## INIT
|
|
50
|
+
|
|
51
|
+
The `INIT` event is emitted when the agent's graph state is initialized. This happens when a new session begins or when the agent starts processing a new conversation context.
|
|
52
|
+
|
|
53
|
+
### Input Structure
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
{
|
|
57
|
+
state: { // Full initial agent state
|
|
58
|
+
messages: BaseMessage[]; // Empty array - no messages yet
|
|
59
|
+
memory: Memory; // Initial memory state (from your schema defaults)
|
|
60
|
+
history: HistoryStep[]; // Empty array - no flow history yet
|
|
61
|
+
sessionId: string; // Session identifier (generated or provided)
|
|
62
|
+
sessionType: SessionType; // Type of session (TEXT, VOICE, etc.)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### Handler Return Value
|
|
68
|
+
|
|
69
|
+
- **Return type**: `void`
|
|
70
|
+
- **Purpose**: Handlers are used for side effects like logging, setup, or initialization tasks
|
|
71
|
+
- **Note**: Return values are ignored
|
|
72
|
+
|
|
73
|
+
### Usage Example
|
|
74
|
+
|
|
75
|
+
```typescript
|
|
76
|
+
import { Agent, events } from 'mindedjs';
|
|
77
|
+
|
|
78
|
+
const agent = new Agent({
|
|
79
|
+
memorySchema,
|
|
80
|
+
config,
|
|
81
|
+
tools,
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
// Listen to initialization events
|
|
85
|
+
agent.on(events.INIT, async ({ state }) => {
|
|
86
|
+
console.log('Agent initialized for session:', state.sessionId);
|
|
87
|
+
console.log('Session type:', state.sessionType);
|
|
88
|
+
console.log('Initial memory:', state.memory);
|
|
89
|
+
|
|
90
|
+
// Setup session-specific resources
|
|
91
|
+
await initializeSessionResources(state.sessionId);
|
|
92
|
+
|
|
93
|
+
// Log session start for analytics
|
|
94
|
+
await logSessionStart({
|
|
95
|
+
sessionId: state.sessionId,
|
|
96
|
+
sessionType: state.sessionType,
|
|
97
|
+
timestamp: new Date(),
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
// Initialize external services if needed
|
|
101
|
+
if (state.sessionType === 'VOICE') {
|
|
102
|
+
await setupVoiceSession(state.sessionId);
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### Common Use Cases
|
|
108
|
+
|
|
109
|
+
- **Session Logging**: Track when new sessions begin for analytics
|
|
110
|
+
- **Resource Initialization**: Set up session-specific resources or connections
|
|
111
|
+
- **State Validation**: Verify initial memory state meets requirements
|
|
112
|
+
- **External Service Setup**: Initialize third-party services for the session
|
|
113
|
+
- **Session Routing**: Route sessions to appropriate handlers based on type
|
|
114
|
+
- **Debugging**: Log initial state for troubleshooting
|
|
115
|
+
|
|
116
|
+
## AI_MESSAGE
|
|
117
|
+
|
|
118
|
+
The `AI_MESSAGE` event is emitted when an AI generates a message that should be sent to the user.
|
|
119
|
+
|
|
120
|
+
### Input Structure
|
|
121
|
+
|
|
122
|
+
```typescript
|
|
123
|
+
{
|
|
124
|
+
message: string; // The AI-generated message content
|
|
125
|
+
state: { // Full agent state
|
|
126
|
+
messages: BaseMessage[]; // Conversation messages
|
|
127
|
+
memory: Memory; // Current memory state (your defined memory schema)
|
|
128
|
+
history: HistoryStep[]; // Flow execution history with detailed step information
|
|
129
|
+
sessionId: string; // Session identifier
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### Handler Return Value
|
|
135
|
+
|
|
136
|
+
- **Return type**: `void`
|
|
137
|
+
- **Purpose**: Handlers are used for side effects like sending messages to UI
|
|
138
|
+
- **Note**: Return values are ignored
|
|
139
|
+
|
|
140
|
+
### Usage Example
|
|
141
|
+
|
|
142
|
+
```typescript
|
|
143
|
+
import { Agent, events } from 'mindedjs';
|
|
144
|
+
|
|
145
|
+
const agent = new Agent({
|
|
146
|
+
memorySchema,
|
|
147
|
+
config,
|
|
148
|
+
tools,
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
// Listen to AI messages
|
|
152
|
+
agent.on(events.AI_MESSAGE, async ({ message, state }) => {
|
|
153
|
+
console.log('AI said:', message);
|
|
154
|
+
console.log('Current memory:', state.memory);
|
|
155
|
+
console.log('Session ID:', state.sessionId);
|
|
156
|
+
console.log('Message count:', state.messages.length);
|
|
157
|
+
|
|
158
|
+
// Send message to user interface with session context
|
|
159
|
+
await sendMessageToUser(message, state.sessionId);
|
|
160
|
+
|
|
161
|
+
// Send via WebSocket with session information
|
|
162
|
+
await websocket.send(
|
|
163
|
+
JSON.stringify({
|
|
164
|
+
type: 'ai_message',
|
|
165
|
+
content: message,
|
|
166
|
+
sessionId: state.sessionId,
|
|
167
|
+
memory: state.memory,
|
|
168
|
+
}),
|
|
169
|
+
);
|
|
170
|
+
});
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
### Common Use Cases
|
|
174
|
+
|
|
175
|
+
- **Real-time Chat UI**: Send AI responses to chat interfaces with session context
|
|
176
|
+
- **Logging**: Record AI responses for analytics or debugging with session tracking
|
|
177
|
+
- **Message Formatting**: Transform AI messages before displaying to users
|
|
178
|
+
- **Notifications**: Trigger alerts or notifications based on AI responses
|
|
179
|
+
- **Session Management**: Route messages to specific user sessions or conversation threads
|
|
180
|
+
|
|
181
|
+
## TRIGGER_EVENT
|
|
182
|
+
|
|
183
|
+
The `TRIGGER_EVENT` event is emitted when a trigger node is executed. This event allows you to qualify, transform, and provide initial state for trigger inputs before they're processed by the agent.
|
|
184
|
+
|
|
185
|
+
### Input Structure
|
|
186
|
+
|
|
187
|
+
```typescript
|
|
188
|
+
{
|
|
189
|
+
triggerName: string; // Name of the trigger being executed
|
|
190
|
+
triggerBody: any; // The trigger input data (type varies by trigger)
|
|
191
|
+
sessionId?: string; // Optional session ID for the trigger execution
|
|
192
|
+
}
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
### Handler Return Values
|
|
196
|
+
|
|
197
|
+
TRIGGER_EVENT handlers **must** return an object that contains, at minimum, an `isQualified: boolean` field. Depending on your needs you may also return `messages`, `memory`, or a `sessionId`.
|
|
198
|
+
|
|
199
|
+
The three common patterns are:
|
|
200
|
+
|
|
201
|
+
#### 1. Provide Initial State & Qualify
|
|
202
|
+
|
|
203
|
+
```typescript
|
|
204
|
+
{
|
|
205
|
+
isQualified: true, // ✅ The trigger should be processed
|
|
206
|
+
messages?: BaseMessage[], // Optional initial conversation messages
|
|
207
|
+
memory?: Memory, // Optional initial memory state
|
|
208
|
+
history?: HistoryStep[], // Optional history steps to include
|
|
209
|
+
sessionId?: string, // Optional session continuity identifier
|
|
210
|
+
}
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
#### 2. Disqualify the Trigger
|
|
214
|
+
|
|
215
|
+
```typescript
|
|
216
|
+
{
|
|
217
|
+
isQualified: false; // ❌ Rejects / disqualifies the trigger
|
|
218
|
+
}
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
#### 3. Qualify Without Extra State
|
|
222
|
+
|
|
223
|
+
```typescript
|
|
224
|
+
{
|
|
225
|
+
isQualified: true; // ✅ Accept the trigger – no extra state needed
|
|
226
|
+
}
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
**Note on sessionId**: The `sessionId` is crucial for persistence and resuming existing sessions. When you provide a `sessionId` that already exists, the agent will resume from the previous state. If none is provided or a new one is given, a fresh execution starts. The platform will automatically generate a `sessionId` for you in the sandbox playground – make sure to pass it forward in that environment.
|
|
230
|
+
|
|
231
|
+
### Usage Examples
|
|
232
|
+
|
|
233
|
+
#### Processing User Input
|
|
234
|
+
|
|
235
|
+
```typescript
|
|
236
|
+
agent.on(events.TRIGGER_EVENT, async ({ triggerName, triggerBody, sessionId }) => {
|
|
237
|
+
if (triggerName === 'userMessage') {
|
|
238
|
+
console.log('Processing trigger for session:', sessionId);
|
|
239
|
+
return {
|
|
240
|
+
isQualified: true,
|
|
241
|
+
memory: {
|
|
242
|
+
conversationStarted: true,
|
|
243
|
+
sessionId: sessionId, // Store session ID in memory if needed
|
|
244
|
+
},
|
|
245
|
+
messages: [new HumanMessage(triggerBody)],
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
#### Trigger Qualification
|
|
252
|
+
|
|
253
|
+
```typescript
|
|
254
|
+
agent.on(events.TRIGGER_EVENT, async ({ triggerName, triggerBody }) => {
|
|
255
|
+
// Validate the trigger input
|
|
256
|
+
if (!isValidInput(triggerBody)) {
|
|
257
|
+
return { isQualified: false }; // Disqualify the trigger
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// Only process during business hours
|
|
261
|
+
if (triggerName === 'supportRequest' && !isBusinessHours()) {
|
|
262
|
+
return { isQualified: false };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
return {
|
|
266
|
+
isQualified: true,
|
|
267
|
+
memory: { validatedInput: triggerBody },
|
|
268
|
+
messages: [],
|
|
269
|
+
};
|
|
270
|
+
});
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
#### Input Transformation
|
|
274
|
+
|
|
275
|
+
```typescript
|
|
276
|
+
agent.on(events.TRIGGER_EVENT, async ({ triggerName, triggerBody }) => {
|
|
277
|
+
if (triggerName === 'emailTrigger') {
|
|
278
|
+
// Transform email data into structured format
|
|
279
|
+
const parsedEmail = parseEmailContent(triggerBody);
|
|
280
|
+
|
|
281
|
+
return {
|
|
282
|
+
isQualified: true,
|
|
283
|
+
memory: {
|
|
284
|
+
emailSubject: parsedEmail.subject,
|
|
285
|
+
senderEmail: parsedEmail.from,
|
|
286
|
+
},
|
|
287
|
+
messages: [new HumanMessage(parsedEmail.content)],
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
// Disqualify all other triggers handled by this listener
|
|
291
|
+
return { isQualified: false };
|
|
292
|
+
});
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
### Common Use Cases
|
|
296
|
+
|
|
297
|
+
- **Input Validation**: Ensure trigger data meets requirements before processing
|
|
298
|
+
- **Data Transformation**: Convert trigger inputs into standardized formats
|
|
299
|
+
- **Context Setting**: Provide initial memory state based on trigger context
|
|
300
|
+
- **Access Control**: Disqualify triggers based on permissions or business rules
|
|
301
|
+
- **Routing Logic**: Handle different trigger types with specific logic
|
|
302
|
+
|
|
303
|
+
## ERROR
|
|
304
|
+
|
|
305
|
+
The `ERROR` event is emitted when an error occurs during agent execution. This event allows you to handle errors gracefully, log them for debugging, or implement custom error recovery logic.
|
|
306
|
+
|
|
307
|
+
### Input Structure
|
|
308
|
+
|
|
309
|
+
```typescript
|
|
310
|
+
{
|
|
311
|
+
error: Error; // The error object that was thrown
|
|
312
|
+
state: { // Full agent state at the time of error
|
|
313
|
+
messages: BaseMessage[]; // Conversation messages
|
|
314
|
+
memory: Memory; // Current memory state (your defined memory schema)
|
|
315
|
+
history: HistoryStep[]; // Flow execution history with detailed step information
|
|
316
|
+
sessionId: string; // Session identifier
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
### Handler Return Value
|
|
322
|
+
|
|
323
|
+
- **Return type**: `void`
|
|
324
|
+
- **Purpose**: Handlers are used for side effects like error logging, notifications, or recovery actions
|
|
325
|
+
- **Note**: Return values are ignored
|
|
326
|
+
|
|
327
|
+
### Usage Example
|
|
328
|
+
|
|
329
|
+
```typescript
|
|
330
|
+
import { Agent, events } from 'mindedjs';
|
|
331
|
+
|
|
332
|
+
const agent = new Agent({
|
|
333
|
+
memorySchema,
|
|
334
|
+
config,
|
|
335
|
+
tools,
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
// Listen to errors
|
|
339
|
+
agent.on(events.ERROR, async ({ error, state }) => {
|
|
340
|
+
console.error('Agent error occurred:', error.message);
|
|
341
|
+
console.error('Error stack:', error.stack);
|
|
342
|
+
console.log('Session ID:', state.sessionId);
|
|
343
|
+
console.log('Current memory:', state.memory);
|
|
344
|
+
console.log('Messages at error:', state.messages.length);
|
|
345
|
+
|
|
346
|
+
// Log to external service
|
|
347
|
+
await logger.error({
|
|
348
|
+
message: 'Agent execution error',
|
|
349
|
+
error: error.message,
|
|
350
|
+
stack: error.stack,
|
|
351
|
+
sessionId: state.sessionId,
|
|
352
|
+
memory: state.memory,
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
// Notify monitoring system
|
|
356
|
+
await notificationService.alert({
|
|
357
|
+
type: 'agent_error',
|
|
358
|
+
error: error.message,
|
|
359
|
+
sessionId: state.sessionId,
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
// Send error response to user (if needed)
|
|
363
|
+
await sendErrorMessageToUser('Something went wrong. Please try again.', state.sessionId);
|
|
364
|
+
});
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
### Common Use Cases
|
|
368
|
+
|
|
369
|
+
- **Error Logging**: Record errors for debugging and monitoring with full context
|
|
370
|
+
- **User Notifications**: Provide graceful error messages to users
|
|
371
|
+
- **Monitoring & Alerting**: Integrate with monitoring systems for error tracking
|
|
372
|
+
- **Error Recovery**: Implement custom recovery logic or fallback behaviors
|
|
373
|
+
- **Session Management**: Clean up or reset sessions that encountered errors
|
|
374
|
+
- **Analytics**: Track error patterns and frequencies for system improvement
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# Logging
|
|
2
|
+
|
|
3
|
+
MindedJS provides a structured logging system that helps you monitor, debug, and audit your agent's behavior. The logger is available throughout your agent code and provides consistent, contextual logging with proper PII handling.
|
|
4
|
+
|
|
5
|
+
## Using the Logger
|
|
6
|
+
|
|
7
|
+
Import the logger from MindedJS:
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { logger } from 'mindedjs';
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
The logger is also available in all tool contexts, so you can use it directly in your tools without importing.
|
|
14
|
+
|
|
15
|
+
## Log Levels
|
|
16
|
+
|
|
17
|
+
The logger supports standard log levels:
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
// Info level - general information
|
|
21
|
+
logger.info('Processing customer request');
|
|
22
|
+
|
|
23
|
+
// Warning level - potential issues
|
|
24
|
+
logger.warn('Customer tier not found, using default');
|
|
25
|
+
|
|
26
|
+
// Error level - errors and exceptions
|
|
27
|
+
logger.error('Failed to process payment');
|
|
28
|
+
|
|
29
|
+
// Debug level - detailed debugging information
|
|
30
|
+
logger.debug('Memory state updated');
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Structured Logging
|
|
34
|
+
|
|
35
|
+
Use structured logging with contextual data for better observability:
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
// Basic structured logging
|
|
39
|
+
logger.info('Order processed', {
|
|
40
|
+
orderId: 'ORD-123',
|
|
41
|
+
customerId: 'CUST-456',
|
|
42
|
+
amount: 99.99,
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
// Include session context in tools
|
|
46
|
+
logger.info('Tool execution started', {
|
|
47
|
+
sessionId: state.sessionId,
|
|
48
|
+
toolName: 'refundOrder',
|
|
49
|
+
orderId: input.orderId,
|
|
50
|
+
});
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Log Configuration
|
|
54
|
+
|
|
55
|
+
The logger can be configured through environment variables:
|
|
56
|
+
|
|
57
|
+
```env
|
|
58
|
+
# Set log level (debug, info, warn, error)
|
|
59
|
+
LOG_LEVEL=info
|
|
60
|
+
|
|
61
|
+
# In development, you might want debug level
|
|
62
|
+
LOG_LEVEL=debug
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Best Practices
|
|
66
|
+
|
|
67
|
+
1. **Always Include Session Context**: Include `sessionId` in all tool-related logs
|
|
68
|
+
2. **Use Appropriate Log Levels**: Don't use `info` for debugging information
|
|
69
|
+
3. **Structure Your Data**: Use objects for structured logging rather than strings
|
|
70
|
+
4. **Log State Changes**: Log important state transitions and memory updates
|
|
71
|
+
5. **Error Context**: Include full error context when logging failures
|
|
72
|
+
6. **Performance Metrics**: Log timing information for performance monitoring
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
# Memory Types
|
|
2
|
+
|
|
3
|
+
Memory in MindedJS allows agents to persist and share data across conversation turns and flow executions. It acts as the agent's working memory, storing context, user information, conversation state, and any other data your agent needs to remember.
|
|
4
|
+
|
|
5
|
+
## What is Memory?
|
|
6
|
+
|
|
7
|
+
Memory is a structured data store that:
|
|
8
|
+
|
|
9
|
+
- Persists throughout an agent session
|
|
10
|
+
- Is accessible to all nodes in your flows
|
|
11
|
+
- Gets automatically merged when updated
|
|
12
|
+
- Is validated against a schema you define
|
|
13
|
+
- Can store any JSON-serializable data
|
|
14
|
+
|
|
15
|
+
## Defining Memory Schema
|
|
16
|
+
|
|
17
|
+
Memory schemas are defined using [Zod](https://zod.dev/) for type safety and runtime validation.
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
import { z } from 'zod';
|
|
21
|
+
|
|
22
|
+
const memorySchema = z.object({
|
|
23
|
+
user: z.object({
|
|
24
|
+
id: z.string(),
|
|
25
|
+
name: z.string(),
|
|
26
|
+
preferences: z.object({
|
|
27
|
+
language: z.string().default('en'),
|
|
28
|
+
timezone: z.string().default('UTC'),
|
|
29
|
+
}),
|
|
30
|
+
}),
|
|
31
|
+
conversation: z.object({
|
|
32
|
+
topic: z.string().optional(),
|
|
33
|
+
urgency: z.enum(['low', 'medium', 'high']).default('medium'),
|
|
34
|
+
}),
|
|
35
|
+
order: z
|
|
36
|
+
.object({
|
|
37
|
+
id: z.string(),
|
|
38
|
+
status: z.string(),
|
|
39
|
+
total: z.number(),
|
|
40
|
+
})
|
|
41
|
+
.optional(),
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
type Memory = z.infer<typeof memorySchema>;
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Using Memory in Your Agent
|
|
48
|
+
|
|
49
|
+
### 1. Configure Memory Schema
|
|
50
|
+
|
|
51
|
+
```typescript
|
|
52
|
+
import { Agent } from 'mindedjs';
|
|
53
|
+
|
|
54
|
+
const agent = new Agent({
|
|
55
|
+
memorySchema,
|
|
56
|
+
config,
|
|
57
|
+
tools,
|
|
58
|
+
});
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### 2. Initialize Memory
|
|
62
|
+
|
|
63
|
+
Memory is typically initialized when a trigger event occurs:
|
|
64
|
+
|
|
65
|
+
```typescript
|
|
66
|
+
import { events } from 'mindedjs';
|
|
67
|
+
|
|
68
|
+
agent.on(events.TRIGGER_EVENT, async ({ triggerName, triggerBody }) => {
|
|
69
|
+
if (triggerName === 'new_order_issue') {
|
|
70
|
+
return {
|
|
71
|
+
memory: {
|
|
72
|
+
user: { id: triggerBody.userId, name: triggerBody.userName },
|
|
73
|
+
order: { id: triggerBody.orderId, status: 'pending' },
|
|
74
|
+
},
|
|
75
|
+
messages: [],
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### 3. Access Memory in Tools
|
|
82
|
+
|
|
83
|
+
Tools can read from and write to memory:
|
|
84
|
+
|
|
85
|
+
```typescript
|
|
86
|
+
const updateOrderStatus = {
|
|
87
|
+
name: 'updateOrderStatus',
|
|
88
|
+
description: 'Updates the order status in memory',
|
|
89
|
+
inputSchema: z.object({
|
|
90
|
+
newStatus: z.string(),
|
|
91
|
+
}),
|
|
92
|
+
execute: async ({ input, memory }) => {
|
|
93
|
+
// Read from memory
|
|
94
|
+
const currentOrder = memory.order;
|
|
95
|
+
|
|
96
|
+
// Return updated memory (merges with existing)
|
|
97
|
+
return {
|
|
98
|
+
result: `Order status updated to ${input.newStatus}`,
|
|
99
|
+
memory: {
|
|
100
|
+
order: {
|
|
101
|
+
...currentOrder,
|
|
102
|
+
status: input.newStatus,
|
|
103
|
+
lastUpdated: new Date().toISOString(),
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Memory Lifecycle
|
|
112
|
+
|
|
113
|
+
1. **Initialization**: Memory starts empty `{}` and gets populated during trigger events
|
|
114
|
+
2. **Persistence**: Automatically persisted between conversation turns
|
|
115
|
+
3. **Updates**: Memory updates are merged when tools return a memory object
|
|
116
|
+
4. **Validation**: All updates are validated against your schema
|
|
117
|
+
|
|
118
|
+
```typescript
|
|
119
|
+
// Current memory: { userId: "123", userName: "John" }
|
|
120
|
+
// Tool returns: { memory: { userName: "John Doe", email: "john@example.com" } }
|
|
121
|
+
// Result: { userId: "123", userName: "John Doe", email: "john@example.com" }
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Best Practices
|
|
125
|
+
|
|
126
|
+
### 1. Keep It Focused
|
|
127
|
+
|
|
128
|
+
Only store data relevant to your agent's functionality:
|
|
129
|
+
|
|
130
|
+
```typescript
|
|
131
|
+
// Good: Focused schema
|
|
132
|
+
const memorySchema = z.object({
|
|
133
|
+
customerId: z.string(),
|
|
134
|
+
currentIssue: z.string(),
|
|
135
|
+
resolutionSteps: z.array(z.string()),
|
|
136
|
+
});
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### 2. Use Optional Fields and Defaults
|
|
140
|
+
|
|
141
|
+
```typescript
|
|
142
|
+
const memorySchema = z.object({
|
|
143
|
+
userId: z.string(),
|
|
144
|
+
orderId: z.string().optional(), // Not all conversations involve orders
|
|
145
|
+
conversationState: z.enum(['started', 'in_progress', 'resolved']).default('started'),
|
|
146
|
+
attemptCount: z.number().default(0),
|
|
147
|
+
});
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### 3. Structure Related Data
|
|
151
|
+
|
|
152
|
+
Group related fields into objects:
|
|
153
|
+
|
|
154
|
+
```typescript
|
|
155
|
+
const memorySchema = z.object({
|
|
156
|
+
customer: z.object({
|
|
157
|
+
id: z.string(),
|
|
158
|
+
name: z.string(),
|
|
159
|
+
tier: z.enum(['bronze', 'silver', 'gold']),
|
|
160
|
+
}),
|
|
161
|
+
session: z.object({
|
|
162
|
+
startTime: z.string(),
|
|
163
|
+
channel: z.enum(['chat', 'email', 'phone']),
|
|
164
|
+
}),
|
|
165
|
+
});
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
## Common Patterns
|
|
169
|
+
|
|
170
|
+
### User Context Pattern
|
|
171
|
+
|
|
172
|
+
```typescript
|
|
173
|
+
const memorySchema = z.object({
|
|
174
|
+
user: z.object({
|
|
175
|
+
id: z.string(),
|
|
176
|
+
profile: z.object({
|
|
177
|
+
name: z.string(),
|
|
178
|
+
email: z.string(),
|
|
179
|
+
preferences: z.record(z.unknown()),
|
|
180
|
+
}),
|
|
181
|
+
}),
|
|
182
|
+
});
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
### Conversation State Pattern
|
|
186
|
+
|
|
187
|
+
```typescript
|
|
188
|
+
const memorySchema = z.object({
|
|
189
|
+
conversation: z.object({
|
|
190
|
+
phase: z.enum(['greeting', 'information_gathering', 'processing', 'resolution']),
|
|
191
|
+
data: z.record(z.unknown()),
|
|
192
|
+
}),
|
|
193
|
+
});
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
## Memory vs Messages vs History
|
|
197
|
+
|
|
198
|
+
- **Memory**: Structured data representing current state and context
|
|
199
|
+
- **Messages**: Conversation messages (AI, Human, Tool call, System etc.)
|
|
200
|
+
- **History**: Flow execution tracking with details about node visits, triggers, and tool calls
|
|
201
|
+
|
|
202
|
+
```typescript
|
|
203
|
+
// Memory: Current state
|
|
204
|
+
{
|
|
205
|
+
orderId: "ORD-123",
|
|
206
|
+
status: "processing",
|
|
207
|
+
customer: { name: "John", tier: "gold" }
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// Messages: Conversation messages
|
|
211
|
+
[
|
|
212
|
+
{ role: "human", content: "I need help with my order" },
|
|
213
|
+
{ role: "ai", content: "I'd be happy to help!" },
|
|
214
|
+
]
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
All three work together to provide complete context to your agent.
|