Build a Multilingual Chatbot With FastAPI and Google Cloud Translation
Create a multilingual chatbot that utilizes FastAPI and Google Cloud Translation for seamless communication across languages.
Join the DZone community and get the full member experience.
Join For FreeIn our connected world, having a chatbot that can speak multiple languages is important for businesses. This guide will show you how to build a simple multilingual chatbot using Python, FastAPI, the Google Cloud Translation API, and a sentiment analysis tool from Hugging Face.
Get Started With Python, FastAPI, and the Google Cloud Translation API
First, make sure that Python installed on our computer. Next, set up your FastAPI uvicorn library:
pip install fastapi uvicorn google-cloud-translate transformers
And finally, you will need to set up a Google Cloud project, enable the Translation API, and download the service account key as a JSON file.
Understanding the Code
Before we write the code, let’s break down what we’ll be doing and using:
- Setting up FastAPI: This will allow us to create a web server to handle requests from users.
- Google Cloud Translation: We’ll use this service to translate messages between languages.
- Sentiment analysis: We’ll analyze the user’s message to understand if it’s positive or negative, helping us respond appropriately.
- Chat endpoint: We’ll create an endpoint (URL) where users can send messages and receive responses.
Writing the Code in Python
Let's start with the writing of the code. We will create a new Python file called chatbot.py
and add the following code:
from fastapi import FastAPI
from pydantic import BaseModel
from google.cloud import translate_v2 as translate
import os
# Set up Google Cloud Translation API credentials
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path/to/your/service-account-file.json"
# Create a FastAPI app
app = FastAPI()
translate_client = translate.Client()
# Define the structure for chat requests
class ChatRequest(BaseModel):
message: str
language: str = 'en' # Default to English
# Create the chat endpoint
@app.post("/chat")
async def chat(request: ChatRequest):
user_message = request.message
user_language = request.language
# If no language is provided, detect the user's language
if not user_language:
detected_language = translate_client.detect_language(user_message)
user_language = detected_language['language']
# Simple responses based on the message
if "hello" in user_message.lower():
response_message = "Hello! How can I assist you today?"
elif "thank you" in user_message.lower():
response_message = "You're welcome!"
else:
response_message = "I'm here to help!"
# Translate the response back to the user's language
translated_response = translate_client.translate(response_message, target_language=user_language)['translatedText']
return {
'response': translated_response,
'language': user_language
}
# Run the app
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)
Explanation of the Code and Next Steps
-
Importing Libraries:
- We import the necessary libraries.
FastAPI
is for creating a web server, andgoogle-cloud-translate
is for translating messages.
- We import the necessary libraries.
-
Setting up API credentials:
- We set the path to our Google Cloud service account key, which allows us to access the Translation API.
-
Creating the FastAPI app:
- We create an instance of the FastAPI app, which will handle our chatbot's requests.
-
Defining the ChatRequest class:
- This class defines the structure of our chat requests. It includes:
message
: The user's message.language
: The user's preferred language, defaulting to English.
- This class defines the structure of our chat requests. It includes:
-
Creating the chat endpoint:
- The
/chat
endpoint listens for POST requests. When a user sends a message:- We can detect if the user doesn't provide a language (optional).
- We create simple responses based on the content of the message (e.g., greeting or thanking).
- Finally, we translate our response back to the user’s language and send it back.
- The
-
Running the app:
- The last lines of code start the FastAPI server, allowing us to interact with the chatbot.
Running Our Chatbot
To run our chatbot, we open the terminal and navigate to the directory where our chatbot.py
file is located. Then, we type:
uvicorn chatbot:app --reload
This will start the server, and we can access it at http://127.0.0.1:8000
Testing the Chatbot
We can test the chatbot using tools like Postman or CURL. Here’s an example using CURL:
curl -X POST http://127.0.0.1:8000/chat \
-H "Content-Type: application/json" \
-d '{"message": "Estoy muy feliz", "language": "es"}'
Conclusion
We have now successfully built a multilingual chatbot using FastAPI, Google Cloud Translation, and sentiment analysis. This chatbot can understand user sentiments and respond appropriately in different languages. We can enhance this further by adding more complex features or integrating it with databases for a better user experience.
Opinions expressed by DZone contributors are their own.
Comments