6

我正在尝试使用此 node.js 代码来使用我们 ios 应用程序中 ibm cloud bluemix 中的 watson api。谁能告诉我这段代码在做什么,并为我们提供如何使用我们应用程序中的 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);
4

2 回答 2

6

大部分代码是 Node 和在 BlueMix 环境中执行所必需的。VCAP_SERVICES是 Bluemix 环境变量,您可以使用它来获取您有兴趣使用的给定服务的凭证。在这种情况下,service_name设置为“question_and_answer”以访问问答平台服务。

在您的Bluemix 环境中,您应该有一个问答服务实例和一个应用程序。当应用程序绑定到问答服务时,它会创建一个服务绑定。服务绑定具有访问服务实例的应用程序凭据。在这种情况下,VCAP_SERVICES包含用于与服务实例通信和验证的绑定的URL用户名密码。

从您的 iOS 应用程序中,您将需要一些东西。首先,您需要一个服务绑定,现在您必须在 Bluemix 中创建它。在 Bluemix 中获得凭据后,您就可以在 iOS 应用程序中使用这些凭据。或者,您可以在 Bluemix 上托管一个应用程序并让它处理与 Watson 的通信。

接下来,您需要能够调用问答服务,它是一个 RESTful 服务。在上面的代码中,变量options包含向 Watson 服务发布问题所需的信息。请注意,service_url从凭证获得的附加路径信息附加了使用 Watson For Healthcare 域的路径信息。

从那里您可以创建您的问题。变量questionData包含上面代码中的问题。该question.questionText属性设置为您想问 Watson 的问题,例如“我应该每天服用阿司匹林吗?”。

然后,您可以将问题发布到 Watson,如下面的代码片段所示:

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

Node 是异步的,所以响应在http.request(...). 答案被发送回请求的应用程序

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})
   })

其余代码是特定于节点的。但我已经概述了您在 iOS 应用程序中需要的基础知识。

于 2014-11-05T20:17:57.750 回答
3

所有代码都用于处理对Watson Question and Answer服务的 HTTPS 请求。

如果您想在您的 IO 应用程序中使用该服务,您必须:

  1. 修改 nodejs 代码并添加 REST API 功能。

    例如,您应该有一个端点来接收问题并返回答案:

    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. 在 bluemix 中启动您的应用程序并保存 URL,它将类似于:

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

笔记:

对于 IO 应用程序,您可以使用AFNetworking

您还应该在此处阅读有关问答服务文档的移动,并在此处阅读有关服务 API 的信息

于 2014-11-06T15:31:27.567 回答