-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathroute-lifecycle-hooks.ts
More file actions
556 lines (526 loc) · 18.1 KB
/
route-lifecycle-hooks.ts
File metadata and controls
556 lines (526 loc) · 18.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
/**
* Rules & Prohibitions Example
* Updated for v2 architecture with session step management
*
* Demonstrates how to use rules and prohibitions to control agent behavior
* in different conversation routes (e.g., WhatsApp bot with different styles)
*
* NEW: Enhanced with complex ConditionTemplate patterns:
* - Mixed conditions: ["AI context", (ctx) => keyword_detection]
* - Route skipIf: Dynamic route exclusion based on message analysis
* - Function-only conditions: (ctx) => sophisticated_routing_logic
* - String-only conditions: "simple AI context for general chat"
* - Emergency routing with never-skip logic (skipIf: false)
* - Performance patterns for real-time condition evaluation
*/
import { Agent, type History, END_ROUTE, OpenAIProvider } from "../../src";
/**
* Configuration for the AI provider
*/
const provider = new OpenAIProvider({
apiKey: process.env.OPENAI_API_KEY || "your-api-key-here",
model: "gpt-5",
});
// Define data schema for feedback collection
interface ServiceData {
feedbackRating?: number;
feedbackComments?: string;
}
const serviceSchema = {
type: "object",
properties: {
feedbackRating: {
type: "number",
description: "Rating from 1-5",
minimum: 1,
maximum: 5,
},
feedbackComments: {
type: "string",
description: "Additional feedback comments",
},
},
};
/**
* Create a new agent instance with predefined routes and rules/prohibitions.
*/
const agent = new Agent<unknown, ServiceData>({
name: "CustomerServiceAgent",
description:
"A versatile customer service agent that adapts its behavior based on the conversation's context.",
goal: "Provide excellent customer service by following route-specific rules and prohibitions.",
provider,
// NEW: Agent-level schema
schema: serviceSchema,
debug: true,
// Knowledge base with customer service best practices
knowledgeBase: {
communicationGuidelines: {
channels: {
whatsapp: {
maxMessageLength: "1000 characters",
supports: ["text", "images", "documents"],
bestFor: [
"Quick questions",
"Personal communication",
"Mobile users",
],
},
email: {
maxMessageLength: "No limit",
supports: ["text", "attachments", "formatting"],
bestFor: [
"Detailed inquiries",
"Documentation",
"Formal communication",
],
},
chat: {
maxMessageLength: "Real-time",
supports: ["text", "quick responses"],
bestFor: ["Immediate help", "Simple questions", "Live support"],
},
},
toneGuidelines: {
professional: "Formal language, complete sentences, proper grammar",
casual: "Friendly language, contractions, emojis allowed",
urgent: "Direct, clear, action-oriented language",
},
},
escalationPaths: {
technical: "Route to technical support team",
billing: "Route to billing department",
complaint: "Route to customer success manager",
legal: "Route to legal/compliance team",
},
responseTimeTargets: {
whatsapp: "Within 5 minutes during business hours",
email: "Within 24 hours",
chat: "Immediate response",
emergency: "Immediate escalation",
},
customerSegments: {
new: "Welcome warmly, provide overview, offer help",
returning: "Personalize greeting, reference history, anticipate needs",
vip: "Priority service, direct manager access, special offers",
enterprise: "Dedicated account manager, SLA guarantees, custom solutions",
},
},
});
/**
* Add routes to the agent.
*/
agent.createRoute({
title: "Quick Support",
description: "Fast answers for common questions",
// Mixed condition: AI context + programmatic validation
when: [
"User has a simple question",
"User wants quick help",
(ctx) => {
const message = ctx.helpers.getLastUserMessage()?.toLowerCase() || '';
return message.includes('quick') || message.includes('simple') || message.length < 50;
}
],
// Skip if user seems to need detailed help
skipIf: [
"user needs detailed or complex assistance",
(ctx) => {
const message = ctx.helpers.getLastUserMessage()?.toLowerCase() || '';
return message.includes('detailed') || message.includes('complex') || message.length > 100;
}
],
rules: [
"Keep messages extremely short (1-2 lines maximum)",
"Use bullet points for lists",
"Maximum 1 emoji per message 👍",
"Be direct and to the point",
],
prohibitions: [
"Never send long paragraphs",
"Do not over-explain",
"Never use more than 2 emojis",
"Do not ask follow-up questions unless necessary",
],
});
agent.createRoute({
title: "Sales Consultation",
description: "Help customer discover needs and present solutions",
// Function-only condition for programmatic sales detection
when: (ctx) => {
const message = ctx.helpers.getLastUserMessage()?.toLowerCase() || '';
return message.includes('buy') || message.includes('purchase') ||
message.includes('price') || message.includes('cost') ||
message.includes('product') || message.includes('interested');
},
// Skip if user is having technical issues
skipIf: [
"user has technical problems that need solving first",
(ctx) => {
const message = ctx.helpers.getLastUserMessage()?.toLowerCase() || '';
return message.includes('broken') || message.includes('error') ||
message.includes('not working') || message.includes('problem');
}
],
rules: [
"Ask open-ended questions to discover needs",
"Use storytelling when presenting solutions",
"Emoji to reinforce positive emotions 😊✨",
"Present value before mentioning price",
"Make customer feel special and understood",
],
prohibitions: [
"Never talk about price before showing value",
"Do not pressure or push",
"Avoid technical jargon",
"Never send more than 2 messages without waiting for response",
"Do not make promises you cannot keep",
],
// Route-level guidelines for sales behavior
guidelines: [
{
condition: "Customer mentions budget concerns",
action: "Focus on ROI and long-term value rather than upfront cost",
},
{
condition: "Customer seems hesitant or unsure",
action: "Offer a free trial or consultation to reduce risk",
},
{
condition: "Customer asks for competitors comparison",
action:
"Highlight unique strengths and differentiators without negative comments",
},
],
});
agent.createRoute({
title: "Technical Support",
description: "Help with technical issues and troubleshooting",
// Mixed condition: AI context + technical keyword detection
when: [
"User has technical problem",
"User needs step-by-step help",
(ctx) => {
const message = ctx.helpers.getLastUserMessage()?.toLowerCase() || '';
return message.includes('help') || message.includes('problem') ||
message.includes('error') || message.includes('not working') ||
message.includes('broken') || message.includes('fix');
}
],
// Skip if user is just browsing or asking about sales
skipIf: (ctx) => {
const message = ctx.helpers.getLastUserMessage()?.toLowerCase() || '';
return message.includes('price') || message.includes('buy') || message.includes('cost');
},
rules: [
"Provide clear, numbered steps",
"Use simple language for technical concepts",
"Confirm understanding after each major step",
"Offer screenshots or visual aids when helpful",
"Be patient and thorough",
],
prohibitions: [
"Never skip steps or assume knowledge",
"Do not use excessive technical terms without explanation",
"Never blame the user for the issue",
"Do not rush through explanations",
],
});
// Add a stepful feedback flow to the Technical Support route
const techSupportRoute = agent
.getRoutes()
.find((r) => r.title === "Technical Support")!;
techSupportRoute.initialStep
.nextStep({
prompt: "Provide step-by-step technical assistance.",
})
.nextStep({
prompt: "Ask for a rating of the support provided (1-5).",
collect: ["feedbackRating"],
})
.nextStep({
prompt: "Ask for any additional comments.",
collect: ["feedbackComments"],
})
.nextStep({
prompt: "Thank the user for their feedback.",
})
.nextStep({ step: END_ROUTE });
agent.createRoute({
title: "Emergency Support",
description: "Handle urgent customer issues",
// Mixed condition: AI context + urgency detection
when: [
"Customer is frustrated",
"Urgent issue",
"Service down",
(ctx) => {
const message = ctx.helpers.getLastUserMessage()?.toLowerCase() || '';
const urgentWords = ['urgent', 'emergency', 'critical', 'down', 'broken', 'frustrated', 'angry'];
return urgentWords.some(word => message.includes(word)) || message.includes('!!!');
}
],
// Never skip emergency support
skipIf: ()=>false,
rules: [
"Acknowledge the urgency immediately",
"Express empathy and understanding",
"Provide concrete next steps",
"Set clear expectations on resolution time",
"Keep customer updated",
],
prohibitions: [
"Never downplay the customer's concern",
"Do not use emojis (keep it professional)",
'Never say "calm down" or similar dismissive phrases',
"Do not transfer without explaining why",
"Never make excuses or blame others",
],
});
agent.createRoute({
title: "General Chat",
description: "Casual conversation and general questions",
// String-only condition for AI context
when: "User is just chatting, greeting, or asking general questions",
// Skip if user has specific needs that other routes can handle
skipIf: (ctx) => {
const message = ctx.helpers.getLastUserMessage()?.toLowerCase() || '';
return message.includes('help') || message.includes('buy') ||
message.includes('problem') || message.includes('urgent');
},
rules: [
"Be friendly and conversational",
"Use emojis naturally 😊",
"Mirror the customer's tone and energy",
"Keep it light and positive",
],
prohibitions: [
"Do not be overly formal",
"Never ignore the customer's mood",
"Do not push products unless asked",
],
});
/**
* Demonstration function to show how the agent responds to different scenarios.
*/
async function demonstrateRulesAndProhibitions() {
const agent = new Agent<unknown, ServiceData>({
name: "CustomerServiceAgent",
description:
"A versatile customer service agent that adapts its behavior based on the conversation's context.",
goal: "Provide excellent customer service by following route-specific rules and prohibitions.",
provider,
// NEW: Agent-level schema
schema: serviceSchema,
debug: true,
});
// Add domains
agent.createRoute({
title: "Quick Support",
description: "Fast answers for common questions",
when: ["User has a simple question", "User wants quick help"],
rules: [
"Keep messages extremely short (1-2 lines maximum)",
"Use bullet points for lists",
"Maximum 1 emoji per message 👍",
"Be direct and to the point",
],
prohibitions: [
"Never send long paragraphs",
"Do not over-explain",
"Never use more than 2 emojis",
"Do not ask follow-up questions unless necessary",
],
});
agent.createRoute({
title: "Sales Consultation",
description: "Help customer discover needs and present solutions",
when: [
"User is interested in buying",
"User wants product information",
],
rules: [
"Ask open-ended questions to discover needs",
"Use storytelling when presenting solutions",
"Emoji to reinforce positive emotions 😊✨",
"Present value before mentioning price",
"Make customer feel special and understood",
],
prohibitions: [
"Never talk about price before showing value",
"Do not pressure or push",
"Avoid technical jargon",
"Never send more than 2 messages without waiting for response",
"Do not make promises you cannot keep",
],
});
agent.createRoute({
title: "Technical Support",
description: "Help with technical issues and troubleshooting",
when: ["User has technical problem", "User needs step-by-step help"],
rules: [
"Provide clear, numbered steps",
"Use simple language for technical concepts",
"Confirm understanding after each major step",
"Offer screenshots or visual aids when helpful",
"Be patient and thorough",
],
prohibitions: [
"Never skip steps or assume knowledge",
"Do not use excessive technical terms without explanation",
"Never blame the user for the issue",
"Do not rush through explanations",
],
});
// Add a stepful feedback flow to the Technical Support route
const techSupportRoute = agent
.getRoutes()
.find((r) => r.title === "Technical Support")!;
techSupportRoute.initialStep
.nextStep({
prompt: "Provide step-by-step technical assistance.",
})
.nextStep({
prompt: "Ask for a rating of the support provided (1-5).",
collect: ["feedbackRating"],
})
.nextStep({
prompt: "Ask for any additional comments.",
collect: ["feedbackComments"],
})
.nextStep({
prompt: "Thank the user for their feedback.",
})
.nextStep({ step: END_ROUTE });
agent.createRoute({
title: "Emergency Support",
description: "Handle urgent customer issues",
when: ["Customer is frustrated", "Urgent issue", "Service down"],
rules: [
"Acknowledge the urgency immediately",
"Express empathy and understanding",
"Provide concrete next steps",
"Set clear expectations on resolution time",
"Keep customer updated",
],
prohibitions: [
"Never downplay the customer's concern",
"Do not use emojis (keep it professional)",
'Never say "calm down" or similar dismissive phrases',
"Do not transfer without explaining why",
"Never make excuses or blame others",
],
});
agent.createRoute({
title: "General Chat",
description: "Casual conversation and general questions",
when: ["User is just chatting", "Greeting", "General question"],
rules: [
"Be friendly and conversational",
"Use emojis naturally 😊",
"Mirror the customer's tone and energy",
"Keep it light and positive",
],
prohibitions: [
"Do not be overly formal",
"Never ignore the customer's mood",
"Do not push products unless asked",
],
});
console.info("\n=== Rules & Prohibitions Demo ===\n");
// --- Quick Support ---
console.info("1️⃣ Quick Support Route (short, direct)");
const quickSupportMessages: History = [
{
role: "user",
content: "How do I reset my password?",
},
];
const response1 = await agent.respond({ history: quickSupportMessages });
console.info(`Route: ${response1.session?.currentRoute?.title}`);
console.info(`Response: ${response1.message}`);
console.info(`Expected: Short, direct, max 1 emoji\n`);
// --- Sales Consultation ---
console.info("2️⃣ Sales Consultation Route (conversational, value-first)");
const salesMessages: History = [
{
role: "user",
content: "How much does your premium plan cost?",
},
];
const response2 = await agent.respond({ history: salesMessages });
console.info(`Route: ${response2.session?.currentRoute?.title}`);
console.info(`Response: ${response2.message}`);
console.info(`Expected: Ask about needs, show value before price\n`);
// --- Technical Support ---
console.info("3️⃣ Technical Support Route (detailed, step-by-step)");
const techSupportMessages: History = [
{
role: "user",
content: "My new headphones won't connect to Bluetooth.",
},
];
const response3 = await agent.respond({ history: techSupportMessages });
console.info(`Route: ${response3.session?.currentRoute?.title}`);
console.info(`Response: ${response3.message}`);
console.info(`Expected: Clear steps, simple language, patient\n`);
if (response3.isRouteComplete) {
console.info("\n✅ Technical support feedback collected!");
}
// --- Emergency Support ---
console.info("4️⃣ Emergency Support Route (urgent, professional)");
const emergencyMessages: History = [
{
role: "user",
content: "My account has been compromised!",
},
];
const response4 = await agent.respond({ history: emergencyMessages });
console.info(`Route: ${response4.session?.currentRoute?.title}`);
console.info(`Response: ${response4.message}`);
console.info(`Expected: Acknowledge urgency, no emojis, concrete steps\n`);
// --- General Chat ---
console.info("5️⃣ General Chat Route (friendly, casual)");
const generalMessages: History = [
{
role: "user",
content: "What's the weather like today?",
},
];
const response5 = await agent.respond({ history: generalMessages });
console.info(`Route: ${response5.session?.currentRoute?.title}`);
console.info(`Response: ${response5.message}`);
console.info(`Expected: Friendly, emojis, mirrors customer tone\n`);
}
/**
* Inspect route configurations.
*/
console.info("\n📋 Route Configurations:\n");
agent.getRoutes().forEach((route) => {
console.info(`\n🛤️ ${route.title}`);
const rules = route.getRules();
const prohibitions = route.getProhibitions();
if (rules.length > 0) {
console.info(` ✅ Rules (${rules.length}):`);
rules.forEach((rule, i) => console.info(` ${i + 1}. ${String(rule)}`));
}
if (prohibitions.length > 0) {
console.info(` ❌ Prohibitions (${prohibitions.length}):`);
prohibitions.forEach((prohibition, i) =>
console.info(` ${i + 1}. ${String(prohibition)}`)
);
}
});
/**
* Benefits explanation.
*/
console.info(`
💡 This demo shows how rules and prohibitions, combined with routing,
allow a single agent to handle diverse scenarios with tailored,
context-appropriate behavior.
`);
// Run demonstration
if (import.meta.url === `file://${process.argv[1]}`) {
demonstrateRulesAndProhibitions().catch((err) => console.error(err));
}
export { agent };