DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Building and Deploying a Chatbot With Google Cloud Run and Dialogflow
  • Transforming Telecom With AI/ML: A Deep Dive Into Smart Networks
  • Build Your First Python Chatbot Project
  • Traditional Testing and RAGAS: A Hybrid Strategy for Evaluating AI Chatbots

Trending

  • Advancing Robot Vision and Control
  • Next Evolution in Integration: Architecting With Intent Using Model Context Protocol
  • Distributed Consensus: Paxos vs. Raft and Modern Implementations
  • Navigating and Modernizing Legacy Codebases: A Developer's Guide to AI-Assisted Code Understanding
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Build a Multilingual Chatbot With FastAPI and Google Cloud Translation

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.

By 
Neha Dhaliwal user avatar
Neha Dhaliwal
·
Nov. 07, 24 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
1.0K Views

Join the DZone community and get the full member experience.

Join For Free

In 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:

Shell
 
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:

  1. Setting up FastAPI: This will allow us to create a web server to handle requests from users.
  2. Google Cloud Translation: We’ll use this service to translate messages between languages.
  3. Sentiment analysis: We’ll analyze the user’s message to understand if it’s positive or negative, helping us respond appropriately.
  4. 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:

Python
 
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

  1. Importing Libraries:

    • We import the necessary libraries. FastAPI is for creating a web server, and google-cloud-translate is for translating messages.
  2. Setting up API credentials:

    • We set the path to our Google Cloud service account key, which allows us to access the Translation API.
  3. Creating the FastAPI app:

    • We create an instance of the FastAPI app, which will handle our chatbot's requests.
  4. 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.
  5. Creating the chat endpoint:

    • The /chatendpoint 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.
  6. 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:

Shell
 
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:

Shell
 
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.

Chatbot Google Cloud Shell Python (language)

Opinions expressed by DZone contributors are their own.

Related

  • Building and Deploying a Chatbot With Google Cloud Run and Dialogflow
  • Transforming Telecom With AI/ML: A Deep Dive Into Smart Networks
  • Build Your First Python Chatbot Project
  • Traditional Testing and RAGAS: A Hybrid Strategy for Evaluating AI Chatbots

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!