简体   繁体   English

使用node.js的Watson api

[英]Watson api using node.js

I am trying to use this node.js code to use watson api which is in ibm cloud bluemix in our ios app. 我正在尝试使用此node.js代码来使用我们的ios应用程序中的ibm cloud bluemix中的watson api。 Can anybody tell me what this code is doing and provide us an answer how to use the watson service from our app. 任何人都可以告诉我这段代码在做什么,并为我们提供如何使用我们的应用程序中的watson服务的答案。

var express = require('express');
var https = require('https');
var url = require('url');

// setup middleware

var app = express();
app.use(express.errorHandler());
app.use(express.urlencoded()); // to support URL-encoded bodies
app.use(app.router);

app.use(express.static(__dirname + '/public')); //setup static public directory
app.set('view engine', 'jade');
app.set('views', __dirname + '/views'); //optional since express defaults to CWD/views

// There are many useful environment variables available in process.env.
// VCAP_APPLICATION contains useful information about a deployed application.

var appInfo = JSON.parse(process.env.VCAP_APPLICATION || "{}");
// TODO: Get application information and use it in your app.

// defaults for dev outside bluemix

var service_url = '<service_url>';
var service_username = '<service_username>';
var service_password = '<service_password>';

// VCAP_SERVICES contains all the credentials of services bound to
// this application. For details of its content, please refer to
// the document or sample of each service.

if (process.env.VCAP_SERVICES) {
  console.log('Parsing VCAP_SERVICES');
  var services = JSON.parse(process.env.VCAP_SERVICES);

//service name, check the VCAP_SERVICES in bluemix to get the name of the services you have

var service_name = 'question_and_answer';

  if (services[service_name]) {
    var svc = services[service_name][0].credentials;
    service_url = svc.url;
    service_username = svc.username;
    service_password = svc.password;
  } else {
    console.log('The service '+service_name+' is not in the VCAP_SERVICES, did you forget to bind it?');
  }

} else {
  console.log('No VCAP_SERVICES found in ENV, using defaults for local development');
}

console.log('service_url = ' + service_url);
console.log('service_username = ' + service_username);
console.log('service_password = ' + new Array(service_password.length).join("X"));

var auth = "Basic " + new Buffer(service_username + ":" +    service_password).toString("base64");

// render index page

app.get('/', function(req, res){
    res.render('index');
});

// Handle the form POST containing the question to ask Watson and reply with the answer

app.post('/', function(req, res){

// Select healthcare as endpoint 

var parts = url.parse(service_url +'/v1/question/healthcare');
// create the request options to POST our question to Watson

var options = { host: parts.hostname,
    port: parts.port,
    path: parts.pathname,
    method: 'POST',
    headers: {
      'Content-Type'  :'application/json',
      'Accept':'application/json',
      'X-synctimeout' : '30',
      'Authorization' :  auth }
  };

// Create a request to POST to Watson

var watson_req = https.request(options, function(result) {
    result.setEncoding('utf-8');
    var response_string = '';

    result.on('data', function(chunk) {
      response_string += chunk;
    });

    result.on('end', function() {
      var answers_pipeline = JSON.parse(response_string),
          answers = answers_pipeline[0];
      return res.render('index',{'questionText': req.body.questionText, 'answers': answers})
   })

  });

  watson_req.on('error', function(e) {
    return res.render('index', {'error': e.message})
  });

// create the question to Watson

var questionData = {
    'question': {
      'evidenceRequest': { 
        'items': 5 // the number of anwers
      },
      'questionText': req.body.questionText // the question
    }
  };

// Set the POST body and send to Watson

 watson_req.write(JSON.stringify(questionData));
 watson_req.end();

});

// The IP address of the Cloud Foundry DEA (Droplet Execution Agent) that hosts this application:

var host = (process.env.VCAP_APP_HOST || 'localhost');
// The port on the DEA for communication with the application:

var port = (process.env.VCAP_APP_PORT || 3000);
// Start server

app.listen(port, host);

Majority of this code is required for Node and for executing in the BlueMix environment. 这些代码的大部分是Node需要的,并且在BlueMix环境中执行。 VCAP_SERVICES is the Bluemix environment variable that you use to obtain credentials for a given service that you are interested in using. VCAP_SERVICES是Bluemix环境变量,可用于获取您感兴趣的给定服务的凭据。 In this case the service_name is set to "question_and_answer" to access the Question and Answer platform service. 在这种情况下, service_name设置为“question_and_answer”以访问问答平台服务。

