Search code examples
pythonprotocol-buffersdialogflow-es

How to access infos in protobuf response from dialogflow API


I am having serious trouble accessing the values from a protobuf object I receive after accessing the google dialogflow api

(... create google cloud session object ...)

text_input = dialogflow.types.TextInput(text=text, language_code=language_code)
query_input = dialogflow.types.QueryInput(text=text_input)
response = session_client.detect_intent(request={"session": session, "query_input": query_input})

from google.protobuf import json_format
response_json = json_format.MessageToDict(response)

The error is:

AttributeError: 'MapComposite' object has no attribute 'DESCRIPTOR'

Basically I have two issues:

a) I am not able to convert the protobuf to json (here I am easily able to see how to access the infos I am looking for)

b) I am not able to understand the protobof data structure. Is there a dictionary?

Any helper in a) or b) are appreciated.

btw: I am looking for a way to access response.parameters in the API response.


Edit for Scott:

response.parameters is an object: <proto.marshal.collections.maps.MapComposite object at 0x7fe7323f7da0>

The parameters object is described here: https://cloud.google.com/dialogflow/es/docs/reference/rest/v2/DetectIntentResponse#QueryResult

Does it make sense to you? Because I don't understand how to access the values in this object.


Solution

  • You may use MessageToDict approach, as shown below, to serialize protobuf to a dictionary and use response._pb instead of response.

    from google.protobuf.json_format import MessageToDict
    response_json = MessageToDict(response._pb)
    

    Now, you can now navigate through the dictionary for the parameters that you want to access as shown below since parameters is inside/under queryResult (based on the structure).

    print(response_json["queryResult"]["parameters"])