Greg Thompson commited on
Commit
46b6696
1 Parent(s): 1399a2f

Add error handling for additional payload types

Browse files
Files changed (3) hide show
  1. app.py +9 -8
  2. mathtext_fastapi/nlu.py +3 -4
  3. scripts/make_request.py +10 -0
app.py CHANGED
@@ -4,7 +4,9 @@ or
4
  `python -m uvicorn app:app --reload --host localhost --port 7860`
5
  """
6
  import ast
 
7
  import mathactive.microlessons.num_one as num_one_quiz
 
8
  import sentry_sdk
9
 
10
  from fastapi import FastAPI, Request
@@ -13,17 +15,15 @@ from fastapi.staticfiles import StaticFiles
13
  from fastapi.templating import Jinja2Templates
14
  # from mathtext.sentiment import sentiment
15
  from mathtext.text2int import text2int
16
- from pydantic import BaseModel
17
-
18
  from mathtext_fastapi.logging import prepare_message_data_for_logging
19
  from mathtext_fastapi.conversation_manager import manage_conversation_response
20
  from mathtext_fastapi.v2_conversation_manager import manage_conversation_response
21
  from mathtext_fastapi.nlu import evaluate_message_with_nlu
22
  from mathtext_fastapi.nlu import run_intent_classification
 
23
 
24
- import os
25
- from dotenv import load_dotenv
26
 
 
27
  load_dotenv()
28
 
29
  sentry_sdk.init(
@@ -161,8 +161,11 @@ async def evaluate_user_message_with_nlu_api(request: Request):
161
  {'type':'integer', 'data': '8', 'confidence': 0}
162
  {'type':'sentiment', 'data': 'negative', 'confidence': 0.99}
163
  """
164
- data_dict = await request.json()
165
- message_data = data_dict.get('message_data', '')
 
 
 
166
  nlu_response = evaluate_message_with_nlu(message_data)
167
  return JSONResponse(content=nlu_response)
168
 
@@ -183,12 +186,10 @@ async def num_one(request: Request):
183
  'state': 'question'
184
  }
185
  """
186
- print("STEP 1")
187
  data_dict = await request.json()
188
  message_data = ast.literal_eval(data_dict.get('message_data', '').get('message_body', ''))
189
  user_id = message_data['user_id']
190
  message_text = message_data['message_text']
191
- print("STEP 2")
192
  return num_one_quiz.process_user_message(user_id, message_text)
193
 
194
 
 
4
  `python -m uvicorn app:app --reload --host localhost --port 7860`
5
  """
6
  import ast
7
+ from json import JSONDecodeError
8
  import mathactive.microlessons.num_one as num_one_quiz
9
+ import os
10
  import sentry_sdk
11
 
12
  from fastapi import FastAPI, Request
 
15
  from fastapi.templating import Jinja2Templates
16
  # from mathtext.sentiment import sentiment
17
  from mathtext.text2int import text2int
 
 
18
  from mathtext_fastapi.logging import prepare_message_data_for_logging
19
  from mathtext_fastapi.conversation_manager import manage_conversation_response
20
  from mathtext_fastapi.v2_conversation_manager import manage_conversation_response
21
  from mathtext_fastapi.nlu import evaluate_message_with_nlu
22
  from mathtext_fastapi.nlu import run_intent_classification
23
+ from pydantic import BaseModel
24
 
 
 
25
 
26
+ from dotenv import load_dotenv
27
  load_dotenv()
28
 
