forked from wit-ai/wit-api-only-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
5-generate-answers.js
82 lines (79 loc) · 2.18 KB
/
5-generate-answers.js
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
const {
FIREBASE_CONFIG,
queryWit,
interactive,
firstEntity,
validateSamples,
} = require('../shared');
const firebase = require('firebase');
const N = 3;
const THRESHOLD = 0.7;
function generateIntentValue(text) {
return text.toLowerCase().replace(/\W/g, '');
}
function recordAnswer(question, readline) {
console.log('🤖 How would you answer this question?');
readline.question('answer > ', answer => {
const newValue = generateIntentValue(answer);
validateSamples([
{
text: question,
entities: [
{
entity: 'intent',
value: newValue,
},
],
},
])
.then(({n}) => console.log(`validated ${n}!`))
.then(() => {
return firebase.database().ref(`answers/${newValue}`).set(answer);
console.log('🤖 ok! saved');
readline.prompt();
});
});
}
function handleMessage(question, readline) {
return queryWit(question, N).then(({entities}) => {
const intents = entities['intent'] || [];
const bestIntent = intents[0];
const dateTime = firstEntity(entities, 'datetime') || {};
if (!bestIntent || bestIntent.confidence < THRESHOLD) {
console.log('🤖 what would you like to do?');
intents.forEach(intent => console.log(`\n -- ${intent.value}`));
console.log('\n -- new');
readline.question('choice > ', choice => {
if (choice === 'new') {
recordAnswer(question, readline);
return;
}
console.log(`🤖 okay, running > ${choice}`);
validateSamples([
{
text: question,
entities: [
{
entity: 'intent',
value: choice,
},
],
},
])
.then(({n}) => console.log(`validated ${n}!`))
.then(() => readline.prompt());
});
return;
}
return firebase
.database()
.ref(`answers/${bestIntent.value}`)
.once('value')
.then(snapshot => {
const val = snapshot.val();
console.log(`🤖 ${val || bestIntent.value}`, dateTime);
});
});
}
firebase.initializeApp(FIREBASE_CONFIG);
interactive(handleMessage);