Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

AWS Lex + Lambda

2025-03-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

AWS Lex

Create Bots-- > Try a sample {OrderFlowers}

La Lambda initialization and validation-- > add a defined Lambda function

Slots-- > segment value

SlotType-- > define values of Slots

Slots-> FlowerType Prompt-- > Prompt response cards-- > URL: Global S3 https://s3.cn-north-1.amazonaws.com.cn/sides-share/AWS+INNOVATE+2018/builders_workshop/Flower.jpeg Button title/value for each button.

After modification, "Save Intent" saves, click "Build" to test as below--

Publish to publish Slack/Facebook Channel.

AWS Lambda

Create Function-> Blueprints (filter "lex")-- > Choose "lex-order-flowers-python"-- > Role: LexRoleOrderFlowers

Function Code as below:

"" This sample demonstrates an implementation of the Lex Code Hook Interfacein order to serve a sample bot which manages orders for flowers.Bot, Intent, and Slot models which are compatible with this sample can be found in the Lex Consoleas part of the 'OrderFlowers' template.For instructions on how to set up and test this bot, as well as additional samples Visit the Lex Getting Started documentation http://docs.aws.amazon.com/lex/latest/dg/getting-started.html."""import mathimport dateutil.parserimport datetimeimport timeimport osimport loggingimport boto3import jsonlogger = logging.getLogger () logger.setLevel (logging.DEBUG) ""-- Helpers to build responses which match the structure of the necessary dialog actions-- "" def get_slots (intent_request): return intent_request ['currentIntent'] [' slots'] def elicit_slot (session_attributes, intent_name, slots, slot_to_elicit Message): return {'sessionAttributes': session_attributes,' dialogAction': {'type':' ElicitSlot', 'intentName': intent_name,' slots': slots, 'slotToElicit': slot_to_elicit,' message': message}} def close (session_attributes, fulfillment_state Message): response = {'sessionAttributes': session_attributes,' dialogAction': {'type':' Close', 'fulfillmentState': fulfillment_state,' message': message}} return responsedef delegate (session_attributes, slots): return {'sessionAttributes': session_attributes,' dialogAction': {'type':' Delegate' 'slots': slots} "--Helper Functions -"def parse_int (n): try: return int (n) except ValueError: return float (' nan') def build_validation_result (is_valid, violated_slot, message_content): if message_content is None: return {" isValid ": is_valid "violatedSlot": violated_slot,} return {'isValid': is_valid,' violatedSlot': violated_slot, 'message': {' contentType': 'PlainText',' content': message_content}} def isvalid_date (date): try: dateutil.parser.parse (date) return True except ValueError: return Falsedef validate_order_flowers (flower_type, date Pickup_time, number): flower_types = ['lilies',' roses', 'tulips'] if flower_type is not None and flower_type.lower () not in flower_types: return build_validation_result (False,' FlowerType','We do not have {}, would you like a different type of flower?' 'Our most popular flowers are roses'.format (flower_type)) if date is not None: if not isvalid_date (date): return build_validation_result (False,' PickupDate','I did not understand that, what date would you like to pick the flowers up?') Elif datetime.datetime.strptime (date,'% Ymuri% mmi% d'). Date () 16: # Outside of business hours return build_validation_result (False, 'PickupTime',' Our business hours are from ten a m. To four p m. Can you specify a time during this range?') If number is not None: num = parse_int (number) if num

< 0 or num >

5: return build_validation_result (False,'FlowerNumber', 'Please input a number between 1 / 5. We can offer 1 / 5 at once.') Return build_validation_result (True, None, None) ""-- Functions that control the bot's behavior-- "def order_flowers (intent_request):" Performs dialog management and fulfillment for ordering flowers. Beyond fulfillment, the implementation of this intent demonstrates the use of the elicitSlot dialog action in slot validation and re-prompting. " Flower_type = get_slots (intent_request) ["FlowerType"] date = get_slots (intent_request) ["PickupDate"] pickup_time = get_slots (intent_request) ["PickupTime"] number = get_slots (intent_request) ["FlowerNumber"] source = intent_request ['invocationSource'] if source =' DialogCodeHook': # Perform basic validation on the supplied input slots. # Use the elicitSlot dialog action to re-prompt for the first violation detected. Slots = get_slots (intent_request) validation_result = validate_order_flowers (flower_type, date, pickup_time, number) if not validation_result ['isValid']: slotts [validation _ result [' violatedSlot']] = None return elicit_slot (intent_request ['sessionAttributes'], intent_request [' currentIntent'] ['name']) Slots, validation_result ['violatedSlot'], validation_result [' message']) # Pass the price of the flowers back through session attributes to be used in various prompts defined # on the bot model. Output_session_attributes = intent_request ['sessionAttributes'] if intent_request [' sessionAttributes'] is not None else {} if number is not None: output_session_attributes ['Price'] = int (number) * 5 # Elegant pricing model return delegate (output_session_attributes, get_slots (intent_request)) sns = boto3.client (' sns') snsmessage = {'content':' Thanks Your order for {} of {} has been placed and will be ready for pickup by {} on {} '.format (number, flower_type, pickup_time, date)} # snsmessage = {"test": "message test"} sns.publish (TopicArn='YOUR_Topic_ARN', Message=json.dumps (snsmessage)) # Order the flowers, and rely on the goodbye message of the bot to define the message to the end user. # In a real bot, this would likely involve a call to a backend service. Return close (intent_request ['sessionAttributes'],' Fulfilled', {'contentType':' PlainText', 'OrderConfirm':' Thanks, your order for {} of {} has been placed and will be ready for pickup by {} on {} '.format (number, flower_type, pickup_time) Date)}) ""-- Intents-- "def dispatch (intent_request):" Called when the user specifies an intent for this bot. " Logger.debug ('dispatch userId= {}, intentName= {}' .format (intent_request ['userId']) Intent_request ['currentIntent'] [' name']) intent_name = intent_request ['currentIntent'] [' name'] # Dispatch to your bot's intent handlers if intent_name = = 'OrderFlowers': return order_flowers (intent_request) raise Exception (' Intent with name' + intent_name + 'not supported') "- Main handler--"def lambda_handler (event, context):"Route the incoming request based on intent. The JSON body of the request is provided in the event slot. # By default, treat the user request as coming from the America/New_York time zone. Os.environ ['TZ'] =' America/New_York' time.tzset () logger.debug ('event.bot.name= {}' .format (event ['bot'] [' name'])) return dispatch (event)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report