@minded-ai/mindedjs 1.0.19

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 (183) hide show
  1. package/.github/workflows/CI.yml +34 -0
  2. package/.prettierrc +8 -0
  3. package/README.md +6 -0
  4. package/dist/agent.d.ts +36 -0
  5. package/dist/agent.js +199 -0
  6. package/dist/agent.js.map +1 -0
  7. package/dist/analytics.d.ts +6 -0
  8. package/dist/analytics.js +19 -0
  9. package/dist/analytics.js.map +1 -0
  10. package/dist/edges/createDirectEdge.d.ts +4 -0
  11. package/dist/edges/createDirectEdge.js +14 -0
  12. package/dist/edges/createDirectEdge.js.map +1 -0
  13. package/dist/edges/createLogicalRouter.d.ts +5 -0
  14. package/dist/edges/createLogicalRouter.js +18 -0
  15. package/dist/edges/createLogicalRouter.js.map +1 -0
  16. package/dist/edges/createPromptRouter.d.ts +7 -0
  17. package/dist/edges/createPromptRouter.js +54 -0
  18. package/dist/edges/createPromptRouter.js.map +1 -0
  19. package/dist/edges/edgeFactory.d.ts +9 -0
  20. package/dist/edges/edgeFactory.js +65 -0
  21. package/dist/edges/edgeFactory.js.map +1 -0
  22. package/dist/events/AgentEvents.d.ts +22 -0
  23. package/dist/events/AgentEvents.js +9 -0
  24. package/dist/events/AgentEvents.js.map +1 -0
  25. package/dist/events/index.d.ts +2 -0
  26. package/dist/events/index.js +5 -0
  27. package/dist/events/index.js.map +1 -0
  28. package/dist/index.d.ts +6 -0
  29. package/dist/index.js +15 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/infrastructure.ts/mindedRequest.d.ts +8 -0
  32. package/dist/infrastructure.ts/mindedRequest.js +22 -0
  33. package/dist/infrastructure.ts/mindedRequest.js.map +1 -0
  34. package/dist/llm/createLlmInstance.d.ts +2 -0
  35. package/dist/llm/createLlmInstance.js +14 -0
  36. package/dist/llm/createLlmInstance.js.map +1 -0
  37. package/dist/nodes/addHumanInTheLoopNode.d.ts +8 -0
  38. package/dist/nodes/addHumanInTheLoopNode.js +17 -0
  39. package/dist/nodes/addHumanInTheLoopNode.js.map +1 -0
  40. package/dist/nodes/addPromptNode.d.ts +15 -0
  41. package/dist/nodes/addPromptNode.js +52 -0
  42. package/dist/nodes/addPromptNode.js.map +1 -0
  43. package/dist/nodes/addToolNode.d.ts +10 -0
  44. package/dist/nodes/addToolNode.js +82 -0
  45. package/dist/nodes/addToolNode.js.map +1 -0
  46. package/dist/nodes/addTriggerNode.d.ts +6 -0
  47. package/dist/nodes/addTriggerNode.js +12 -0
  48. package/dist/nodes/addTriggerNode.js.map +1 -0
  49. package/dist/nodes/nodeFactory.d.ts +13 -0
  50. package/dist/nodes/nodeFactory.js +41 -0
  51. package/dist/nodes/nodeFactory.js.map +1 -0
  52. package/dist/platform/analytics.d.ts +6 -0
  53. package/dist/platform/analytics.js +19 -0
  54. package/dist/platform/analytics.js.map +1 -0
  55. package/dist/platform/mindedCheckpointSaver.d.ts +10 -0
  56. package/dist/platform/mindedCheckpointSaver.js +49 -0
  57. package/dist/platform/mindedCheckpointSaver.js.map +1 -0
  58. package/dist/platform/mindedConnection.d.ts +13 -0
  59. package/dist/platform/mindedConnection.js +117 -0
  60. package/dist/platform/mindedConnection.js.map +1 -0
  61. package/dist/platform/mindedConnectionTypes.d.ts +10 -0
  62. package/dist/platform/mindedConnectionTypes.js +8 -0
  63. package/dist/platform/mindedConnectionTypes.js.map +1 -0
  64. package/dist/platform/mindedRequest.d.ts +8 -0
  65. package/dist/platform/mindedRequest.js +22 -0
  66. package/dist/platform/mindedRequest.js.map +1 -0
  67. package/dist/types/Agent.types.d.ts +8 -0
  68. package/dist/types/Agent.types.js +3 -0
  69. package/dist/types/Agent.types.js.map +1 -0
  70. package/dist/types/Flows.types.d.ts +83 -0
  71. package/dist/types/Flows.types.js +24 -0
  72. package/dist/types/Flows.types.js.map +1 -0
  73. package/dist/types/LLM.types.d.ts +10 -0
  74. package/dist/types/LLM.types.js +9 -0
  75. package/dist/types/LLM.types.js.map +1 -0
  76. package/dist/types/LangGraph.types.d.ts +29 -0
  77. package/dist/types/LangGraph.types.js +20 -0
  78. package/dist/types/LangGraph.types.js.map +1 -0
  79. package/dist/types/Tools.types.d.ts +14 -0
  80. package/dist/types/Tools.types.js +3 -0
  81. package/dist/types/Tools.types.js.map +1 -0
  82. package/dist/types/Triggers.types.d.ts +1 -0
  83. package/dist/types/Triggers.types.js +3 -0
  84. package/dist/types/Triggers.types.js.map +1 -0
  85. package/docs/.gitbook/assets/image.png +0 -0
  86. package/docs/README.md +51 -0
  87. package/docs/SUMMARY.md +21 -0
  88. package/docs/api-reference/.nojekyll +1 -0
  89. package/docs/api-reference/assets/hierarchy.js +1 -0
  90. package/docs/api-reference/assets/highlight.css +120 -0
  91. package/docs/api-reference/assets/icons.js +18 -0
  92. package/docs/api-reference/assets/icons.svg +1 -0
  93. package/docs/api-reference/assets/main.js +60 -0
  94. package/docs/api-reference/assets/navigation.js +1 -0
  95. package/docs/api-reference/assets/search.js +1 -0
  96. package/docs/api-reference/assets/style.css +1640 -0
  97. package/docs/api-reference/classes/index.Agent.html +4 -0
  98. package/docs/api-reference/enums/index.EdgeType.html +4 -0
  99. package/docs/api-reference/enums/index.NodeType.html +6 -0
  100. package/docs/api-reference/enums/index.TriggerType.html +4 -0
  101. package/docs/api-reference/enums/index.events.html +3 -0
  102. package/docs/api-reference/hierarchy.html +1 -0
  103. package/docs/api-reference/index.html +310 -0
  104. package/docs/api-reference/interfaces/index.AppToolNode.html +5 -0
  105. package/docs/api-reference/interfaces/index.AppTriggerNode.html +6 -0
  106. package/docs/api-reference/interfaces/index.Flow.html +4 -0
  107. package/docs/api-reference/interfaces/index.JunctionNode.html +4 -0
  108. package/docs/api-reference/interfaces/index.LogicalConditionEdge.html +5 -0
  109. package/docs/api-reference/interfaces/index.ManualTriggerNode.html +5 -0
  110. package/docs/api-reference/interfaces/index.PromptConditionEdge.html +5 -0
  111. package/docs/api-reference/interfaces/index.PromptNode.html +6 -0
  112. package/docs/api-reference/interfaces/index.StepForwardEdge.html +4 -0
  113. package/docs/api-reference/interfaces/index.Tool.html +6 -0
  114. package/docs/api-reference/interfaces/index.ToolNode.html +5 -0
  115. package/docs/api-reference/modules/index-1.html +1 -0
  116. package/docs/api-reference/modules/index.html +1 -0
  117. package/docs/api-reference/modules.html +1 -0
  118. package/docs/api-reference/types/index.Edge.html +1 -0
  119. package/docs/api-reference/types/index.Node.html +1 -0
  120. package/docs/api-reference/types/index.TriggerNode.html +1 -0
  121. package/docs/core-concepts/edges.md +242 -0
  122. package/docs/core-concepts/events.md +161 -0
  123. package/docs/core-concepts/flows.md +74 -0
  124. package/docs/core-concepts/memory-types.md +208 -0
  125. package/docs/core-concepts/nodes.md +239 -0
  126. package/docs/core-concepts/tools.md +205 -0
  127. package/docs/examples/order-refund-flow.md +560 -0
  128. package/docs/getting-started/installation.md +34 -0
  129. package/docs/getting-started/quick-start.md +264 -0
  130. package/docs-structure.md +144 -0
  131. package/eslint.config.js +68 -0
  132. package/examples/orderRefundAgent/flows/orderRefundFlow.yaml +32 -0
  133. package/examples/orderRefundAgent/minded.json +14 -0
  134. package/examples/orderRefundAgent/orderRefundAgent.ts +58 -0
  135. package/examples/orderRefundAgent/schema.ts +7 -0
  136. package/examples/orderRefundAgent/tools/escalateConversation.ts +28 -0
  137. package/examples/orderRefundAgent/tools/index.ts +4 -0
  138. package/examples/orderRefundAgent/tools/refundOrder.ts +27 -0
  139. package/package.json +46 -0
  140. package/src/agent.ts +216 -0
  141. package/src/edges/createDirectEdge.ts +11 -0
  142. package/src/edges/createLogicalRouter.ts +16 -0
  143. package/src/edges/createPromptRouter.ts +52 -0
  144. package/src/edges/edgeFactory.ts +85 -0
  145. package/src/events/AgentEvents.ts +22 -0
  146. package/src/events/index.ts +3 -0
  147. package/src/index.ts +22 -0
  148. package/src/llm/createLlmInstance.ts +10 -0
  149. package/src/nodes/addHumanInTheLoopNode.ts +20 -0
  150. package/src/nodes/addPromptNode.ts +66 -0
  151. package/src/nodes/addToolNode.ts +95 -0
  152. package/src/nodes/addTriggerNode.ts +12 -0
  153. package/src/nodes/nodeFactory.ts +65 -0
  154. package/src/platform/analytics.ts +16 -0
  155. package/src/platform/mindedCheckpointSaver.ts +74 -0
  156. package/src/platform/mindedConnection.ts +106 -0
  157. package/src/platform/mindedConnectionTypes.ts +15 -0
  158. package/src/platform/mindedRequest.ts +28 -0
  159. package/src/types/Agent.types.ts +10 -0
  160. package/src/types/Flows.types.ts +103 -0
  161. package/src/types/LLM.types.ts +13 -0
  162. package/src/types/LangGraph.types.ts +25 -0
  163. package/src/types/Tools.types.ts +9 -0
  164. package/test/can-stay-on-node/can-stay-on-node.test.ts +148 -0
  165. package/test/can-stay-on-node/flows/test-flow.yaml +25 -0
  166. package/test/cannot-stay-on-node/cannot-stay-on-node.test.ts +201 -0
  167. package/test/cannot-stay-on-node/flows/test-flow.yaml +34 -0
  168. package/test/human-in-the-loop-node/flows/test-flow.yaml +23 -0
  169. package/test/human-in-the-loop-node/human-in-the-loop-node.test.ts +92 -0
  170. package/test/logical-edges/flows/logical-edge-test-flow.yaml +24 -0
  171. package/test/logical-edges/logical-edges.test.ts +66 -0
  172. package/test/no-human-in-the-loop-node/flows/test-flow.yaml +23 -0
  173. package/test/no-human-in-the-loop-node/no-human-in-the-loop-node.test.ts +80 -0
  174. package/test/prompt-edges/flows/test-flow.yaml +24 -0
  175. package/test/prompt-edges/prompt-edges.test.ts +90 -0
  176. package/test/prompt-node/flows/test-flow.yaml +24 -0
  177. package/test/prompt-node/prompt-node.test.ts +86 -0
  178. package/test/setup.ts +5 -0
  179. package/test/tool-node/flows/test-flow.yaml +14 -0
  180. package/test/tool-node/tool-node.test.ts +67 -0
  181. package/test/trigger/flows/test-flow.yaml +7 -0
  182. package/test/trigger/trigger.test.ts +57 -0
  183. package/tsconfig.json +17 -0
