Select your cookie preferences

We use essential cookies and similar tools that are necessary to provide our site and services. We use performance cookies to collect anonymous statistics, so we can understand how customers use our site and make improvements. Essential cookies cannot be deactivated, but you can choose “Customize” or “Decline” to decline performance cookies.

If you agree, AWS and approved third parties will also use cookies to provide useful site features, remember your preferences, and display relevant content, including relevant advertising. To accept or decline all non-essential cookies, choose “Accept” or “Decline.” To make more detailed choices, choose “Customize.”

AWS Logo
Menu
From 'Bonjour' to 'Boarding Pass': Multilingual AI Chatbot for Flight Reservations

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.

Published Aug 29, 2024
Last Modified Aug 30, 2024
Imagine a bustling international airport. Travelers from every corner of the world are rushing to catch their flights, a symphony of languages filling the air. Now, picture a single AI chatbot capable of assisting each of these travelers in their native tongue, booking flights with incredible efficiency. Sounds like something out of a spy movie, doesn't it? Well, get ready, because I'm about to show you how to make this a reality!
In this article, I'll guide you through creating a multilingual AI chatbot for booking flights. Here's the exciting part: we'll be using a framework I helped develop called the Multi-Agent Orchestrator. This framework is our secret weapon, making our mission much easier, and I'm thrilled to share it with you.
The Multi-Agent Orchestrator framework is like M from James Bond movies. But instead of managing just one 007, it coordinates a whole team of AI secret agents. Each AI agent has its own special skills - like language translation or flight booking. These AI agents work together on their mission: to help travelers from around the world.
Here's what I'll cover in this article:
  1. What the Multi-Agent Orchestrator framework is and how it works
  2. How to set up our chatbot that speaks many languages and books flights
  3. How to use Amazon Lex to understand what people are saying
  4. How to make our chatbot translate languages
  5. How to put everything together to make a smooth, multi-language experience
By the end of this article, you'll know how to use AI agents together to do complex tasks. This skill is useful for more than just booking flights. You could use it for online shopping, helping customers, or any job where talking to people in different languages is important.
So, open your computer and get ready to code. I'm excited to show you how to make a chatbot that can talk to people from all around the world!
Here is the cool part: our flight reservation bot is just one example of what's possible. The Multi-Agent Orchestrator framework includes a flexible feature that allows each agent to perform a series of actions in sequence. This capability opens up endless possibilities for building complex, multi-step workflows. In this article, we'll explain how this works and show you how to apply it to create a seamless experience, such as translating user input, processing it with Amazon Lex, and translating the response back—all in one fluid interaction.
While I'm focused on flight reservations here, you could easily adapt this idea to create a network of diverse AI agents to fit to your specific needs. The key is that the Multi-Agent Orchestrator framework remains constant, providing a solid foundation for various applications.
You might deploy agents for processing orders, answering customer inquiries, or providing technical support - all while maintaining seamless communication across multiple languages. The specific roles and capabilities of each agent can be customized to your requirements, whether you're in e-commerce, customer service, healthcare, or any field where clear, multilingual communication is crucial.
The framework allows you to mix and match different types of AI agents - perhaps combining a language model for natural conversation, a specialized agent for data processing, and another for decision-making. This versatility opens up a world of possibilities, enabling you to create sophisticated, multi-functional systems that can handle complex tasks across language barriers.

Let's get started

Before we dive in, make sure you have the following:
  • 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

Step 1: Set up an Amazon Lex Bot

To implement this example, you'll need an Amazon Lex bot, as the framework itself doesn't create any resources. Follow these steps to quickly set up a Lex bot:
  1. Sign in to the AWS Management Console and navigate to the Amazon Lex service.
  2. Click on "Create bot" and select the template "Airline Services" from the list of templates.
  3. Give your bot a name (e.g., "MultilingualAirlineBot")
  4. Choose your preferred language (e.g., English)
  5. Under "IAM permissions", select "Create a role with basic Amazon Lex permissions"
  6. Click "Next"
  7. Review the sample intents and slots, then click "Create bot"
  8. Once the bot is created, build and test it in the Lex console to ensure it's working correctly
  9. Note down the Bot ID, Bot Alias ID, and Locale ID from the bot settings
Important: Sample data to be used when providing answers in the example below is available here.

Step 2: Install required libraries