29
  sentry_sdk.init(
 
161
  {'type':'integer', 'data': '8', 'confidence': 0}
162
  {'type':'sentiment', 'data': 'negative', 'confidence': 0.99}
163
  """
164
+ try:
165
+ data_dict = await request.json()
166
+ except JSONDecodeError:
167
+ data_dict = {}
168
+ message_data = data_dict.get('message_data', {})
169
  nlu_response = evaluate_message_with_nlu(message_data)
170
  return JSONResponse(content=nlu_response)
171
 
 
186
  'state': 'question'
187
  }
188
  """
 
189
  data_dict = await request.json()
190
  message_data = ast.literal_eval(data_dict.get('message_data', '').get('message_body', ''))
191
  user_id = message_data['user_id']
192
  message_text = message_data['message_text']
 
193
  return num_one_quiz.process_user_message(user_id, message_text)
194
 
195
 
mathtext_fastapi/nlu.py CHANGED
@@ -4,10 +4,10 @@ import datetime as dt
4
  from dateutil.parser import isoparse
5
 
6
  from fuzzywuzzy import fuzz
 
7
  from mathtext_fastapi.logging import prepare_message_data_for_logging
8
  from mathtext.sentiment import sentiment
9
  from mathtext.text2int import text2int, TOKENS2INT_ERROR_INT
10
- from mathtext_fastapi.intent_classification import predict_message_intent
11
 
12
  log = getLogger(__name__)
13
 
@@ -163,16 +163,15 @@ def payload_is_valid(payload_object):
163
  """
164
  try:
165
  isinstance(
166
- isoparse(payload_object.get('message_inserted_at')),
167
  dt.datetime
168
  )
169
  isinstance(
170
- isoparse(payload_object.get('message_updated_at')),
171
  dt.datetime
172
  )
173
  except ValueError:
174
  return False
175
-
176
  return (
177
  isinstance(payload_object, Mapping) and
178
  isinstance(payload_object.get('author_id'), str) and
 
4
  from dateutil.parser import isoparse
5
 
6
  from fuzzywuzzy import fuzz
7
+ from mathtext_fastapi.intent_classification import predict_message_intent
8
  from mathtext_fastapi.logging import prepare_message_data_for_logging
9
  from mathtext.sentiment import sentiment
10
  from mathtext.text2int import text2int, TOKENS2INT_ERROR_INT
 
11
 
12
  log = getLogger(__name__)
13
 
 
163
  """
164
  try:
165
  isinstance(
166
+ isoparse(payload_object.get('message_inserted_at','')),
167
  dt.datetime
168
  )
169
  isinstance(
170
+ isoparse(payload_object.get('message_updated_at','')),
171
  dt.datetime
172
  )
173
  except ValueError:
174
  return False
 
175
  return (
176
  isinstance(payload_object, Mapping) and
177
  isinstance(payload_object.get('author_id'), str) and
scripts/make_request.py CHANGED
@@ -71,9 +71,19 @@ def run_full_nlu_endpoint_payload_test(sample_payload):
71
  print(request)
72
 
73
 
 
 
 
 
74
  run_full_nlu_endpoint_payload_test(b'{"message_data": {"author_id": "57787919091", "author_type": "OWNER", "contact_uuid": "df78gsdf78df", "message_body": "8", "message_direction": "inbound", "message_id": "dfgha789789ag9ga", "message_inserted_at": "2023-01-10T02:37:28.487319Z", "message_updated_at": "2023-01-10T02:37:28.487319Z"}}')
 
 
75
  run_full_nlu_endpoint_payload_test(b'{"message_data": {"author_id": "@event.message._vnd.v1.chat.owner", "author_type": "@event.message._vnd.v1.author.type", "contact_uuid": "@event.message._vnd.v1.chat.contact_uuid", "message_body": "@event.message.text.body", "message_direction": "@event.message._vnd.v1.direction", "message_id": "@event.message.id", "message_inserted_at": "@event.message._vnd.v1.chat.inserted_at", "message_updated_at": "@event.message._vnd.v1.chat.updated_at"}}')
76
 
 
 
 
 
77
  # run_simulated_request('intent-classification', 'exit')
78
  # run_simulated_request('intent-classification', "I'm not sure")
79
  # run_simulated_request('intent-classification', "easier")
 
71
  print(request)
72
 
73
 
74
+ # Case: Wrong key
75
+ run_full_nlu_endpoint_payload_test(b'{"message": {"author_id": "@event.message._vnd.v1.chat.owner", "author_type": "@event.message._vnd.v1.author.type", "contact_uuid": "@event.message._vnd.v1.chat.contact_uuid", "message_body": "@event.message.text.body", "message_direction": "@event.message._vnd.v1.direction", "message_id": "@event.message.id", "message_inserted_at": "@event.message._vnd.v1.chat.inserted_at", "message_updated_at": "@event.message._vnd.v1.chat.updated_at"}}')
76
+
77
+ # Case: Correct payload
78
  run_full_nlu_endpoint_payload_test(b'{"message_data": {"author_id": "57787919091", "author_type": "OWNER", "contact_uuid": "df78gsdf78df", "message_body": "8", "message_direction": "inbound", "message_id": "dfgha789789ag9ga", "message_inserted_at": "2023-01-10T02:37:28.487319Z", "message_updated_at": "2023-01-10T02:37:28.487319Z"}}')
79
+
80
+ # Case: Incorrect payload values
81
  run_full_nlu_endpoint_payload_test(b'{"message_data": {"author_id": "@event.message._vnd.v1.chat.owner", "author_type": "@event.message._vnd.v1.author.type", "contact_uuid": "@event.message._vnd.v1.chat.contact_uuid", "message_body": "@event.message.text.body", "message_direction": "@event.message._vnd.v1.direction", "message_id": "@event.message.id", "message_inserted_at": "@event.message._vnd.v1.chat.inserted_at", "message_updated_at": "@event.message._vnd.v1.chat.updated_at"}}')
82
 
83
+ # Case: Wrong payload object
84
+ run_full_nlu_endpoint_payload_test(b'{"message_data": {"_vnd": {"v1": {"author": {"id": 54327547257, "name": "Jin", "type": "OWNER"}, "card_uuid": None, "chat": {"assigned_to": None, "contact_uuid": "f7889-f78dfgb798-f786ah89g7-f78f9a", "inserted_at": "2023-03-28T13:21:47.581221Z", "owner": "+43789789146", "permalink": "", "state": "OPEN", "state_reason": "Re-opened by inbound message.", "unread_count": 97, "updated_at": "2023-04-07T21:05:27.389948Z", "uuid": "dfg9a78-d76a786dghas-78d9fga789g-a78d69a9"}, "direction": "inbound", "faq_uuid": None, "in_reply_to": None, "inserted_at": "2023-04-07T21:05:27.368580Z", "labels": [], "last_status": None, "last_status_timestamp": None, "on_fallback_channel": False, "rendered_content": None, "uuid": "hf78s7s89b-789fb68d9fg-789fb789dfb-f79sfb789"}}, "from": 5475248689, "id": "SBDE4zgAAy7887sfdT35SHFS", "text": {"body": 1000}, "timestamp": 1680901527, "type": "text"}, "type": "message"}')
85
+
86
+
87
  # run_simulated_request('intent-classification', 'exit')
88
  # run_simulated_request('intent-classification', "I'm not sure")
89
  # run_simulated_request('intent-classification', "easier")