@@ -0,0 +1,560 @@
1
+ # Order Refund Flow Example
2
+
3
+ A complete example demonstrating how to build an intelligent customer support agent that can handle order refunds with sophisticated routing and business logic.
4
+
5
+ ## Overview
6
+
7
+ This example showcases:
8
+ - **Trigger handling** with qualification logic
9
+ - **Prompt-based routing** for intelligent conversation flow
10
+ - **Tool integration** for business logic execution
11
+ - **Memory management** for maintaining conversation state
12
+ - **Error handling** and edge cases
13
+
14
+ ## Complete Implementation
15
+
16
+ ### Project Structure
17
+
18
+ ```
19
+ order-refund-agent/
20
+ ā”œā”€ā”€ minded.json # Agent configuration
21
+ ā”œā”€ā”€ schema.ts # Memory type definition
22
+ ā”œā”€ā”€ agent.ts # Main agent implementation
23
+ ā”œā”€ā”€ flows/
24
+ │ └── refundFlow.yaml # Flow definition
25
+ └── tools/
26
+ ā”œā”€ā”€ lookupOrder.ts # Order lookup tool
27
+ ā”œā”€ā”€ processRefund.ts # Refund processing tool
28
+ └── index.ts # Tool exports
29
+ ```
30
+
31
+ ### 1. Agent Configuration
32
+
33
+ **`minded.json`:**
34
+ ```json
35
+ {
36
+ "flows": ["./flows"],
37
+ "llm": {
38
+ "name": "ChatOpenAI",
39
+ "properties": {
40
+ "model": "gpt-4o",
41
+ "temperature": 0.7
42
+ }
43
+ }
44
+ }
45
+ ```
46
+
47
+ ### 2. Memory Schema
48
+
49
+ **`schema.ts`:**
50
+ ```ts
51
+ import { z } from 'zod';
52
+
53
+ const memorySchema = z.object({
54
+ // Customer information
55
+ customerName: z.string().optional(),
56
+ customerEmail: z.string().optional(),
57
+ customerId: z.string().optional(),
58
+
59
+ // Order information
60
+ orderId: z.string().optional(),
61
+ orderInfo: z.object({
62
+ id: z.string(),
63
+ status: z.string(),
64
+ total: z.number(),
65
+ items: z.array(z.string()),
66
+ purchaseDate: z.string(),
67
+ canRefund: z.boolean(),
68
+ }).optional(),
69
+
70
+ // Conversation state
71
+ conversationStage: z.enum([
72
+ 'greeting',
73
+ 'gathering_info',
74
+ 'processing_refund',
75
+ 'complete'
76
+ ]).optional(),
77
+
78
+ // Refund information
79
+ refundReason: z.string().optional(),
80
+ refundAmount: z.number().optional(),
81
+ refundProcessed: z.boolean().optional(),
82
+
83
+ // Metadata
84
+ timestamp: z.string().optional(),
85
+ customerQuery: z.string().optional(),
86
+ });
87
+
88
+ export type Memory = z.infer<typeof memorySchema>;
89
+ export default memorySchema;
90
+ ```
91
+
92
+ ### 3. Flow Definition
93
+
94
+ **`flows/refundFlow.yaml`:**
95
+ ```yaml
96
+ name: 'Advanced Order Refund Flow'
97
+ nodes:
98
+ # Entry point
99
+ - type: trigger
100
+ triggerType: manual
101
+ name: Customer Support Trigger
102
+
103
+ # Initial customer interaction
104
+ - type: promptNode
105
+ name: Support Agent
106
+ prompt: |
107
+ You are a helpful customer support agent specializing in order issues and refunds.
108
+
109
+ Current customer context:
110
+ - Query: {{memory.customerQuery}}
111
+ - Stage: {{memory.conversationStage}}
112
+
113
+ If this is the first interaction:
114
+ 1. Greet the customer warmly
115
+ 2. Ask for their order ID if they mention order issues
116
+ 3. Ask for their name and email for verification
117
+
118
+ If you have order information:
119
+ - Customer: {{memory.customerName}}
120
+ - Order ID: {{memory.orderId}}
121
+ - Order Status: {{memory.orderInfo.status}}
122
+ - Order Total: ${{memory.orderInfo.total}}
123
+
124
+ Be empathetic, professional, and focused on resolving their issue.
125
+ llmConfig:
126
+ name: ChatOpenAI
127
+ properties:
128
+ model: gpt-4o
129
+ temperature: 0.7
130
+
131
+ # Order lookup functionality
132
+ - type: tool
133
+ name: Lookup Order
134
+ toolName: lookupOrder
135
+
136
+ # Junction for decision making
137
+ - type: junction
138
+ name: Refund Decision Point
139
+
140
+ # Refund processing
141
+ - type: tool
142
+ name: Process Refund
143
+ toolName: processRefund
144
+
145
+ # Final confirmation
146
+ - type: promptNode
147
+ name: Refund Confirmation
148
+ prompt: |
149
+ Great news! Your refund has been processed successfully.
150
+
151
+ Refund Details:
152
+ - Order ID: {{memory.orderId}}
153
+ - Refund Amount: ${{memory.refundAmount}}
154
+ - Reason: {{memory.refundReason}}
155
+
156
+ You can expect to see the refund in your original payment method within 3-5 business days.
157
+
158
+ Is there anything else I can help you with today?
159
+
160
+ edges:
161
+ # Initial flow
162
+ - source: Customer Support Trigger
163
+ target: Support Agent
164
+ type: stepForward
165
+
166
+ # Route to order lookup when customer provides order ID
167
+ - source: Support Agent
168
+ target: Lookup Order
169
+ type: promptCondition
170
+ prompt: "Customer has provided an order ID and wants to look up order information"
171
+
172
+ # After order lookup, go to decision point
173
+ - source: Lookup Order
174
+ target: Refund Decision Point
175
+ type: stepForward
176
+
177
+ # Decision point routing
178
+ - source: Refund Decision Point
179
+ target: Process Refund
180
+ type: logicalCondition
181
+ condition: "({ memory }) => memory.orderInfo?.canRefund && memory.customerQuery?.toLowerCase().includes('refund')"
182
+
183
+ - source: Refund Decision Point
184
+ target: Support Agent
185
+ type: logicalCondition
186
+ condition: "({ memory }) => !memory.orderInfo?.canRefund"
187
+
188
+ # After refund processing
189
+ - source: Process Refund
190
+ target: Refund Confirmation
191
+ type: stepForward
192
+
193
+ # Allow continued conversation
194
+ - source: Refund Confirmation
195
+ target: Support Agent
196
+ type: promptCondition
197
+ prompt: "Customer has additional questions or needs more help"
198
+ ```
199
+
200
+ ### 4. Tools Implementation
201
+
202
+ **`tools/lookupOrder.ts`:**
203
+ ```ts
204
+ import { z } from 'zod';
205
+ import { Tool } from 'mindedjs/src/types/Tools.types';
206
+ import { Memory } from '../schema';
207
+
208
+ const schema = z.object({
209
+ orderId: z.string(),
210
+ customerEmail: z.string().optional(),
211
+ });
212
+
213
+ const lookupOrderTool: Tool<typeof schema, Memory> = {
214
+ name: 'lookupOrder',
215
+ description: 'Look up order details by order ID and optionally verify with customer email',
216
+ input: schema,
217
+ execute: async ({ input, memory }) => {
218
+ try {
219
+ // Simulate API call to order system
220
+ const orderInfo = await fetchOrderFromAPI(input.orderId, input.customerEmail);
221
+
222
+ if (!orderInfo) {
223
+ throw new Error(`Order ${input.orderId} not found or email doesn't match`);
224
+ }
225
+
226
+ // Determine if refund is allowed based on business rules
227
+ const canRefund = determineRefundEligibility(orderInfo);
228
+
229
+ return {
230
+ memory: {
231
+ orderId: input.orderId,
232
+ orderInfo: {
233
+ ...orderInfo,
234
+ canRefund,
235
+ },
236
+ conversationStage: 'gathering_info',
237
+ customerId: orderInfo.customerId,
238
+ },
239
+ };
240
+ } catch (error) {
241
+ console.error('Order lookup failed:', error);
242
+ return {
243
+ memory: {
244
+ orderId: input.orderId,
245
+ conversationStage: 'gathering_info',
246
+ },
247
+ };
248
+ }
249
+ },
250
+ };
251
+
252
+ // Simulate order API
253
+ async function fetchOrderFromAPI(orderId: string, email?: string) {
254
+ // Simulate database lookup
255
+ const orders = {
256
+ '12345': {
257
+ id: '12345',
258
+ customerId: 'cust_123',
259
+ customerEmail: 'john@example.com',
260
+ status: 'delivered',
261
+ total: 89.99,
262
+ items: ['Wireless Headphones', 'Phone Case'],
263
+ purchaseDate: '2024-01-15T10:30:00Z',
264
+ },
265
+ '67890': {
266
+ id: '67890',
267
+ customerId: 'cust_456',
268
+ customerEmail: 'jane@example.com',
269
+ status: 'shipped',
270
+ total: 199.99,
271
+ items: ['Laptop Stand', 'Wireless Mouse'],
272
+ purchaseDate: '2024-01-20T14:20:00Z',
273
+ },
274
+ };
275
+
276
+ const order = orders[orderId];
277
+ if (!order) return null;
278
+
279
+ // Verify email if provided
280
+ if (email && order.customerEmail !== email) {
281
+ return null;
282
+ }
283
+
284
+ return order;
285
+ }
286
+
287
+ // Business rules for refund eligibility
288
+ function determineRefundEligibility(orderInfo: any): boolean {
289
+ const purchaseDate = new Date(orderInfo.purchaseDate);
290
+ const now = new Date();
291
+ const daysSincePurchase = Math.floor((now.getTime() - purchaseDate.getTime()) / (1000 * 60 * 60 * 24));
292
+
293
+ // Refund rules:
294
+ // - Must be within 30 days
295
+ // - Order must be delivered
296
+ // - Order total must be less than $500 (higher amounts need manager approval)
297
+ return (
298
+ daysSincePurchase <= 30 &&
299
+ orderInfo.status === 'delivered' &&
300
+ orderInfo.total < 500
301
+ );
302
+ }
303
+
304
+ export default lookupOrderTool;
305
+ ```
306
+
307
+ **`tools/processRefund.ts`:**
308
+ ```ts
309
+ import { z } from 'zod';
310
+ import { Tool } from 'mindedjs/src/types/Tools.types';
311
+ import { Memory } from '../schema';
312
+
313
+ const schema = z.object({
314
+ orderId: z.string(),
315
+ customerName: z.string(),
316
+ reason: z.string(),
317
+ amount: z.number().optional(), // Optional partial refund amount
318
+ });
319
+
320
+ const processRefundTool: Tool<typeof schema, Memory> = {
321
+ name: 'processRefund',
322
+ description: 'Process a refund for the customer order',
323
+ input: schema,
324
+ execute: async ({ input, memory }) => {
325
+ try {
326
+ // Determine refund amount
327
+ const refundAmount = input.amount || memory.orderInfo?.total || 0;
328
+
329
+ // Validate refund amount
330
+ if (refundAmount > (memory.orderInfo?.total || 0)) {
331
+ throw new Error('Refund amount cannot exceed order total');
332
+ }
333
+
334
+ // Process the refund (simulate payment processor API)
335
+ const refundResult = await processRefundWithPaymentProcessor({
336
+ orderId: input.orderId,
337
+ amount: refundAmount,
338
+ reason: input.reason,
339
+ });
340
+
341
+ // Log the refund for auditing
342
+ await logRefundTransaction({
343
+ orderId: input.orderId,
344
+ customerId: memory.customerId,
345
+ amount: refundAmount,
346
+ reason: input.reason,
347
+ processedBy: 'ai-agent',
348
+ timestamp: new Date().toISOString(),
349
+ });
350
+
351
+ console.log(`āœ… Refund processed: Order ${input.orderId}, Amount: $${refundAmount}`);
352
+
353
+ return {
354
+ memory: {
355
+ refundAmount,
356
+ refundReason: input.reason,
357
+ refundProcessed: true,
358
+ conversationStage: 'complete',
359
+ },
360
+ };
361
+ } catch (error) {
362
+ console.error('Refund processing failed:', error);
363
+
364
+ return {
365
+ memory: {
366
+ refundAmount: 0,
367
+ refundReason: input.reason,
368
+ refundProcessed: false,
369
+ conversationStage: 'gathering_info', // Go back to gathering info
370
+ },
371
+ };
372
+ }
373
+ },
374
+ };
375
+
376
+ // Simulate payment processor API
377
+ async function processRefundWithPaymentProcessor(params: any) {
378
+ // Simulate API call delay
379
+ await new Promise(resolve => setTimeout(resolve, 1000));
380
+
381
+ // Simulate occasional failures for testing
382
+ if (Math.random() < 0.1) {
383
+ throw new Error('Payment processor temporarily unavailable');
384
+ }
385
+
386
+ return {
387
+ refundId: `ref_${Date.now()}`,
388
+ status: 'processed',
389
+ amount: params.amount,
390
+ };
391
+ }
392
+
393
+ // Simulate audit logging
394
+ async function logRefundTransaction(transaction: any) {
395
+ console.log('šŸ“ Logging refund transaction:', transaction);
396
+ // In real implementation, this would write to a database or audit system
397
+ }
398
+
399
+ export default processRefundTool;
400
+ ```
401
+
402
+ **`tools/index.ts`:**
403
+ ```ts
404
+ import lookupOrderTool from './lookupOrder';
405
+ import processRefundTool from './processRefund';
406
+
407
+ export default [lookupOrderTool, processRefundTool];
408
+ ```
409
+
410
+ ### 5. Main Agent Implementation
411
+
412
+ **`agent.ts`:**
413
+ ```ts
414
+ import { Agent } from 'mindedjs/src/agent';
415
+ import { HumanMessage } from '@langchain/core/messages';
416
+ import { events } from 'mindedjs/src/index';
417
+ import memorySchema, { Memory } from './schema';
418
+ import tools from './tools';
419
+ import config from './minded.json';
420
+
421
+ // Create the agent
422
+ const agent = new Agent<Memory>({
423
+ memorySchema,
424
+ config,
425
+ tools,
426
+ });
427
+
428
+ // Handle AI messages (responses to user)
429
+ agent.on(events.AI_MESSAGE, async ({ message, memory }) => {
430
+ console.log('šŸ¤– Agent:', message);
431
+ if (memory.conversationStage) {
432
+ console.log(` Stage: ${memory.conversationStage}`);
433
+ }
434
+ });
435
+
436
+ // Handle trigger events with qualification logic
437
+ agent.on(events.TRIGGER_EVENT, async ({ triggerName, triggerBody }) => {
438
+ if (triggerName === 'Customer Support Trigger') {
439
+ // Qualify the trigger - only handle customer service related queries
440
+ const lowerQuery = triggerBody.toLowerCase();
441
+ const serviceKeywords = ['order', 'refund', 'help', 'support', 'issue', 'problem'];
442
+
443
+ const isServiceQuery = serviceKeywords.some(keyword =>
444
+ lowerQuery.includes(keyword)
445
+ );
446
+
447
+ if (!isServiceQuery) {
448
+ console.log('āŒ Query not qualified for customer service');
449
+ return false; // Disqualify this trigger
450
+ }
451
+
452
+ console.log('āœ… Customer service query qualified');
453
+
454
+ // Transform the request and initialize memory
455
+ return {
456
+ memory: {
457
+ customerQuery: triggerBody,
458
+ conversationStage: 'greeting',
459
+ timestamp: new Date().toISOString(),
460
+ },
461
+ messages: [new HumanMessage(triggerBody)],
462
+ };
463
+ }
464
+
465
+ return false; // Unknown trigger
466
+ });
467
+
468
+ // Example usage function
469
+ async function runRefundExample() {
470
+ console.log('šŸš€ Starting Order Refund Flow Example\n');
471
+
472
+ const examples = [
473
+ {
474
+ description: 'Happy path - valid refund request',
475
+ query: 'Hi, I need to return my order #12345. The headphones don\'t work properly.',
476
+ },
477
+ {
478
+ description: 'Order lookup required',
479
+ query: 'I want to check the status of my recent order and possibly get a refund.',
480
+ },
481
+ {
482
+ description: 'Non-service query (should be disqualified)',
483
+ query: 'What\'s the weather like today?',
484
+ },
485
+ ];
486
+
487
+ for (const example of examples) {
488
+ console.log(`\nšŸ“‹ Example: ${example.description}`);
489
+ console.log(`User: ${example.query}\n`);
490
+
491
+ try {
492
+ const result = await agent.invoke({
493
+ triggerBody: example.query,
494
+ triggerName: 'Customer Support Trigger',
495
+ sessionId: `session_${Date.now()}`,
496
+ });
497
+
498
+ console.log('āœ… Flow completed successfully');
499
+ console.log('Final memory state:', JSON.stringify(result.memory, null, 2));
500
+ } catch (error) {
501
+ console.error('āŒ Flow execution failed:', error);
502
+ }
503
+
504
+ console.log('\n' + '─'.repeat(50));
505
+ }
506
+ }
507
+
508
+ // Run the example if this file is executed directly
509
+ if (require.main === module) {
510
+ runRefundExample().catch(console.error);
511
+ }
512
+
513
+ export { agent, runRefundExample };
514
+ ```
515
+
516
+ ## Running the Example
517
+
518
+ 1. **Install dependencies:**
519
+ ```bash
520
+ npm install @agentsforce/sdk langchain
521
+ ```
522
+
523
+ 2. **Set up environment:**
524
+ ```bash
525
+ export OPENAI_API_KEY="your-openai-api-key"
526
+ ```
527
+
528
+ 3. **Run the agent:**
529
+ ```bash
530
+ npx ts-node agent.ts
531
+ ```
532
+
533
+ ## Expected Output
534
+
535
+ ```
536
+ šŸš€ Starting Order Refund Flow Example
537
+
538
+ šŸ“‹ Example: Happy path - valid refund request
539
+ User: Hi, I need to return my order #12345. The headphones don't work properly.
540
+
541
+ āœ… Customer service query qualified
542
+ šŸ¤– Agent: Hello! I'm sorry to hear you're having trouble with your headphones. I'd be happy to help you with a return. I see you mentioned order #12345. Could you please provide your email address so I can look up your order details?
543
+
544
+ āœ… Refund processed: Order 12345, Amount: $89.99
545
+ šŸ“ Logging refund transaction: {...}
546
+ šŸ¤– Agent: Great news! Your refund has been processed successfully...
547
+
548
+ āœ… Flow completed successfully
549
+ ```
550
+
551
+ ## Key Features Demonstrated
552
+
553
+ 1. **Intelligent Qualification**: The trigger only accepts customer service related queries
554
+ 2. **Conversation State Management**: Memory tracks the conversation stage and relevant information
555
+ 3. **Business Logic Integration**: Tools implement real business rules for refund eligibility
556
+ 4. **Error Handling**: Graceful handling of failed API calls and invalid requests
557
+ 5. **Audit Trail**: All refund transactions are logged for compliance
558
+ 6. **Type Safety**: Full TypeScript type safety throughout the flow
559
+
560
+ This example provides a solid foundation for building production-ready customer service agents with MindedJS!
@@ -0,0 +1,34 @@
1
+ # Installation
2
+
3
+ Get MindedJS up and running in your project.
4
+
5
+ ## Requirements
6
+
7
+ * Node.js 18 or later
8
+ * npm, yarn, or pnpm
9
+
10
+ ## Install MindedJS
11
+
12
+ {% tabs %}
13
+ {% tab title="npm" %}
14
+ ```bash
15
+ npm i @agentsforce/sdk langchain
16
+ ```
17
+ {% endtab %}
18
+
19
+ {% tab title="yarn" %}
20
+ ```bash
21
+ yarn add @agentsforce/sdk langchain
22
+ ```
23
+ {% endtab %}
24
+
25
+ {% tab title="pnpm" %}
26
+ ```bash
27
+ pnpm add @agentsforce/sdk langchain
28
+ ```
29
+ {% endtab %}
30
+ {% endtabs %}
31
+
32
+ ## Next Steps
33
+
34
+ Now that MindedJS is installed, head over to the [Quick Start](quick-start.md) guide to build your first agent!