dialogflow-esdialogflow-es-fulfillment

Dialogflow: How to store multiple parameters in a list parameter from different user sentences?


Basically I want to achieve this:

1.user: I want apple.
bot: You want apple right? 
2.user: I also want banana.
bot: You want apple and banana right? 

Here apple and banana are all parameters of the same fruit entity. In my webook backend I want to receive [apple, banana] when the user entered 2nd sentence, so the bot needs to remember all the fruit (parameters) users gave during the conversation.

I was playing around with dialogflow context. I know it could pass parameters between different intents. But at here I'm using the same intent buyFruit, so the output context only has the new fruit parameters user entered in a new sentence:

1.user: I want apple. -> outputContext.parameters = [apple]
2.user: I also want banana. -> outputContext.parameters = [banana]

I couldn't find a way to get the fruit parameters user said in previous sentences. In another word, I want outputContext.parameters = [apple, banana] in the second webhook request. Does anyone know how to achieve this?


Solution

  • I found the solution to this. I will assume you understand how to use fulfillment, and adding webhooks. If not, feel free to visit here or shoot a question.

    For this, there are 3 necessary parts. Dialogflow, your fulfillment code ( I used flask and python), and communication between the two. Enable Webhook, fill in the appropriate local machine url (for this I used NGROK).

    I created a cart and a function for creating and maintaining said cart. Below is the code:

    from flask import Flask, request
    
    app = Flask(__name__)
    
    
    
    ##Create the cart
    cart = []
    
    
    #create a route for the webhook
    @app.route('/webhook', methods=['GET', 'POST'])
    def webhook():
        req = request.get_json(silent=True, force=True)
        fulfillmentText = ''
        query_result = req.get('queryResult')
    
        if query_result.get('action') == 'order.wings':
            food_data = query_result['parameters']
    
            ##create temp dictionary so we always extract correct order data
            temp_dictionary = []
            for item in food_data:
                temp_dictionary.append(item)
    
            ##add items to cart
            new_item = []
            for item in temp_dictionary:
                new_item.append(food_data[item])
    
            cart.append(new_item)
            print(cart)
    
    
            fulfillmentText = "Added Wings to Cart"
        return {
                "fulfillmentText": fulfillmentText,
                "source": "webhookdata"
        }
    
    
    #run the app
    if __name__ == '__main__':
        app.run()