Spaces:
Runtime error
Runtime error
Greg Thompson commited on
Commit ·
271c78c
1
Parent(s): 32f36d9
Update conversation_manager.py for code style and comments
Browse filesFiles changed (2)
51 unmodified lines52535455565758596061626364656667686970717251 unmodified lines@app.post("/manager")async def programmatic_message_manager(request: Request):print(request)data_dict = await request.json()# print("FULL REQUEST")# print(data_dict)# message_data = data_dict.get('message_data', '')# context_data = data_dict.get('context', '')# print("MESSAGE_DATA")# print(message_data)# print("CONTEXT_DATA")# print(context_data)context = generate_message(data_dict)return JSONResponse(context)@app.post("/nlu")51 unmodified lines525354555657585951 unmodified lines@app.post("/manager")async def programmatic_message_manager(request: Request):data_dict = await request.json()context = manage_conversational_response(data_dict)return JSONResponse(context)@app.post("/nlu")
9 unmodified lines101112131415162 unmodified lines192021222324252627282930313233343536373839404114 unmodified lines565758596061626364656667686970717273747576777879808182838485868788899091929333 unmodified lines1271281291301311321331341351361371381391401411421431441451461471481491501511521539 unmodified linesdef create_text_message(message_text, whatsapp_id):data = {"preview_url": False,"recipient_type": "individual","to": whatsapp_id,2 unmodified lines"body": message_text}}return datadef create_button_objects(button_options):button_arr = []for option in button_options:button_choice = {"type": "reply","reply": {"id": "inquiry-yes","title": "add"}}button_arr.append(button_choice)return button_arrdef create_interactive_message(message_text, button_options, whatsapp_id):button_arr = create_button_objects(button_options)data = {14 unmodified linesreturn datadef generate_message(data_json):""" pendingREQUIREMENTS- implement logging of message- have a very simple activity which allows for different dialogue* add - Add the numbers, 1+1, 2+2* subtract - Subtract the numbers, 1-1, 2-2* menu - Choose one- send message data to retrieve dialogue state- retrieve response and build message object- send message objectNeed to make util functions that apply to both /nlu and /conversation_manager"""message_data = data_json.get('message_data', '')context_data = data_json.get('context', '')whatsapp_id = message_data['message']['_vnd']['v1']['chat']['owner'].replace("+","")user_message = message_data['message']['text']['body']print("===============")print("message_data")print(message_data)print("context_data")print(context_data)print("===============")if context_data['user_message'] == '' and context_data['state'] == 'start-conversation':message_package = {'messages': [],'input_prompt': "Welcome to our math practice. What would you like to try? Type add or subtract.",'state': "welcome-sequence"33 unmodified lines'input_prompt': "Please type add or subtract to start a math activity.",'state': "reprompt-menu-options"}headers = {'Authorization': f"Bearer {os.environ.get('TURN_AUTHENTICATION_TOKEN')}",'Content-Type': 'application/json'}for message in message_package['messages']:data = create_text_message(message, whatsapp_id)r = requests.post(f'https://whatsapp.turn.io/v1/messages', data=json.dumps(data), headers=headers)# print("==================")# print("Headers")# print(headers)# print("Data")# print(data)# print("Request Info")# print(r)# print("==================")context = {"context":{"user": whatsapp_id, "state": message_package['state'], "bot_message": message_package['input_prompt'], "user_message": user_message, "type": 'ask'}}return context9 unmodified lines101112131415161718192021222324252 unmodified lines2829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727314 unmodified lines88899091929394959697989910010110210310410510633 unmodified lines1401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921939 unmodified linesdef create_text_message(message_text, whatsapp_id):""" Fills a template with the necessary information to send a text message to WhatsappInputs- message_text: str - the content that the message should display- whatsapp_id: str - the message recipient's phone numberOutputs- message_data: dict - a preformatted template with the inputs' values included"""message_data = {"preview_url": False,"recipient_type": "individual","to": whatsapp_id,2 unmodified lines"body": message_text}}return message_datadef create_button_objects(button_options):""" Creates a list of button objects using the input valuesInput- button_options: list - a list of text to be displayed in buttonsOutput- button_arr: list - a list of button objects that use a template filled with the input valuesNOTE: Not fully implemented and tested"""button_arr = []for option in button_options:button_choice = {"type": "reply","reply": {"id": "inquiry-yes","title": option['text']}}button_arr.append(button_choice)return button_arrdef create_interactive_message(message_text, button_options, whatsapp_id):""" Fills a template with the necessary information to send a message with button options to Whatsapp* NOTE: Not fully implemented and tested* NOTE/TODO: It is possible to create other kinds of messages with the 'interactive message' template* Documentation: https://whatsapp.turn.io/docs/api/messages#interactive-messagesInputs- message_text: str - the content that the message should display- button_options: list - what each button option should display- whatsapp_id: str - the message recipient's phone number"""button_arr = create_button_objects(button_options)data = {14 unmodified linesreturn datadef return_next_conversational_state(context_data, user_message):""" Evaluates the current state of the conversation to determine resources for the next state of the conversationInput- context_data: dict - data about the conversation's current state received from the Turn.io stack- user_message: str - the message the user sent in response to the stateOutput- message_package: dict - a series of messages and user input to send the user"""if context_data['user_message'] == '' and context_data['state'] == 'start-conversation':message_package = {'messages': [],'input_prompt': "Welcome to our math practice. What would you like to try? Type add or subtract.",'state': "welcome-sequence"33 unmodified lines'input_prompt': "Please type add or subtract to start a math activity.",'state': "reprompt-menu-options"}return message_packagedef manage_conversational_response(data_json):""" Parses message data, determines how to respond to user message at a given conversational state, builds/sends messages, and updates/sends contextInput- data_json: dict - the data for a message the user sent to Turn.io/WhatsappOutput- context: dict - a record of the state at a given point a conversationTODOs- implement logging of message- test interactive messages- review context object and re-work to use a standardized format- review ways for more robust error handling- need to make util functions that apply to both /nlu and /conversation_manager"""message_data = data_json.get('message_data', '')context_data = data_json.get('context', '')whatsapp_id = message_data['message']['_vnd']['v1']['chat']['owner'].replace("+","")user_message = message_data['message']['text']['body']message_package = return_next_conversational_state(context_data, user_message)headers = {'Authorization': f"Bearer {os.environ.get('TURN_AUTHENTICATION_TOKEN')}",'Content-Type': 'application/json'}# Send all messages for the current state before a user input prompt (text/button input request)for message in message_package['messages']:data = create_text_message(message, whatsapp_id)r = requests.post(f'https://whatsapp.turn.io/v1/messages', data=json.dumps(data), headers=headers)# Update the context object with the new state of the conversationcontext = {"context":{"user": whatsapp_id,"state": message_package['state'],"bot_message": message_package['input_prompt'],"user_message": user_message,"type": 'ask'}}return context
app.py+1-14
mathtext_fastapi/conversation_manager.py+82-42