-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathintent_classifier.php
More file actions
293 lines (244 loc) Β· 10.8 KB
/
intent_classifier.php
File metadata and controls
293 lines (244 loc) Β· 10.8 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
#!/usr/bin/env php
<?php
/**
* Intent Classifier Agent Basic Example
*
* Demonstrates basic usage of the IntentClassifierAgent for intent classification
* and entity extraction in conversational AI applications.
*/
require_once __DIR__ . '/../vendor/autoload.php';
use ClaudeAgents\Agents\IntentClassifierAgent;
use ClaudePhp\ClaudePhp;
use Psr\Log\AbstractLogger;
// Simple console logger
class ConsoleLogger extends AbstractLogger
{
public function log($level, string|\Stringable $message, array $context = []): void
{
$timestamp = date('H:i:s');
$emoji = match ($level) {
'error' => 'β',
'warning' => 'β οΈ',
'info' => 'βΉοΈ',
default => 'π',
};
echo "[{$timestamp}] {$emoji} [{$level}] {$message}\n";
}
}
// 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 "β Intent Classifier Agent Basic Example β\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
// Create intent classifier with logger
$logger = new ConsoleLogger();
$classifier = new IntentClassifierAgent($client, [
'name' => 'demo_classifier',
'logger' => $logger,
'confidence_threshold' => 0.6,
]);
echo "π€ Intent Classifier initialized\n\n";
// Example 1: Basic Intent Classification
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
echo "Example 1: Basic Intent Classification\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
// Define intents
$classifier->addIntent('greeting', [
'Hello',
'Hi there',
'Good morning',
'Hey',
], 'User wants to greet or start a conversation');
$classifier->addIntent('goodbye', [
'Bye',
'Goodbye',
'See you later',
'Have a good day',
], 'User wants to end the conversation');
$classifier->addIntent('help', [
'I need help',
'Can you help me',
'Help please',
], 'User needs assistance');
$testInputs = [
'Hello! How are you today?',
'Goodbye, thanks for your help!',
'I need some help with my account',
];
foreach ($testInputs as $input) {
echo "π¬ User input: \"{$input}\"\n";
$result = $classifier->run($input);
if ($result->isSuccess()) {
$data = $result->getMetadata();
echo " π― Intent: {$data['intent']}\n";
echo " π Confidence: " . number_format($data['confidence'] * 100, 1) . "%\n";
if (!empty($data['entities'])) {
echo " π¦ Entities:\n";
foreach ($data['entities'] as $entity) {
echo " - {$entity['type']}: {$entity['value']}\n";
}
}
} else {
echo " β Error: {$result->getError()}\n";
}
echo "\n";
}
sleep(1);
// Example 2: Entity Extraction
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
echo "Example 2: Intent Classification with Entity Extraction\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
$classifier->addIntent('book_flight', [
'I want to book a flight',
'Book me a flight to Paris',
'I need to fly to London tomorrow',
], 'User wants to book a flight');
$classifier->addIntent('check_weather', [
'What\'s the weather like',
'Will it rain today',
'Weather forecast for tomorrow',
], 'User wants to check weather information');
// Define custom entity types
$classifier->addEntityType('destination', 'City or country name');
$classifier->addEntityType('date', 'Travel date or time period');
$classifier->addEntityType('location', 'Geographic location');
$testInputs2 = [
'I want to book a flight to Tokyo next Monday',
'What\'s the weather like in New York today?',
'Book me a ticket to London for December 25th',
];
foreach ($testInputs2 as $input) {
echo "π¬ User input: \"{$input}\"\n";
$result = $classifier->run($input);
if ($result->isSuccess()) {
$data = $result->getMetadata();
echo " π― Intent: {$data['intent']}\n";
echo " π Confidence: " . number_format($data['confidence'] * 100, 1) . "%\n";
if (!empty($data['entities'])) {
echo " π¦ Entities extracted:\n";
foreach ($data['entities'] as $entity) {
echo " - {$entity['type']}: \"{$entity['value']}\"\n";
}
} else {
echo " π¦ No entities found\n";
}
}
echo "\n";
}
sleep(1);
// Example 3: Chatbot Intent Recognition
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
echo "Example 3: Customer Support Chatbot Intents\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
// Create a new classifier for customer support
$supportClassifier = new IntentClassifierAgent($client, [
'name' => 'support_classifier',
'confidence_threshold' => 0.65,
'fallback_intent' => 'need_human_agent',
]);
// Define support intents
$supportClassifier->addIntent('account_issue', [
'I can\'t log in',
'My account is locked',
'I forgot my password',
], 'User has problems with their account');
$supportClassifier->addIntent('billing_question', [
'Why was I charged',
'I have a question about my bill',
'Refund request',
], 'User has billing or payment questions');
$supportClassifier->addIntent('technical_problem', [
'The app is crashing',
'Feature not working',
'I found a bug',
], 'User is experiencing technical issues');
$supportClassifier->addIntent('feature_request', [
'Can you add this feature',
'I suggest implementing',
'It would be great if',
], 'User wants to request a new feature');
// Define support-specific entities
$supportClassifier->addEntityType('account_number', 'User account or order number');
$supportClassifier->addEntityType('amount', 'Monetary amount');
$supportClassifier->addEntityType('feature_name', 'Name of app feature or functionality');
$supportQueries = [
"I can't log into my account #12345",
"Why was I charged $99.99 last week?",
"The export feature keeps crashing on my phone",
"Can you add dark mode to the app?",
"Something weird is happening but I'm not sure what",
];
foreach ($supportQueries as $query) {
echo "π¬ Customer: \"{$query}\"\n";
$result = $supportClassifier->run($query);
if ($result->isSuccess()) {
$data = $result->getMetadata();
$confidence = $data['confidence'];
echo " π― Intent: {$data['intent']}\n";
echo " π Confidence: " . number_format($confidence * 100, 1) . "%\n";
if (!empty($data['entities'])) {
echo " π¦ Extracted entities:\n";
foreach ($data['entities'] as $entity) {
echo " - {$entity['type']}: \"{$entity['value']}\"\n";
}
}
// Route based on intent
if ($data['intent'] === 'need_human_agent') {
echo " π Action: Transfer to human agent (low confidence)\n";
} else {
echo " π Action: Route to {$data['intent']} handler\n";
}
}
echo "\n";
}
sleep(1);
// Example 4: Multi-Language Support
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n";
echo "Example 4: Multi-Language Intent Classification\n";
echo "ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ\n\n";
$multiLangClassifier = new IntentClassifierAgent($client, [
'name' => 'multilang_classifier',
]);
$multiLangClassifier->addIntent('greeting', [
'Hello', 'Bonjour', 'Hola', 'Ciao', 'Hallo',
], 'Greeting in any language');
$multiLangClassifier->addIntent('help_request', [
'Help me', 'Aidez-moi', 'AyΓΊdame', 'Aiutami', 'Hilf mir',
], 'Request for help in any language');
$multiLangInputs = [
'Bonjour! Comment allez-vous?', // French
'Hola, necesito ayuda', // Spanish
'Ciao, come stai?', // Italian
'Hallo, ich brauche Hilfe', // German
];
foreach ($multiLangInputs as $input) {
echo "π¬ Input: \"{$input}\"\n";
$result = $multiLangClassifier->run($input);
if ($result->isSuccess()) {
$data = $result->getMetadata();
echo " π― Intent: {$data['intent']}\n";
echo " π Confidence: " . number_format($data['confidence'] * 100, 1) . "%\n";
}
echo "\n";
}
// Summary
echo str_repeat("β", 80) . "\n";
echo "β¨ Intent Classifier example completed!\n\n";
echo "π Summary:\n";
echo " - Classified various user intents with confidence scores\n";
echo " - Extracted entities from user input (dates, locations, etc.)\n";
echo " - Demonstrated customer support use case\n";
echo " - Showed multi-language classification capabilities\n";
echo " - Used confidence thresholds for fallback routing\n";
echo str_repeat("β", 80) . "\n";