-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathadvanced_intent_classifier.php
More file actions
471 lines (388 loc) Β· 17.6 KB
/
advanced_intent_classifier.php
File metadata and controls
471 lines (388 loc) Β· 17.6 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
#!/usr/bin/env php
<?php
/**
* Advanced Intent Classifier Agent Example
*
* Demonstrates advanced features including:
* - Custom confidence thresholds
* - Intent hierarchies and routing
* - Dynamic intent management
* - Context-aware classification
* - Integration with conversation flows
*/
require_once __DIR__ . '/../vendor/autoload.php';
use ClaudeAgents\Agents\IntentClassifierAgent;
use ClaudePhp\ClaudePhp;
use Psr\Log\AbstractLogger;
// Enhanced console logger with colors
class ColorLogger extends AbstractLogger
{
private array $colors = [
'error' => "\033[0;31m",
'warning' => "\033[0;33m",
'info' => "\033[0;36m",
'debug' => "\033[0;37m",
'reset' => "\033[0m",
];
public function log($level, string|\Stringable $message, array $context = []): void
{
$timestamp = date('H:i:s');
$color = $this->colors[$level] ?? $this->colors['reset'];
$reset = $this->colors['reset'];
$emoji = match ($level) {
'error' => 'β',
'warning' => 'β οΈ',
'info' => 'βΉοΈ',
'debug' => 'π',
default => 'π',
};
echo "{$color}[{$timestamp}] {$emoji} [{$level}] {$message}{$reset}\n";
}
}
// Intent Router - Routes intents to appropriate handlers
class IntentRouter
{
private array $handlers = [];
private array $stats = [];
public function registerHandler(string $intent, callable $handler): void
{
$this->handlers[$intent] = $handler;
}
public function route(array $classification): array
{
$intent = $classification['intent'];
// Track statistics
if (!isset($this->stats[$intent])) {
$this->stats[$intent] = ['count' => 0, 'total_confidence' => 0];
}
$this->stats[$intent]['count']++;
$this->stats[$intent]['total_confidence'] += $classification['confidence'];
if (isset($this->handlers[$intent])) {
$response = call_user_func($this->handlers[$intent], $classification);
return [
'intent' => $intent,
'response' => $response,
'handled' => true,
];
}
return [
'intent' => $intent,
'response' => 'I\'m not sure how to handle that request.',
'handled' => false,
];
}
public function getStats(): array
{
$stats = [];
foreach ($this->stats as $intent => $data) {
$stats[$intent] = [
'count' => $data['count'],
'avg_confidence' => $data['total_confidence'] / $data['count'],
];
}
return $stats;
}
}
// Context Manager - Manages conversation context for better classification
class ClassificationContext
{
private array $history = [];
private int $maxHistory = 5;
private array $userProfile = [];
public function addClassification(array $classification): void
{
$this->history[] = $classification;
if (count($this->history) > $this->maxHistory) {
array_shift($this->history);
}
}
public function getRecentIntents(): array
{
return array_map(fn($c) => $c['intent'], $this->history);
}
public function setUserPreference(string $key, mixed $value): void
{
$this->userProfile[$key] = $value;
}
public function getUserProfile(): array
{
return $this->userProfile;
}
public function getContextSummary(): string
{
$recentIntents = array_slice($this->getRecentIntents(), -3);
return empty($recentIntents)
? 'No prior context'
: 'Recent intents: ' . implode(' β ', $recentIntents);
}
}
// Load environment
$dotenv = __DIR__ . '/../.env';
if (file_exists($dotenv)) {
$lines = file($dotenv, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
if (strpos(trim($line), '#') === 0) continue;
if (strpos($line, '=') === false) continue;
[$name, $value] = explode('=', $line, 2);
$_ENV[trim($name)] = trim($value);
}
}
$apiKey = $_ENV['ANTHROPIC_API_KEY'] ?? throw new RuntimeException('ANTHROPIC_API_KEY not set');
$client = new ClaudePhp(apiKey: $apiKey);
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
echo "β Advanced Intent Classifier Agent Example β\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
$logger = new ColorLogger();
// Example 1: Dynamic Intent Management
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
echo "Example 1: Dynamic Intent Management\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
$classifier = new IntentClassifierAgent($client, [
'name' => 'dynamic_classifier',
'logger' => $logger,
'confidence_threshold' => 0.7,
]);
// Start with basic intents
$classifier->addIntent('greeting', ['Hello', 'Hi'], 'Basic greeting');
$classifier->addIntent('help', ['Help me', 'I need help'], 'Help request');
echo "π Initial intents: " . implode(', ', array_keys($classifier->getIntents())) . "\n\n";
$result = $classifier->run('Hello there!');
$data = $result->getMetadata();
echo "π¬ \"Hello there!\" β Intent: {$data['intent']} ({$data['confidence']})\n\n";
// Dynamically add more intents
echo "β Adding new intents dynamically...\n";
$classifier->addIntent('order_status', [
'Where is my order',
'Track my package',
'Order status',
], 'Customer wants to check order status');
$classifier->addIntent('cancel_order', [
'Cancel my order',
'I want to cancel',
'Stop my order',
], 'Customer wants to cancel an order');
echo "π Updated intents: " . implode(', ', array_keys($classifier->getIntents())) . "\n\n";
$result = $classifier->run('Where is my package?');
$data = $result->getMetadata();
echo "π¬ \"Where is my package?\" β Intent: {$data['intent']} ({$data['confidence']})\n\n";
// Remove an intent
echo "β Removing 'greeting' intent...\n";
$classifier->removeIntent('greeting');
echo "π Final intents: " . implode(', ', array_keys($classifier->getIntents())) . "\n\n";
sleep(1);
// Example 2: Intent Routing System
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
echo "Example 2: Intent Routing with Custom Handlers\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
$routingClassifier = new IntentClassifierAgent($client, [
'name' => 'routing_classifier',
'confidence_threshold' => 0.65,
]);
$routingClassifier->addIntent('order_status', ['Where is my order', 'Track package']);
$routingClassifier->addIntent('return_request', ['Return item', 'I want to return']);
$routingClassifier->addIntent('product_inquiry', ['Tell me about', 'Product info']);
$routingClassifier->addIntent('complaint', ['I\'m unhappy', 'This is terrible']);
$routingClassifier->addEntityType('order_number', 'Order or tracking number');
$routingClassifier->addEntityType('product_name', 'Name of product');
$router = new IntentRouter();
// Register handlers for each intent
$router->registerHandler('order_status', function($classification) {
$orderNum = null;
foreach ($classification['entities'] as $entity) {
if ($entity['type'] === 'order_number') {
$orderNum = $entity['value'];
}
}
if ($orderNum) {
return "Looking up order {$orderNum}... Your order is out for delivery!";
}
return "Please provide your order number to check status.";
});
$router->registerHandler('return_request', function($classification) {
return "I'll help you start a return. Please provide your order number.";
});
$router->registerHandler('product_inquiry', function($classification) {
return "I'd be happy to provide product information. Which product are you interested in?";
});
$router->registerHandler('complaint', function($classification) {
return "I'm sorry to hear you're having issues. Let me connect you with a supervisor.";
});
$customerMessages = [
"Where is my order #12345?",
"I want to return this item",
"This product is terrible and doesn't work!",
"Tell me about the wireless headphones",
];
foreach ($customerMessages as $message) {
echo "π¬ Customer: \"{$message}\"\n";
$result = $routingClassifier->run($message);
if ($result->isSuccess()) {
$classification = $result->getMetadata();
$routingResult = $router->route($classification);
echo " π― Classified as: {$routingResult['intent']}\n";
echo " π‘ Response: {$routingResult['response']}\n";
echo " β
Handled: " . ($routingResult['handled'] ? 'Yes' : 'No') . "\n";
}
echo "\n";
}
echo "π Routing Statistics:\n";
foreach ($router->getStats() as $intent => $stats) {
echo " - {$intent}: {$stats['count']} times (avg confidence: "
. number_format($stats['avg_confidence'] * 100, 1) . "%)\n";
}
echo "\n";
sleep(1);
// Example 3: Context-Aware Classification
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
echo "Example 3: Context-Aware Intent Classification\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
$contextClassifier = new IntentClassifierAgent($client, [
'name' => 'context_classifier',
'confidence_threshold' => 0.6,
]);
$contextClassifier->addIntent('browse_products', ['Show me products', 'What do you have']);
$contextClassifier->addIntent('add_to_cart', ['Add to cart', 'I\'ll take it']);
$contextClassifier->addIntent('checkout', ['Checkout', 'Complete purchase']);
$contextClassifier->addIntent('modify_cart', ['Remove from cart', 'Change quantity']);
$context = new ClassificationContext();
$context->setUserPreference('location', 'US');
$context->setUserPreference('language', 'en');
$conversationFlow = [
"Show me your laptops",
"I'll take the MacBook Pro",
"Actually, add the wireless mouse too",
"Remove the mouse",
"Proceed to checkout",
];
echo "π E-commerce Conversation Flow:\n";
echo "User profile: " . json_encode($context->getUserProfile()) . "\n\n";
foreach ($conversationFlow as $i => $message) {
echo "Turn " . ($i + 1) . ":\n";
echo "π¬ User: \"{$message}\"\n";
echo "π Context: {$context->getContextSummary()}\n";
$result = $contextClassifier->run($message);
if ($result->isSuccess()) {
$classification = $result->getMetadata();
$context->addClassification($classification);
echo " π― Intent: {$classification['intent']}\n";
echo " π Confidence: " . number_format($classification['confidence'] * 100, 1) . "%\n";
if (!empty($classification['entities'])) {
echo " π¦ Entities: ";
echo implode(', ', array_map(
fn($e) => "{$e['type']}={$e['value']}",
$classification['entities']
));
echo "\n";
}
}
echo "\n";
}
sleep(1);
// Example 4: Multi-Level Intent Hierarchy
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
echo "Example 4: Hierarchical Intent Classification\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
// Level 1: Domain classifier
$domainClassifier = new IntentClassifierAgent($client, [
'name' => 'domain_classifier',
'confidence_threshold' => 0.7,
]);
$domainClassifier->addIntent('sales', ['Buy', 'Purchase', 'Price'], 'Sales related');
$domainClassifier->addIntent('support', ['Help', 'Problem', 'Issue'], 'Support related');
$domainClassifier->addIntent('account', ['Login', 'Password', 'Profile'], 'Account related');
// Level 2: Sales-specific classifier
$salesClassifier = new IntentClassifierAgent($client, [
'name' => 'sales_classifier',
]);
$salesClassifier->addIntent('product_info', ['Tell me about', 'Features of']);
$salesClassifier->addIntent('pricing', ['How much', 'Price', 'Cost']);
$salesClassifier->addIntent('purchase', ['Buy now', 'Order', 'Purchase']);
// Level 2: Support-specific classifier
$supportClassifier = new IntentClassifierAgent($client, [
'name' => 'support_classifier',
]);
$supportClassifier->addIntent('technical', ['Not working', 'Error', 'Bug']);
$supportClassifier->addIntent('how_to', ['How do I', 'Show me', 'Tutorial']);
$supportClassifier->addIntent('complaint', ['Unhappy', 'Disappointed', 'Bad']);
$testMessages = [
"How much does the premium plan cost?",
"My app keeps crashing when I export files",
"How do I reset my password?",
];
foreach ($testMessages as $message) {
echo "π¬ User: \"{$message}\"\n";
// Level 1: Determine domain
$domainResult = $domainClassifier->run($message);
if ($domainResult->isSuccess()) {
$domainData = $domainResult->getMetadata();
$domain = $domainData['intent'];
echo " π Domain: {$domain} (confidence: "
. number_format($domainData['confidence'] * 100, 1) . "%)\n";
// Level 2: Classify within domain
$specificClassifier = match($domain) {
'sales' => $salesClassifier,
'support' => $supportClassifier,
default => null,
};
if ($specificClassifier) {
$specificResult = $specificClassifier->run($message);
if ($specificResult->isSuccess()) {
$specificData = $specificResult->getMetadata();
echo " π― Specific Intent: {$specificData['intent']} (confidence: "
. number_format($specificData['confidence'] * 100, 1) . "%)\n";
echo " π Route to: {$domain}/{$specificData['intent']} handler\n";
}
}
}
echo "\n";
}
sleep(1);
// Example 5: Confidence-Based Escalation
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
echo "Example 5: Confidence-Based Escalation Strategy\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
$escalationClassifier = new IntentClassifierAgent($client, [
'name' => 'escalation_classifier',
'confidence_threshold' => 0.5, // Lower threshold for fallback
]);
$escalationClassifier->addIntent('simple_greeting', ['Hello', 'Hi']);
$escalationClassifier->addIntent('simple_help', ['Help', 'Assist me']);
$ambiguousMessages = [
"Hello!",
"Hmm, maybe you can help?",
"asdfghjkl", // Complete gibberish
"What about the thing with the stuff?",
];
foreach ($ambiguousMessages as $message) {
echo "π¬ User: \"{$message}\"\n";
$result = $escalationClassifier->run($message);
if ($result->isSuccess()) {
$data = $result->getMetadata();
$confidence = $data['confidence'];
echo " π― Intent: {$data['intent']}\n";
echo " π Confidence: " . number_format($confidence * 100, 1) . "%\n";
// Escalation logic based on confidence
if ($confidence >= 0.85) {
echo " β
Action: Handle automatically\n";
} elseif ($confidence >= 0.65) {
echo " β οΈ Action: Handle with clarification\n";
} elseif ($confidence >= 0.5) {
echo " π€ Action: Request more information\n";
} else {
echo " π Action: Escalate to human agent\n";
}
}
echo "\n";
}
// Summary
echo str_repeat("β", 80) . "\n";
echo "β¨ Advanced Intent Classifier example completed!\n\n";
echo "π Summary of Advanced Features:\n";
echo " - Dynamic intent management (add/remove at runtime)\n";
echo " - Intent routing with custom handlers\n";
echo " - Context-aware classification with conversation history\n";
echo " - Hierarchical intent classification (domain β specific)\n";
echo " - Confidence-based escalation strategies\n";
echo " - Statistics tracking and analytics\n";
echo " - Real-world e-commerce conversation flow\n";
echo str_repeat("β", 80) . "\n";