簡體   English   中英

使用node.js的Watson api

[英]Watson api using node.js

我正在嘗試使用此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);

這些代碼的大部分是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));

節點是異步的,因此響應在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應用程序中所需的基礎知識。

所有代碼都是處理對Watson問答服務的HTTPS請求。

如果要在IOs應用程序中使用該服務,則必須:

  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. http://my-cool-app.mybluemix.net/api/question?question=Watson調用您的API

筆記:

對於IOs應用程序,您可以使用AFNetworking

您還應該在此處閱讀有關問題和答案服務文檔的內容,並在此處閱讀有關服務API的信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM