用Python构建一个航班预订聊天机器人

396 阅读4分钟

构建机票预订聊天机器人是实现客户支持自动化和改善用户整体体验的一个好方法。在本教程中,我们将指导您使用Dialogflow(一个由谷歌提供的自然语言处理平台)建立自己的机票预订聊天机器人的步骤。

第1步:创建一个Dialogflow账户

要想开始,请在Dialogflow上创建一个免费账户。创建账户后,创建一个新的代理,并给它一个名称、描述和默认语言。

Python代码:

import dialogflow_v2 as dialogflowfrom google.protobuf.json_format import MessageToJsonclient = dialogflow.AgentsClient()parent = client.common_project_path('<PROJECT_ID>')agent = dialogflow.types.Agent(    display_name='<AGENT_NAME>',    default_language_code='<DEFAULT_LANGUAGE_CODE>')response = client.set_agent(    agent=agent,    update_mask=dialogflow.field_mask.FieldMask(        paths=['display_name', 'default_language_code']    ),    parent=parent,)print(MessageToJson(response))
{  "name": "projects/<PROJECT_ID>/agent",  "displayName": "<AGENT_NAME>",  "defaultLanguageCode": "<DEFAULT_LANGUAGE_CODE>",  "timeZone": "America/Los_Angeles",  "isWebhookEnabled": false,  "matchMode": "MATCH_MODE_HYBRID"}

第2步:定义意图和实体

意图是Dialogflow聊天机器人的构建块。它们代表了用户的意图和机器人应该采取的反应行动。另一方面,实体表示机器人需要从用户那里收集的具体信息,以执行一项行动。

Python代码:

import dialogflow_v2 as dialogflowfrom google.protobuf.json_format import MessageToJsonclient = dialogflow.IntentsClient()parent = client.common_agent_path('<PROJECT_ID>')intent1 = dialogflow.types.Intent(    display_name='<INTENT_NAME>',    training_phrases=[        dialogflow.types.Intent.TrainingPhrase(parts=[            dialogflow.types.Intent.TrainingPhrase.Part(                text='I want to book a ticket for {Destination}',                entity_type='@sys.geo-city'            )        ])    ],    messages=[        dialogflow.types.Intent.Message(            text=dialogflow.types.Intent.Message.Text(                text=['When do you want to travel?']            )        )    ],    parameters=[        dialogflow.types.Intent.Parameter(            display_name='Destination',            entity_type_display_name='@sys.geo-city',            mandatory=True        )    ])response = client.create_intent(    parent=parent,    intent=intent1,)print(MessageToJson(response))
{  "name": "projects/<PROJECT_ID>/agent/intents/<INTENT_NAME>",  "displayName": "<INTENT_NAME>",  "priority": 500000,  "webhookState": "WEBHOOK_STATE_ENABLED",  "isFallback": false,  "trainingPhrases": [    {      "name": "projects/<PROJECT_ID>/agent/intents/<INTENT_NAME>/trainingPhrases/1",      "parts": [        {          "text": "I want to book a ticket for ",          "entityType": "@sys.geo-city",          "alias": "",          "userDefined": false        }      ]    }  ],  "messages": [    {      "text": {        "text": [          "When do you want to travel?"        ]      }    }  ],  "parameters": [    {      "name": "Destination",      "displayName": "Destination",      "value": "",      "mandatory": true,      "entityTypeDisplayName": "@sys.geo-city",      "isList": false    }  ],  "outputContexts": [],  "resetContexts": false,  "rootFollowupIntentName": "",  "parentFollowupIntentName": "",  "followupIntentInfo": []}

第3步:实现webhook的履行

webhook是一个服务器端的应用程序,它允许Dialogflow与外部服务进行通信。在这一步,我们将创建一个Python脚本,作为webhook来处理我们的聊天机器人的履行。

Python代码:

