Skip to content

session timeout not working in lex chatbot

0

There is a lex chatbot created in AWS.Session timeout is not getting detected in lex chatbot despite configuring the session timeout to 1 minute.

Even lambda function created on the code hook intent invocation for lex chatbot is also not detecting session timeout on the chatbot.

The code for lambda function is as follows:

import boto3 import json from datetime import datetime, timedelta, timezone

Initialize DynamoDB resource and table

dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('LexSessionTable')

Session timeout in minutes

SESSION_TIMEOUT_MINUTES = 1

def lambda_handler(event, context): print("FULL EVENT:", json.dumps(event, indent=2)) # Debug log

# Safely extract sessionId
session_id = event.get('sessionId')
if not session_id:
    raise ValueError("Missing 'sessionId' in Lex event payload.")

now = datetime.now(timezone.utc)

# Fetch session from DynamoDB
try:
    response = table.get_item(Key={'sessionId': session_id})
    session_data = response.get('Item')
    print(f"Session data: {session_data}")
except Exception as e:
    print(f"Error accessing DynamoDB: {e}")
    session_data = None

if session_data:
    try:
        last_interaction = datetime.fromisoformat(session_data['lastInteractionTime'])
        print(f"Last interaction time: {last_interaction}")
        if now - last_interaction > timedelta(minutes=SESSION_TIMEOUT_MINUTES):
            # Session expired
            print("Session expired")
            table.delete_item(Key={'sessionId': session_id})
            return {
                "sessionState": {
                    "dialogAction": {"type": "Close"},
                    "intent": {"name": "FallbackIntent", "state": "Fulfilled"},
                    "sessionAttributes": {},
                },
                "messages": [{
                    "contentType": "PlainText",
                    "content": "Your session has expired. Let's start over."
                }]
            }
        else:
            # Update timestamp
            print("Updating session timestamp")
            table.update_item(
                Key={'sessionId': session_id},
                UpdateExpression="SET lastInteractionTime = :time",
                ExpressionAttributeValues={':time': now.isoformat()}
            )
    except Exception as e:
        print(f"Error processing session data: {e}")
else:
    # New session
    try:
        print("Creating new session")
        table.put_item(Item={
            'sessionId': session_id,
            'lastInteractionTime': now.isoformat()
        })
    except Exception as e:
        print(f"Error creating new session: {e}")

# Continue with Lex logic
return {
    "sessionState": event.get("sessionState", {}),
    "messages": [{
        "contentType": "PlainText",
        "content": "Session is active."
    }]
}

Cloudwatch Log:

{ "timestamp": "2025-06-09T13:17:18.789Z", "requestId": "635cbabc-7631-4e93-96e5-edd5bf0f7362", "messages": [ { "contentType": "PlainText", "content": "Hey, what is your name ?" } ], "messageVersion": "2.0", "dialogEventLogs": [ { "dialogStepLabel": "Intent/GreetIntent/StartIntent", "nextStep": { "dialogAction": { "type": "InvokeDialogCodeHook" } } }, { "dialogStepLabel": "Intent/GreetIntent/StartIntent/CodeHook/Success", "nextStep": { "dialogAction": { "type": "ElicitSlot", "slotToElicit": "UserName" } } } ], "transcriptions": [ { "transcription": "hi", "transcriptionConfidence": 1, "resolvedContext": { "intent": "GreetIntent" }, "resolvedSlots": {} } ], "sessionId": "189693864019378", "isTestWorkbenchTraffic": false, "inputMode": "Text", "operationName": "RecognizeText", "interpretations": [ { "intent": { "name": "GreetIntent", "state": "InProgress", "slots": { "UserName": null }, "confirmationState": "None" }, "interpretationSource": "Lex", "nluConfidence": "1.00" }, { "intent": { "name": "FallbackIntent", "slots": {} }, "interpretationSource": "Lex" }, { "intent": { "name": "GoodbyeIntent", "slots": {} }, "interpretationSource": "Lex", "nluConfidence": "0.49" }, { "intent": { "name": "ThankYouIntent", "slots": {} }, "interpretationSource": "Lex", "nluConfidence": "0.46" }, { "intent": { "name": "Help_Intent", "slots": {} }, "interpretationSource": "Lex", "nluConfidence": "0.32" } ], "developerOverride": false, "bot": { "name": "DC_GP", "version": "DRAFT", "id": "0QKBBZUGLZ", "aliasName": "TestBotAlias", "aliasId": "TSTALIASID", "localeId": "en_GB" }, "sessionState": { "sessionAttributes": {}, "dialogAction": { "type": "ElicitSlot", "slotToElicit": "UserName" }, "intent": { "name": "GreetIntent", "state": "InProgress", "slots": { "UserName": null }, "confirmationState": "None" }, "originatingRequestId": "1a0e2561-ff28-45b5-9bd8-fc260e41b641" }, "inputTranscript": "hi", "missedUtterance": false, "utteranceContext": {} }

