Я пытаюсь создать чат-бота с rasa nlu, который поможет с поиском отелей.Я создал небольшую базу данных sqlite, содержащую названия и другие описания нескольких ресторанов.Это структура моей базы данных.
Name Cuisine Price ambience location rating
Flower Drum chinese high 2 south 5
Little Italy italian high 2 south 2
Quattro mexican low 2 center 3
Domino's Pizza fast food mid 0 east 3
. Я обучил переводчика некоторым пользовательским намерениям, подобным этому.
## intent:hotel_search
- I'm looking for a [Mexican](cuisine) restaurant in the [North](location) of town
- Which is the [best](rating) restaurant in the city
- Which restaurant has the most [rating](rating) in the city
- I am looking for a [burger](dish) joint in the [south](location) of the city
- I am trying to find an [expensive](price) [Indian](cuisine) restaurant in the [east](location) of the city
Это код для обучения переводчика
def train(data, config_file, model_dir):
training_data = load_data(data)
trainer = Trainer(config.load(config_file))
trainer.train(training_data)
model_directory = trainer.persist(model_dir, fixed_model_name = 'chat')
Это код для поиска отелей из базы данных sqlite
def find_hotels(params):
# Create the base query
query = 'SELECT * FROM hotels'
# Add filter clauses for each of the parameters
if len(params) > 0:
filters = ["{}=?".format(k) for k in params]
query += " WHERE " + " and ".join(filters)
# Create the tuple of values
t = tuple(params.values())
# Open connection to DB
conn = sqlite3.connect('hotels.sqlite')
# Create a cursor
c = conn.cursor()
# Execute the query
c.execute(query, t)
# Return the results
return c.fetchall()
Это код для ответа на входящее сообщение
# Define respond()
def respond(message):
# responses
responses = ["I'm sorry :( I couldn't find anything like that",
'{} is a great hotel!',
'{} or {} would work!',
'{} is one option, but I know others too :)']
# Extract the entities
entities = interpreter.parse(message)["entities"]
# Initialize an empty params dictionary
params = {}
# Fill the dictionary with entities
for ent in entities:
params[ent["entity"]] = str(ent["value"])
print("\n\nparams: {}\n\n".format(params))
# Find hotels that match the dictionary
results = find_hotels(params)
print("\n\nresults: {}\n\n".format(results))
# Get the names of the hotels and index of the response
names = [r[0] for r in results]
n = min(len(results),3)
# Select the nth element of the responses array
return responses[n].format(*names)
Но когда я проверяю переводчика с этимпример
Я ищу дорогой китайский ресторан на юге города
Это результат, который я получаю
params: {'price': 'expensive', 'cuisine': 'chinese', 'location': 'south'}
results: []
I'm sorry :( I couldn't find anything like that
Если ябыли, чтобы удалить дорогое слово из входного вопроса, я получаю правильный результат, такой как этот
Я ищу китайский ресторан на юге города
params: {'cuisine': 'chinese', 'location': 'south'}
results: [('Flower Drum', 'chinese', 'high', 2, 'south', 5)]
Flower Drum is a great hotel!
Бот способен распознать все сущности, но не может выбрать правильные данные из базы данных, поскольку в базе данных цены нет ввода данных с именем дорогой в ценовом столбце.Как научить бота распознавать слово дорогое как высоко