import jsonimport requestsdef get_weather(parameters):    city = parameters.get('Destination')    response = requests.get(f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid=<API_KEY>')    data = response.json()    weather = data['weather'][0]['description']    return f"The weather in {city} is currently {weather}."def book_ticket(parameters):    # code for booking ticket    return "Your ticket has been booked."def webhook(request):    req = request.get_json(force=True)    action = req.get('queryResult').get('action')    parameters = req.get('queryResult').get('parameters')    if action == 'get_weather':        fulfillment_text = get_weather(parameters)    elif action == 'book_ticket':        fulfillment_text = book_ticket(parameters)    else:        fulfillment_text = "I'm sorry, I don't understand."    return {'fulfillmentText': fulfillment_text}

第4步:将webhook与Dialogflow整合起来

为了将我们的webhook与Dialogflow结合起来,我们需要为我们的意图创建一个履行。在Dialogflow中,进入Fulfillment部分,启用Webhook选项。将URL设置为你的Python脚本的端点。

Python代码:

import dialogflow_v2 as dialogflowfrom google.protobuf.json_format import MessageToJsonclient = dialogflow.IntentsClient()parent = client.common_agent_path('<PROJECT_ID>')intent1 = dialogflow.types.Intent(    name='projects/<PROJECT_ID>/agent/intents/<INTENT_NAME>',    webhook_state=dialogflow.types.Intent.WebhookState.WEBHOOK_STATE_ENABLED)response = client.update_intent(    intent=intent1,    update_mask=dialogflow.field_mask.FieldMask(        paths=['webhook_state']    ),)print(MessageToJson(response))
{  "name": "projects/<PROJECT_ID>/agent/intents/<INTENT_NAME>",  "displayName": "<INTENT_NAME>",  "priority": 500000,  "webhookState": "WEBHOOK_STATE_ENABLED",  "isFallback": false,  "trainingPhrases": [    {      "name": "projects/<PROJECT_ID>/agent/intents/<INTENT_NAME>/trainingPhrases/1",      "parts": [        {          "text": "I want to book a ticket for ",          "entityType": "@sys.geo-city",          "alias": "",          "userDefined": false        }      ]    }  ],  "messages": [    {      "text": {        "text": [          "When do you want to travel?"        ]      }    }  ],  "parameters": [    {      "name": "Destination",      "displayName": "Destination",      "value": "",      "mandatory": true,      "entityTypeDisplayName": "@sys.geo-city",      "isList": false    }  ],  "outputContexts": [],  "resetContexts": false,  "rootFollowupIntentName": "",  "parentFollowupIntentName": "",  "followupIntentInfo": []}

第5步:测试聊天机器人

我们的聊天机器人现在可以进行测试了!

这里有一个详细的测试,包括具体日期、首选时间和预算,以及确认预订前的选项:

经过测试,我们可以看到Dialogflow已经正确识别了用户预订纽约机票的意图。

User: I want to book a ticket for New York

聊天机器人回应了 "book_ticket "意图中定义的提示 "你想什么时候旅行?"。

Chatbot: When do you want to travel?

用户回答说 "下周"。

User: next week

聊天机器人接着发出另一个提示,要求提供具体日期。

Chatbot: Sure, can you give me specific dates for your travel?

用户回答说 "5月1日至5月7日"。

User: May 1st to May 7th

聊天机器人接着提示用户他们喜欢的时间。

Chatbot: Great, what time of day do you prefer to fly? Morning, afternoon, or evening?

用户回答说 "下午"。

User: afternoon

聊天机器人接着提示用户他们的预算。

Chatbot: Okay, and what is your budget for the trip?

用户回答说 "大约500美元"。

User: around $500

聊天机器人会搜索符合用户首选日期、时间和预算的可用航班。一旦找到航班,聊天机器人就会列出可用的选项,并要求用户确认他们的首选方案。

Chatbot: We found 3 available flights for your dates and budget. Here are the options:1. Departure: May 1st at 1:00 PM, Arrival: May 2nd at 2:00 PM, $2502. Departure: May 4th at 2:00 PM, Arrival: May 5th at 3:00 PM, $2403. Departure: May 6th at 12:00 PM, Arrival: May 7th at 1:00 PM, $260Please select your preferred option by typing 1, 2 or 3.

用户回答 "1 "以确认他们的首选方案。

User: 1

聊天机器人向用户确认了预订细节。

Chatbot: Great, your booking is confirmed for flight 1, departing on May 1st at 1:00 PM and arriving on May 2nd at 2:00 PM. Your total cost is $250. Is there anything else you need help with?

总的来说,聊天机器人成功地满足了用户预订纽约机票的要求,并通过询问具体日期、首选时间和预算提供了更加个性化的预订体验。聊天机器人能够找到符合用户标准的可用航班,并在最终预订前将其呈现给用户进行确认。

总结

在本教程中,我们使用Dialogflow和Python建立了一个简单的机票预订聊天机器人。我们已经涵盖了创建意图、实体和webhooks的基本知识,并将我们的聊天机器人与一个外部服务整合起来,以处理执行问题。有了这个基础,你可以扩展你的聊天机器人的功能,包括更多的高级功能和集成。