
From 'Bonjour' to 'Boarding Pass': Multilingual AI Chatbot for Flight Reservations
Create a global flight reservation chatbot in minutes! This tutorial walks you through building a multilingual chatbot using the Multi-Agent Orchestrator framework. Learn to effortlessly chain AI agents for instant language processing and booking across multiple languages. Transform complex, multi-step processes into a polyglot flight reservation system.
- What the Multi-Agent Orchestrator framework is and how it works
- How to set up our chatbot that speaks many languages and books flights
- How to use Amazon Lex to understand what people are saying
- How to make our chatbot translate languages
- How to put everything together to make a smooth, multi-language experience
- An AWS account with access to Amazon Lex, Amazon Bedrock, and Amazon Comprehend
- Python 3.7 or later installed on your local machine
- Basic knowledge of Python and AWS services
- The AWS CLI installed and configured with your credentials
- Sign in to the AWS Management Console and navigate to the Amazon Lex service.
- Click on "Create bot" and select the template "Airline Services" from the list of templates.
- Give your bot a name (e.g., "MultilingualAirlineBot")
- Choose your preferred language (e.g., English)
- Under "IAM permissions", select "Create a role with basic Amazon Lex permissions"
- Click "Next"
- Review the sample intents and slots, then click "Create bot"
- Once the bot is created, build and test it in the Lex console to ensure it's working correctly
- Note down the Bot ID, Bot Alias ID, and Locale ID from the bot settings
1
2
3
4
5
mkdir test_multilingual_chatbot
cd test_multilingual_chatbot
python -m venv venv
source venv/bin/activate # On Windows use `venv\Scripts\activate`
pip install boto3 asyncio uuid multi-agent-orchestrator
multilingual_chatbot.py
and add the following imports:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import asyncio
import uuid
import boto3
from multi_agent_orchestrator.orchestrator import MultiAgentOrchestrator, OrchestratorConfig
from multi_agent_orchestrator.agents import (
BedrockLLMAgent,
AgentResponse,
BedrockLLMAgentOptions,
BedrockTranslatorAgent,
BedrockTranslatorAgentOptions,
LexBotAgent,
LexBotAgentOptions,
ChainAgent,
ChainAgentOptions
)
multilingual_chatbot.py
:1
2
3
4
5
6
7
# Configuration
LEX_BOT_ID = "YOUR_BOT_ID"
LEX_BOT_ALIAS_ID = "YOUR_BOT_ALIAS_ID"
LEX_LOCALE_ID = "en_US"
# Initialize orchestrator
orchestrator = MultiAgentOrchestrator()
YOUR_BOT_ID
and YOUR_BOT_ALIAS_ID
with the actual values from your Lex bot.1
2
3
4
async def detect_language(text: str) -> str:
comprehend_client = boto3.client('comprehend', region_name='us-east-1')
response = comprehend_client.detect_dominant_language(Text=text)
return response['Languages'][0]['LanguageCode']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
async def run_multilingual_chatbot():
tech_agent = BedrockLLMAgent(BedrockLLMAgentOptions(
name="Tech Agent",
streaming=True,
description="Specializes in technology areas including software development, hardware, AI, cybersecurity, blockchain, cloud computing, emerging tech innovations, and pricing/costs related to technology products and services.",
model_id="anthropic.claude-3-sonnet-20240229-v1:0"
))
translator_to_english = BedrockTranslatorAgent(BedrockTranslatorAgentOptions(
name="Translator to English",
description="Translates user input to English",
target_language="en"
))
lex_bot = LexBotAgent(LexBotAgentOptions(
name="Lex Bot",
description="Processes user requests",
bot_id=LEX_BOT_ID,
bot_alias_id=LEX_BOT_ALIAS_ID,
locale_id=LEX_LOCALE_ID
))
translator_from_english = BedrockTranslatorAgent(BedrockTranslatorAgentOptions(
name="Translator from English",
description="Translates response back to user's language",
source_language="en"
))
multilingual_chain_agent = ChainAgent(ChainAgentOptions(
name="Multi-lingual Processing Chain",
description="Helps users with airline services in multiple languages",
agents=[translator_to_english, lex_bot, translator_from_english]
))
orchestrator.add_agent(tech_agent)
orchestrator.add_agent(multilingual_chain_agent)
user_id = str(uuid.uuid4())
session_id = str(uuid.uuid4())
detected_language: Optional[str] = None
print("Welcome to the multilingual airline services chatbot. Type your queries in any language and press Enter. Type 'exit' to end the conversation.")
while True:
user_input = input("You: ").strip()
if user_input.lower() == 'exit':
print("Thank you for using our multilingual airline services chatbot. Goodbye!")
break
if not detected_language:
detected_language = await detect_language(user_input)
print(f"Detected language: {detected_language}")
translator_to_english.set_source_language(detected_language)
translator_from_english.set_target_language(detected_language)
try:
response = await orchestrator.route_request(user_input, user_id, session_id)
print(response.output.content[0]['text'])
except Exception as error:
print("Error:", error)
if __name__ == "__main__":
asyncio.run(run_multilingual_chatbot())
run_multilingual_chatbot()
function, which sets up two agents: a technical agent and a multilingual agent. For the purposes of this article, while we include a technical agent but our focus is on the multilingual agent. This multilingual agent employs the ChainAgent
to effectively orchestrate three sub-agents:- Translator to English – This agent converts the user's input into English, ensuring the input is ready for processing.
- Lex Bot – Serves as the core agent that processes the user's request using an Amazon Lex bot.
- Translator from English – This agent translates the bot’s response back into the user's original language.
ChainAgent
, enabling our chatbot to handle multilingual interactions efficiently by automatically translating input and output while interacting with the English-configured Lex Bot.multilingual_chatbot.py
file and run it:1
python multilingual_chatbot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
Welcome to the multi-lingual AI agent. Type your queries in any language and press Enter. Type 'exit' to end the conversation.
You: je veux reserver un billet d'avion
Detected language: fr
> Response:
J'ai remarqué que vous avez un compte de voyageur fréquent avec nous. Pouvez-vous me confirmer votre numéro de voyageur fréquent ?
You: *****
> Response:
Merci. Et pour vérification, puis-je obtenir les quatre derniers chiffres de la carte de crédit enregistrée ?
You: ****
> Response:
D'accord. Laissez-moi obtenir des informations sur votre voyage. S'agit-il d'un voyage aller simple ou d'un voyage aller-retour ?
You: aller retour
> Response:
D'accord. De quelle ville partez-vous ?
You: paris
> Response:
paris. D'accord. Et quelle est votre destination ?
You: new york
> Response:
D'accord. Quelle date souhaitez-vous prendre le vol ?
You: demain
> Response:
Et quelle date souhaitez-vous prendre le vol retour ?
You: dans une semaine
> Response:
D'accord. Quel est le nombre total de voyageurs ?
You: moi uniquement
> Response:
D'accord. Quelle est votre heure de départ préférée ? Vous pouvez dire quelque chose comme 8h
You: l'après midi
> Response:
D'accord. Quelle est votre heure de départ préférée pour le vol retour ? Vous pouvez dire quelque chose comme 8h.
You: l'après midi
> Response:
D'accord. Pour votre vol de départ, j'ai le numéro de vol A123 qui part à 5h30 du matin, et le vol de retour, Z123, qui part à 21h30 et arrive à 23h30. Le coût de ce voyage aller-retour est de 250 $. Si vous voulez procéder avec cela, dites simplement oui. Sinon, dites "obtenir plus d'options".
You: oui
> Response:
Puis-je utiliser la carte enregistrée se terminant par <say-as interpret-as='digits'>3456</say-as> pour faire la réservation ?
You: oui
> Response:
Très bien. J'ai pour vous le vol B123 à destination de New York au départ de Paris le 29/08/2024 à 6h30 et le retour de Paris à New York le 08/09/2024 à 20h30. Votre code de confirmation est <say-as interpret-as='digits'>60343</say-as>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Welcome to the multilingual airline services chatbot. Type your queries in any language and press Enter. Type 'exit' to end the conversation.
You: Hola, quiero reservar un vuelo
Detected language: es
Bot: Hola, he notado que tiene una cuenta de viajero frecuente con nosotros. ¿Puede confirmarme su número de viajero frecuente?
You: *****
Bot: Gracias. Y para verificación, ¿puedo obtener los últimos cuatro dígitos de la tarjeta de crédito registrada?
You: ****
Bot: Bien. Déjeme obtener información sobre su viaje. ¿Es un viaje de ida y vuelta o solo de ida?
You: Ida y vuelta
Bot: Entendido. ¿Desde qué ciudad está saliendo?
You: Madrid
Bot: Madrid, de acuerdo. ¿Y cuál es su destino?
You: Nueva York
Bot: Entendido. ¿En qué fecha le gustaría tomar el vuelo de ida?
You: Mañana
Bot: ¿Y en qué fecha le gustaría tomar el vuelo de regreso?
You: En una semana
Bot: De acuerdo. ¿Cuál es el número total de viajeros?
You: Solo yo
Bot: Entendido. ¿Cuál es su hora de salida preferida para el vuelo de ida? Puede decir algo como "8 de la mañana".
You: 8AM
Bot: De acuerdo. ¿Y cuál es su hora de salida preferida para el vuelo de regreso?
You: 6PM
Bot: Bien. Para su vuelo de ida, tengo el vuelo número S789 que sale a las 15:00, y para el regreso, el vuelo R456 que sale a las 18:00 y llega a las 20:30. El costo de este viaje de ida y vuelta es de 300 €. Si desea proceder con esto, simplemente diga sí. De lo contrario, diga "obtener más opciones".
You: Sí
Bot: ¿Puedo usar la tarjeta registrada que termina en 7890 para hacer la reserva?
You: Sí
Bot: Excelente. He reservado para usted el vuelo S789 a Nueva York desde Madrid mañana a las 15:00 y el regreso de Nueva York a Madrid en una semana a las 18:00. Su código de confirmación es 54321.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Welcome to the multilingual airline services chatbot. Type your queries in any language and press Enter. Type 'exit' to end the conversation.
You: Olá, gostaria de reservar uma passagem aérea
Detected language: pt
Bot: Olá! Notei que você tem uma conta de viajante frequente conosco. Pode confirmar seu número de viajante frequente?
You: *****
Bot: Obrigado. E para verificação, posso obter os últimos quatro dígitos do cartão de crédito registrado?
You: ****
Bot: Certo. Deixe-me obter informações sobre sua viagem. É uma viagem só de ida ou de ida e volta?
You: Ida e volta
Bot: Entendido. De qual cidade você está partindo?
You: Lisboa
Bot: Lisboa, certo. E qual é o seu destino?
You: Nova York
Bot: Entendi. Em que data você gostaria de fazer o voo de ida?
You: Amanhã
Bot: E em que data você gostaria de fazer o voo de volta?
You: Em uma semana
Bot: Certo. Qual é o número total de viajantes?
You: Apenas eu
Bot: Entendido. Qual é o seu horário de partida preferido para o voo de ida? Você pode dizer algo como "8 da manhã".
You: 7AM
Bot: Certo. E qual é o seu horário de partida preferido para o voo de volta?
You: 5PM
Bot: Bem, para o seu voo de ida, tenho o voo número P234 que parte às 14:00, e para o retorno, o voo L567 que parte às 17:00 e chega às 19:30. O custo desta viagem de ida e volta é de 280 €. Se você quiser prosseguir com isso, basta dizer sim. Caso contrário, diga "obter mais opções".
You: Sim
Bot: Posso usar o cartão registrado que termina em 2468 para fazer a reserva?
You: Sim
Bot: Ótimo. Reservei para você o voo P234 para Nova York saindo de Lisboa amanhã às 14:00 e o retorno de Nova York para Lisboa em uma semana às 17:00. Seu código de confirmação é 13579.
- Translate to English
- Process with Lex bot
- Translate back to the original language.
ChainAgent
.ChainAgent
, bypassing the need for an orchestrator. 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import asyncio
import uuid
from multi_agent_orchestrator.agents import (
BedrockTranslatorAgent,
BedrockTranslatorAgentOptions,
LexBotAgent,
LexBotAgentOptions,
ChainAgent,
ChainAgentOptions
)
async def run_multilingual_chatbot_direct():
translator_to_english = BedrockTranslatorAgent(BedrockTranslatorAgentOptions(
name="Translator to English",
description="Translates user input to English",
target_language="en"
))
lex_bot = LexBotAgent(LexBotAgentOptions(
name="Lex Bot",
description="Processes user requests",
bot_id=LEX_BOT_ID,
bot_alias_id=LEX_BOT_ALIAS_ID,
locale_id=LEX_LOCALE_ID
))
translator_from_english = BedrockTranslatorAgent(BedrockTranslatorAgentOptions(
name="Translator from English",
description="Translates response back to user's language",
source_language="en"
))
multilingual_chain_agent = ChainAgent(ChainAgentOptions(
name="Multi-lingual Processing Chain",
description="Helps users with airline services in multiple languages",
agents=[translator_to_english, lex_bot, translator_from_english]
))
user_id = str(uuid.uuid4())
session_id = str(uuid.uuid4())
detected_language: Optional[str] = None
print("Welcome to the multilingual airline services chatbot. Type your queries in any language and press Enter. Type 'exit' to end the conversation.")
while True:
user_input = input("You: ").strip()
if user_input.lower() == 'exit':
print("Thank you for using our multilingual airline services chatbot. Goodbye!")
break
if not detected_language:
detected_language = await detect_language(user_input)
print(f"Detected language: {detected_language}")
translator_to_english.set_source_language(detected_language)
translator_from_english.set_target_language(detected_language)
try:
response = await multilingual_chain_agent.process_request(user_input, user_id, session_id)
print(response.output.content[0]['text'])
except Exception as error:
print("Error:", error)
if __name__ == "__main__":
asyncio.run(run_multilingual_chatbot_direct())
ChainAgent
as before, but instead of adding it to an orchestrator, we call its process_request
method directly.- 📚 Documentation: Get comprehensive guidance and details on how to use the toolkit effectively.
- 🛠️ GitHub Repository: Access the source code, contribute, or browse issues and updates.
- 📦 NPM Repository: Find installation details and version information for the toolkit.
- 📦 PyPi Repository: Find installation details and version information for the toolkit.