Creating a local “Lex” Environment

This came up in a conversation I was having so I decided to take a stab at coding something to help. Let’s say you are building an Amazon Web Services chat bot using Lex and you want to test your Lambda logic locally before you deploy to your AWS account. Currently, as far as I know, there is no way to do this.

So, I create a simple framework for “simulating” the Lex bot locally. I use quotes around simulating because this does not, in any form or fashion, compare to Lex’s abilities to handle user input. But, if you are providing it with basic inputs that you know would work it could be a good starting point for your local assembly testing.

Let’s get into the code.

if __name__ == "__main__":
    session_state = {"currentIntent": None, "slots": {}}
    while True:
        user_input = input("You: ")
        input_response = process_input(user_input, session_state)
        print(f"Bot: {session_state['bot_response']}")
        response = generate_response(session_state)
        print("Bot: ", response)
        print(f"Bot: What else can i help you with?")

The main code here is a while loop that prompts the user to provide input. Using that input we process the users input against a set of predefined intents.

def process_input(user_input, session_state):
    # Logic to match user_input to an intent and fill slots
    # Update session_state with the current intent and slots
    for intent, intent_config in intents.items():
        if user_input in intent_config['utterances']:
            print(f"Found {intent} as input")
            session_state["currentIntent"] = intent
            session_state["bot_response"] = intent_config['response']
            return session_state

This function takes a look at a separate variable that we have defined for intents. You would need to expand this out for your use case but the structure is pretty straightforward.

intents = {
    "time": {
        "utterances": ['what time is it'],
        "slots": [],
        "response": "Checking to see what time it is"

Once the utterance matches an intent we update the session state and return it back to the while loop and then use that to generate a response. This is where your logic would begin to get complex as you call your fulfillment lambda to handle returning a valid response to the user.

You can take a look at the full code and contribute to it on over on my Githbub. If this code helps you or someone on your team feel free to share it across your social media!






Leave a Reply