Open your terminal and install the necessary Python libraries:
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

Step 3: Import required classes

Create a new Python file named 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
)

Step 4: Configure the Orchestrator

Add the following configuration to your 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()
Replace YOUR_BOT_ID and YOUR_BOT_ALIAS_ID with the actual values from your Lex bot.

Step 5: Implement a language detection function

Add a helper function to detect the language of user input:
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']
In this example, we identify the user's language by analyzing their initial input and then use this language for the remainder of the conversation. You might choose to follow this approach, or you may already have a method to determine the user's language, in which case this step would be unnecessary.

Step 6: Create the agents

Implement the main function that sets up the agents and handles the conversation:
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())
The code creates the 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:
  1. Translator to English – This agent converts the user's input into English, ensuring the input is ready for processing.
  2. Lex Bot – Serves as the core agent that processes the user's request using an Amazon Lex bot.
  3. Translator from English – This agent translates the bot’s response back into the user's original language.
These agents are seamlessly linked within the ChainAgent, enabling our chatbot to handle multilingual interactions efficiently by automatically translating input and output while interacting with the English-configured Lex Bot.
The framework allows you to orchestrate multiple top-level agents for user input and select the best one, while also enabling each agent to be composed of a chain of sub-agents, as demonstrated in our multilingual example.
This diagram illustrates how the agents are assembled within the framework:
Image not found
Multi lingual diagram flow

Step 7: Execute the script

Save your multilingual_chatbot.py file and run it:
1
python multilingual_chatbot.py
Now, let's test our multilingual chatbot with examples in different languages. We'll start with French, then exit the script and restart it to demonstrate interactions in Spanish and Portuguese.
Notice the lines beginning with "You:", which represent user input, and the lines starting with "> Response:" which show the chatbot's replies.

French

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>
Now, let's exit the script and start a new conversation in Spanish.


Spanish

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.
Let's exit once more and restart the script, this time interacting in Portuguese.

Portuguese

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.

An alternative approach: direct Agent usage

While the Multi-Agent Orchestrator is powerful for managing multiple agents and complex workflows, there are scenarios where you might not need its full capabilities. If you have a specific sequence of tasks and don't require agent selection or complex orchestration, you can call an agent directly.
In the multilingual chatbot example, we use a chain of three tasks:
  1. Translate to English
  2. Process with Lex bot
  3. Translate back to the original language.
We can accomplish this by directly using the ChainAgent.
Image not found
Direct Agent call
In this direct approach, the user input flows through a predefined sequence of agents within a ChainAgent, bypassing the need for an orchestrator.
Let's see how to implement this version for the chatbot example.
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())
Here, we create the ChainAgent as before, but instead of adding it to an orchestrator, we call its process_request method directly.

Conclusion

In this article, I've demonstrated how to build a multilingual chatbot that leverages the Multi-Agent Orchestrator framework, allowing users to interact with an airline bot in their preferred language. However, this example only scratches the surface of what's possible with this framework.
One of the key strengths of the Multi-Agent Orchestrator is its flexibility in agent selection and chaining. The framework allows you to have multiple agents available to handle user input, automatically selecting the best-fit agent based on the context or query. You can also chain multiple agents to process a single user input, unlocking multiple ways to cover diverse use cases.
While I've focused on an airline services bot, you can apply these principles to any Lex bot template (or any other agent) or custom bot you create.
It's worth noting that while this example uses Python, the Multi-Agent Orchestrator framework is also available for TypeScript, allowing you to implement similar functionality in a JavaScript environment. This cross-language support provides flexibility in choosing your development ecosystem.
In the above example, we used the BedrockTranslatorAgent with the Claude Haiku model for translation. However, the framework offers great flexibility in terms of model selection. Depending on your specific requirements, you could easily swap out the translation model for a smaller and faster one, or even integrate a locally running model. This adaptability makes it straightforward to optimize your chatbot for different performance requirements or deployment scenarios.
I encourage you to explore further and adapt this example to your specific needs.

Explore more

Ready to dive deeper? Check out the resources below to get the most out of the Multi Agent Orchestrator:
  • 📚 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.
     
If you find this framework helpful, please consider giving us a star on GitHub. Also we would love to hear your thoughts, so feel free to leave a comment below. And if you have ideas for new features or improvements, don't hesitate to create a feature request on our GitHub repository.
 

Comments

Log in to comment