-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCourseAdvisor.js
124 lines (107 loc) · 2.75 KB
/
CourseAdvisor.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
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
const DiscoveryV1 = require("ibm-watson/discovery/v1");
async function queryDiscovery(
environmentId,
collectionId,
discoveryUsername,
discoveryPassword,
query,
url
) {
// Function to query Discovery
try {
const discovery = new DiscoveryV1({
version: "2019-02-01",
username: discoveryUsername,
password: discoveryPassword,
url: url
});
const queryResult = await discovery.query({
environment_id: environmentId,
collection_id: collectionId,
query: query
});
return queryResult;
} catch (err) {
throw new Error(err.message);
}
}
async function recommendCourse(queryResult) {
try {
const courses = [];
queryResult.results.forEach(result => {
if (courses.length <= 3) {
const course = {
name: result.name,
link: `https://www.edx.org/search?q=${result.slug}`,
description: result.description.split(".")[0]
};
courses.push(course);
}
});
if (courses.length === 0) {
throw new Error("No courses are found");
}
return { courses };
} catch (err) {
throw new Error(err.message);
}
}
async function answerFaq(queryResult) {
try {
textContent = queryResult.results[0].content;
textContent = textContent.replace(/\n/g,"<br/>")
link = queryResult.results[0].source;
return {
res: textContent+"<br/><a href='"+link+"'>Click here for more</a>"
}
} catch (err) {
throw new Error("Sorry, we are unable to find the answer from Help Centre.");
}
}
const CourseraAdvisor = {
async connectDiscovery(params) {
const {
discoveryUsername,
discoveryPassword,
environmentId,
collectionId,
input,
intent,
url
} = params;
try {
let enrichedField;
if (intent === "course_recommendation") {
enrichedField = "description";
} else if (intent === "faq") {
enrichedField = "content";
} else {
throw new Error(`Intent: ${intent} cannot be recognized`);
}
const queryString = `enriched_${enrichedField}.keywords.text: ${input}`;
const queryResult = await queryDiscovery(
environmentId,
collectionId,
discoveryUsername,
discoveryPassword,
queryString,
url
);
if (!queryResult) {
return "No query result found";
} else if (!queryResult.results) {
return queryResult;
}
let res;
if (intent === "course_recommendation") {
res = await recommendCourse(queryResult);
} else {
res = await answerFaq(queryResult);
}
return res;
} catch (err) {
return { err: err.message };
}
}
};
module.exports = CourseraAdvisor;