Получить параметры контекста Dialogflow из последующего намерения в Python - PullRequest
0 голосов
/ 19 июня 2020

Я создал приложение flask в python для отправки текста в Dialogflow, чтобы определить намерение и вернуть текст выполнения в качестве ответа от него.

Затем я расширил это, чтобы также вернуться по текст выполнения - определенный параметр из результата запроса, который также работает, и я получаю его так:

 orderid = (response.query_result.parameters.fields["ordernumber"])
        orderid_json = json.loads(MessageToJson(orderid))

Теперь мои проблемы начались, когда я добавил последующее намерение, потому что тогда я не могу прочитать параметр, поскольку он является частью контекста.

Ответ RAW API для моего намерения order.status выглядит следующим образом:

{
  "responseId": "7ae77c38-501a-4079-b0e0-24807669c826-83ffff32",
  "queryResult": {
    "queryText": "check my order 456789",
    "action": "order.status",
    "parameters": {
      "ordernumber": "456789"
    },
    "allRequiredParamsPresent": true,
    "fulfillmentText": "Uh-oh, your order seems to be delayed and the exptected delivery date is: 29.06.2020Would you like to talk with an agent about this delay?",
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            "Uh-oh, your order seems to be delayed and the exptected delivery date is: 29.06.2020Would you like to talk with an agent about this delay?"
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/voicebotdemo-hdnmue/agent/sessions/5ea2f271-1e00-5041-5f23-f05c73bd1a95/contexts/orderstatus-followup",
        "lifespanCount": 2,
        "parameters": {
          "ordernumber.original": "456789",
          "ordernumber": "456789"
        }
      },
      {
        "name": "projects/voicebotdemo-hdnmue/agent/sessions/5ea2f271-1e00-5041-5f23-f05c73bd1a95/contexts/ordernumber",
        "lifespanCount": 5,
        "parameters": {
          "ordernumber": "456789",
          "ordernumber.original": "456789"
        }
      }
    ],
    "intent": {
      "name": "projects/voicebotdemo-hdnmue/agent/intents/fcb8a584-5ca1-41c7-b67e-34a35dd53602",
      "displayName": "order.status"
    },
    "intentDetectionConfidence": 0.8599001,
    "diagnosticInfo": {
      "webhook_latency_ms": 156
    },
    "languageCode": "en",
    "sentimentAnalysisResult": {
      "queryTextSentiment": {
        "score": -0.3,
        "magnitude": 0.3
      }
    }
  },
  "webhookStatus": {
    "message": "Webhook execution successful"
  }
}

и ответ для последующего намерения order.status-yes вот так:

    {
  "responseId": "8c63e43d-ff01-430b-becf-be8f8fa40839-83ffff32",
  "queryResult": {
    "queryText": "why not",
    "action": "orderstatus.orderstatus-yes",
    "parameters": {},
    "allRequiredParamsPresent": true,
    "fulfillmentText": "Routing you to an agent now!",
    "fulfillmentMessages": [
      {
        "text": {
          "text": [
            "Routing you to an agent now!"
          ]
        }
      }
    ],
    "outputContexts": [
      {
        "name": "projects/voicebotdemo-hdnmue/agent/sessions/5ea2f271-1e00-5041-5f23-f05c73bd1a95/contexts/ordernumber",
        "lifespanCount": 5,
        "parameters": {
          "ordernumber": "456789",
          "ordernumber.original": "456789"
        }
      },
      {
        "name": "projects/voicebotdemo-hdnmue/agent/sessions/5ea2f271-1e00-5041-5f23-f05c73bd1a95/contexts/orderstatus-followup",
        "lifespanCount": 1,
        "parameters": {
          "ordernumber": "456789",
          "ordernumber.original": "456789"
        }
      }
    ],
    "intent": {
      "name": "projects/voicebotdemo-hdnmue/agent/intents/1a3a01da-cdf4-4dc6-b0d6-4c28c9a0bca7",
      "displayName": "order.status - yes"
    },
    "intentDetectionConfidence": 1,
    "languageCode": "en",
    "sentimentAnalysisResult": {
      "queryTextSentiment": {
        "score": 0.3,
        "magnitude": 0.3
      }
    }
  }
}

Ответ на последующее намерение не содержит никаких параметров. Итак, мой вопрос: как я могу прочитать параметр номер заказа из "outputContexts" вместо "queryResult" ?

Вот мой полный скрипт:

import json
import os
import dialogflow_v2

from flask import Flask
from flask import request
from google.api_core.exceptions import InvalidArgument
from google.protobuf.json_format import MessageToJson


proxy = 'http://10.7.111.18:8080'

os.environ['http_proxy'] = proxy
os.environ['HTTP_PROXY'] = proxy
os.environ['https_proxy'] = proxy
os.environ['HTTPS_PROXY'] = proxy


os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = 'private_key_easteregg.json'

DIALOGFLOW_PROJECT_ID = 'voicebotdemo-hdnmue'
DIALOGFLOW_LANGUAGE_CODE = 'en'
SESSION_ID = 'me'


app = Flask(__name__)


@app.route('/call/user_input_flask', methods=['GET', 'POST', 'PUT', 'DELETE'])
def user_input_flask():
    #req_data = request.get_json(dict)
    input_text_from_web = request.form.get('input', '')
    session_client = dialogflow_v2.SessionsClient()
    session = session_client.session_path(DIALOGFLOW_PROJECT_ID, SESSION_ID)
    text_input = dialogflow_v2.types.TextInput(text=input_text_from_web, language_code=DIALOGFLOW_LANGUAGE_CODE)
    query_input = dialogflow_v2.types.QueryInput(text=text_input)
    query_parameter = dialogflow_v2.types.QueryParameters()
    try:
        response = session_client.detect_intent(session=session, query_input=query_input)
        orderid = (response.query_result.parameters.fields["ordernumber"])
        orderid_json = json.loads(MessageToJson(orderid))
    except InvalidArgument:
        raise
    return {
        "response": response.query_result.fulfillment_text,
        "ordernumber": orderid_json
    }


app.run(host='0.0.0.0', port=5002, debug=True)


Спасибо!

...