【问题标题】:How to print the answer returned by IBM Watson Assistant?如何打印 IBM Watson Assistant 返回的答案?
【发布时间】:2018-10-16 04:27:51
【问题描述】:

我有一个尝试使用 IBM Watson Assistant 的 Python Flask 应用程序。下面是调用消息 API 函数的代码 sn-p。如何打印返回的答案?

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)

【问题讨论】:

    标签: python flask ibm-cloud ibm-watson watson-conversation


    【解决方案1】:

    您的代码未显示您如何设置和配置Python SDK with the credentials for IBM Watson Assistantmessage function with its input and output is documented here in the API reference。如果在返回的消息对象上使用json.dumps,则可以看到result (response) structure

    结果结构取决于您在 SDK 初始化期间配置的 API version(未在您的代码中显示)。它可以只有文本作为数组,或者使用最新的 API 版本,可以包含图像、可供选择的选项等等。所有内容都在 output 元素下的 JSON 结构中返回(显示在您的代码中)。

    【讨论】:

      【解决方案2】:

      将您返回的答案发布到另一个页面

      @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
      

      给你的输入消息一个消息标签, ,并在您的索引页面中编写 html 代码以在索引页面中嵌入 /returned_answer 消息

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

      【讨论】:

      • 您能在此处添加适当的代码 sn-p 作为您的答案吗?指向外部资源的链接不太适合本网站的答案。
      • @L.ScottJohnson 感谢您的反馈,这里是新的,并将遵守
      猜你喜欢
      • 2019-10-02
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多