简体   繁体   中英

How to print the answer returned by IBM Watson Assistant?

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)

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

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)  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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