Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Preview
Start a free Basic trial
to watch this video
Moving away from the browser-based tools, let's now take a look at how to query the Discovery service from our app, using its API.
Documentation
Supporting Courses
- Node.js Basics: Remember to check out our Node course if you want more help understanding how to write a Node app that can consume an API like this.
- Express Basics: Express is used for the web client code that users interact with.
- REST API Basics: This short course explains how REST APIs (like the Watson APIs) are designed and used.
Final Project Files
This finished code is available for download as a zip or from our GitHub repo. Individual files available for this video:
Code for Copy/Paste
.env
# Discovery Service
DISCOVERY_URL=https://gateway.watsonplatform.net/discovery/api
DISCOVERY_COLLECTION_ID=<add your collection ID>
DISCOVERY_ENVIRONMENT_ID=<add your environment ID>
DISCOVERY_USERNAME=<add your username>
DISCOVERY_PASSWORD=<add your password>
DISCOVERY_VERSION_DATE=2017-10-17
# Environment variables
INTENT_CONFIDENCE=0.75
app.js (wrapper)
var discovery = new watsonDiscovery({
url: process.env.DISCOVERY_URL,
username: process.env.DISCOVERY_USERNAME || '<username>',
password: process.env.DISCOVERY_PASSWORD || '<password>',
version_date: process.env.DISCOVERY_VERSION_DATE,
version: 'v1'
});
var intentConfidence = process.env.INTENT_CONFIDENCE;
app.js (else if)
// Check the confidence level and forward text to the Discovery service, if needed
else if (data.input.text !== "start conversation" && data.intents.length > 0 && data.intents[0].confidence < intentConfidence) {
// Log the Conversation repsonse for us to explore
console.log("Logging the response from the Conversation service:");
console.log(data);
// return discovery data
var response = {
"input": {"text": req.body.input.text},
"context": data.context,
"output": {"text": []}
};
var version_date = process.env.DISCOVERY_VERSION_DATE;
var environment_id = process.env.DISCOVERY_ENVIRONMENT_ID;
var collection_id = process.env.DISCOVERY_COLLECTION_ID;
discovery.query({
version_date: version_date,
environment_id: environment_id,
collection_id: collection_id,
query: req.body.input.text,
count: 5
},
(err, data) => {
if (err) {
console.log("Error: ");
console.log(err);
return res.status(err.code || 500).json(err);
}
if (data.results.length > 0) {
for(var i = 0; i < data.results.length; i++) {
response.output.text.push(data.results[i]); // keep this use-case agnostic;
}
} else {
response.output.text.push("I cannot find an answer to your question.");
}
return res.json(response);
}
);
}
You need to sign up for Treehouse in order to download course files.
Sign up