{"timestamp":"2025-06-09T13:17:18.789Z","requestId":"635cbabc-7631-4e93-96e5-edd5bf0f7362","messages":[{"contentType":"PlainText","content":"Hey, what is your name ?"}],"messageVersion":"2.0","dialogEventLogs":[{"dialogStepLabel":"Intent/GreetIntent/StartIntent","nextStep":{"dialogAction":{"type":"InvokeDialogCodeHook"}}},{"dialogStepLabel":"Intent/GreetIntent/StartIntent/CodeHook/Success","nextStep":{"dialogAction":{"type":"ElicitSlot","slotToElicit":"UserName"}}}],"transcriptions":[{"transcription":"hi","transcriptionConfidence":1.0,"resolvedContext":{"intent":"GreetIntent"},"resolvedSlots":{}}],"sessionId":"189693864019378","isTestWorkbenchTraffic":false,"inputMode":"Text","operationName":"RecognizeText","interpretations":[{"intent":{"name":"GreetIntent","state":"InProgress","slots":{"UserName":null},"confirmationState":"None"},"interpretationSource":"Lex","nluConfidence":"1.00"},{"intent":{"name":"FallbackIntent","slots":{}},"interpretationSource":"Lex"},{"intent":{"name":"GoodbyeIntent","slots":{}},"interpretationSource":"Lex","nluConfidence":"0.49"},{"intent":{"name":"ThankYouIntent","slots":{}},"interpretationSource":"Lex","nluConfidence":"0.46"},{"intent":{"name":"Help_Intent","slots":{}},"interpretationSource":"Lex","nluConfidence":"0.32"}],"developerOverride":false,"bot":{"name":"DC_GP","version":"DRAFT","id":"0QKBBZUGLZ","aliasName":"TestBotAlias","aliasId":"TSTALIASID","localeId":"en_GB"},"sessionState":{"sessionAttributes":{},"dialogAction":{"type":"ElicitSlot","slotToElicit":"UserName"},"intent":{"name":"GreetIntent","state":"InProgress","slots":{"UserName":null},"confirmationState":"None"},"originatingRequestId":"1a0e2561-ff28-45b5-9bd8-fc260e41b641"},"inputTranscript":"hi","missedUtterance":false,"utteranceContext":{}} So basically session timeout is not working at lex chatbot level. The issue is persistent since last week and we as a team are unable to find a workaround despite having tried out all possible methods.

1 Answer
0

It appears that the session timeout is not working as expected in your Lex chatbot, despite configuring it to 1 minute. There are a few potential reasons for this and some steps you can take to troubleshoot:

  1. Lex Bot Configuration: Ensure that the session timeout is correctly set to 1 minute in the Lex bot configuration. This setting should be applied when you create or update the bot.

  2. Lambda Function Logic: Your Lambda function is using DynamoDB to track session timeouts, which is separate from Lex's built-in session management. Make sure your DynamoDB table is correctly set up and that the Lambda function has the necessary permissions to access it.

  3. Session ID Consistency: Verify that the session ID being passed to your Lambda function is consistent across multiple interactions within the same session. If the session ID changes unexpectedly, it could prevent proper timeout detection.

  4. Time Zone Handling: Ensure that the time comparisons in your Lambda function are correctly handling time zones. The code is using UTC, which is good, but double-check that this aligns with how Lex is handling timestamps.

  5. Error Handling: Your Lambda function has error handling, but errors might be preventing the timeout logic from executing properly. Check your CloudWatch logs for any error messages.

  6. Lex Session vs. Lambda Invocation: Remember that Lex's session timeout and your Lambda function's execution are separate. Lex may not be invoking your Lambda if it considers the session expired.

  7. Testing Method: How are you testing the timeout? Ensure you're waiting the full minute between interactions when testing.

  8. CloudWatch Logs: Analyze your CloudWatch logs thoroughly. Look for patterns in the session IDs, timestamps, and any error messages.

  9. Lex Console Testing: Try testing directly in the Lex console to isolate whether the issue is with Lex itself or your integration.

  10. AWS Support: If the issue persists after verifying all of the above, consider contacting AWS support, as there might be an underlying issue with the Lex service.

Remember, Lex's built-in session management should handle the timeout automatically. Your Lambda function's timeout logic is an additional layer that may not be necessary unless you need custom behavior beyond what Lex provides.
Sources
Setting the session timeout - Amazon Lex
[Invalid Lambda Response: Received invalid response from Lambda: Cannot construct instance of IntentResponse, problem: The validated object is null at Source: (String)" | AWS re:Post

answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.