AWS Lex 自由文本的 Slot 类型可以使用 AMAZON.AlphaNumeric 作为基本的 Slot 类型,然后将 ElasticSearch 和 AWS Lambda 结合使用,以便执行自定义的文本分析和验证。以下是基于 ElasticSearch 和 Lambda 的示例代码:
定义一个 ElasticSearch 的索引,来保存可用的字符串列表,例如下面的例子:
{
"string": [
"北京市",
"上海市",
"广州市",
"深圳市"
]
}
创建一个 Lambda 函数来执行自定义的文本验证。此示例中,Lambda 函数使用 ElasticSearch 索引中的字符串列表进行验证。如果输入的字符串是可用的,则返回匹配的字符串,否则返回一个错误。
import boto3
from elasticsearch import Elasticsearch
region_name = 'us-west-2'
url = 'https://search-domains.example.com' # REPLACE_WITH_ELASTICSEARCH_ENDPOINT
aws_access_key_id = 'ACCESS KEY ID'
aws_secret_access_key = 'SECRET ACCESS KEY'
index_name = 'index_name' # REPLACE_WITH_INDEX_NAME
def validate_input_text(text):
try:
es = Elasticsearch(
[url],
http_auth=(aws_access_key_id, aws_secret_access_key),
use_ssl=True,
verify_certs=True,
connection_class=RequestsHttpConnection
)
result = es.search(
index=index_name,
body={"query": {"match": {"string": text}}}
)
if not result['hits']['total']['value']:
response = {
'isValid': False,
'errorMessage': 'Text is invalid. Please provide a valid text.'
}
else:
response = {
'isValid': True,
'text': result['hits']['hits'][0]['_source']['string']
}
except Exception as e:
response = {
'isValid': False,
'errorMessage': str(e)
}
return response
def lambda_handler(event, context):
text = event['currentIntent']['slots']['text']
validation_result = validate_input_text(text)
if validation_result['isValid']:
response = {
'sessionAttributes': event['sessionAttributes'],
'dialogAction': {
'type': 'Close',
'fulfillmentState': 'Fulfilled',
'message': {
'contentType': 'PlainText',
'content': '您的文本“{}”已验证成功。'.format(validation_result['text'])
}
}
}
else:
response