In your Bluemix environment, you should have a Question and Answer service instance and an application. 在Bluemix环境中,您应该有一个问答服务实例和一个应用程序。 When the application is bound to the Question and Answer service it creates a service binding. 当应用程序绑定到问答服务时,它会创建服务绑定。 The service binding has the application credentials to access the service instance. 服务绑定具有访问服务实例的应用程序凭据。 In this case, VCAP_SERVICES contains the URL , username and password of the binding used to communicated and authenticate with the service instance. 在这种情况下, VCAP_SERVICES包含用于与服务实例进行通信和身份验证的绑定的URL用户名密码

From your iOS app you will need a couple of things. 从您的iOS应用程序,您将需要一些东西。 First, you need a service binding and you have to, for now, create that in Bluemix. 首先,您需要一个服务绑定,并且您现在必须在Bluemix中创建它。 Once you have the credentials in Bluemix then you may use those in your iOS app. 获得Bluemix中的凭据后,您可以在iOS应用中使用这些凭据。 Or you could host an application on Bluemix and let that handle communication with Watson. 或者您可以在Bluemix上托管应用程序,并让它处理与Watson的通信。

Next, you need the capability to invoke the Question and Answer service which is a RESTful service. 接下来,您需要能够调用问答服务,这是一项RESTful服务。 In the code above, the variable options contains the necessary information to POST a question to the Watson service. 在上面的代码中,变量options包含将问题发布到Watson服务的必要信息。 Note that the service_url obtained from the credentials is appended with an additional path information to use the Watson For Healthcare domain. 请注意,从凭证获取的service_url附加了一个额外的路径信息,以使用Watson For Healthcare域。

From there you can create your question. 从那里你可以创建你的问题。 Variable questionData contains the question in the code above. 变量questionData包含上面代码中的问题。 The question.questionText property is set to the question that you want to ask Watson, like, "Should I take aspirin on a daily basis?". question.questionText属性设置为你想问Watson的问题,比如,“我应该每天服用阿司匹林吗?”。

Then you can POST the question to Watson, as the following snippet does: 然后您可以将问题发布到Watson,如下面的代码片段所示:

watson_req.write(JSON.stringify(questionData));

Node is asynchronous, so the response is handled in the http.request(...) . 节点是异步的,因此响应在http.request(...) The answer is sent back to the requesting application in 答案将发送回请求的应用程序

result.on('end', function() {
  var answers_pipeline = JSON.parse(response_string),
      answers = answers_pipeline[0];
  return res.render('index',{'questionText': req.body.questionText, 'answers': answers})
   })

Rest of the code is node specific. 其余代码是特定于节点的。 But I've outlined the basics that you need in your iOS application. 但我已经概述了iOS应用程序中所需的基础知识。

All the code is to handle a HTTPS request to the Watson Question and Answer service. 所有代码都是处理对Watson问答服务的HTTPS请求。

If you want to use the service in your IOs app you will have to: 如果要在IOs应用程序中使用该服务,则必须:

  1. Modify the nodejs code and add REST API capabilities. 修改nodejs代码并添加REST API功能。

    For example, you should have an endpoint to receive a questions and return answers: 例如,您应该有一个端点来接收问题并返回答案:

     app.get('/api/question', function(req, res){ // Call the service with a question and get an array with the answers var answers = watson.question(req.query); // Send the answers and the question to the client in json res.json({answers: answers, question: req.query.question}); }); 
  2. Start your app in bluemix and save the URL, it will be something like: 在bluemix中启动您的应用并保存URL,它将类似于:

      http://my-cool-app.mybluemix.net 
  3. Call your API at http://my-cool-app.mybluemix.net/api/question?question=Watson http://my-cool-app.mybluemix.net/api/question?question=Watson调用您的API

Notes: 笔记:

For the IOs app you can use AFNetworking . 对于IOs应用程序,您可以使用AFNetworking

You should also read move about the question and answer service documentation here , and read the about the service API here 您还应该在此处阅读有关问题和答案服务文档的内容,并在此处阅读有关服务API的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM