-->

How to print the answer returned by IBM Watson Ass

2019-09-21 02:51发布

问题:

I have a Python Flask app that tries to use IBM Watson Assistant. Below is a code snippet that invokes the message API function. How do I print the returned answer?

import json, _watson, requests, jsonify
import watson_developer_cloud
from flask import Flask, render_template
from flask_socketio import SocketIO, send


@app.route('/')
def index():
    return render_template('index.html')


@socketio.on('message')
def handleMessage(msg):
    print("Message: "+msg)
    msg = _watson.conversacion(msg)
    send(msg, broadcast=False)

def conversacion(mensaje):
    response = assistant.message(workspace_id='1bef94fd-be51-4996-956c-73f9d0f08c41', input={'text': mensaje})
    mens = (json.dumps(response, indent=2))
    msj = json.loads(mens)
    # print(json.dumps(response, indent=2))
    print(msj["output"]["text"][0])  # mensaje de respuesta
    rewa = (msj["output"]["text"][0])
    return rewa


if __name__=='__main__':
    socketio.run(app)

回答1:

Your code does not show how you set up and configure the Python SDK with the credentials for IBM Watson Assistant. The message function with its input and output is documented here in the API reference. If you use json.dumps on the returned message object, you can see the result (response) structure.

The result structure depends on the API version which you configure during the SDK initialization (not shown in your code). It can have only text as an array or, with latest API versions, can contain images, options to choose from and more. All is returned in a JSON structure under the output element (which is shown in your code).



回答2:

Post your returned answer to another page

@app.route(/returned_answer/<mensaje>)
def conversacion(mensaje):
        response = assistant.message(workspace_id='1bef94fd-be51-4996-956c-73f9d0f08c41', input={'text': mensaje})
        mens = (json.dumps(response, indent=2))
        msj = json.loads(mens)
        # print(json.dumps(response, indent=2))
        print(msj["output"]["text"][0])  # mensaje de respuesta
        rewa = (msj["output"]["text"][0])
        return rewa

giver your input messages a message tag , , and in your index page write html code to embed the /returned_answer messages in index page

  <button onclick="window.location.href = ('/returned_answer/'+document.getElementById('message_id').value)