Building an End-to-End Currency Converter Chatbot with Python and Dialogflow

Chatbots have become increasingly popular in recent years as a way for businesses to automate customer support, streamline processes, and provide 24/7 assistance to users. Beyond customer service, chatbots can be used for a wide variety of applications, from e-commerce and lead generation to entertainment and education.

In this tutorial, we‘ll walk through the process of building a currency converter chatbot using Dialogflow and Python. Dialogflow is a conversational AI platform that enables developers to create engaging voice and text-based conversational interfaces, powered by machine learning. By the end of this guide, you‘ll have a fully functional chatbot that can handle currency conversion requests across different platforms.

What is Dialogflow?

Dialogflow, formerly known as API.AI, is a Google-owned platform for building conversational interfaces for websites, mobile apps, messaging platforms, and IoT devices. Some of the key features of Dialogflow include:

  • Natural Language Understanding (NLU): Dialogflow uses machine learning to understand the intent behind user queries, allowing your chatbot to engage in more natural conversations.

  • Entity Extraction: Dialogflow can identify and extract relevant information (entities) from user queries, such as dates, numbers, and custom categories you define.

  • Multi-language Support: Chatbots can be trained to understand and respond in over 20 languages.

  • Pre-built Agents: Dialogflow provides pre-trained agents for common use cases like appointment scheduling, which can be customized for your needs.

  • Integrations: Dialogflow integrates with a variety of messaging platforms, including Google Assistant, Facebook Messenger, Slack, and Telegram, as well as custom websites and apps.

One of the advantages of using a platform like Dialogflow is that it abstracts away much of the underlying complexity of natural language processing and machine learning, allowing developers to focus on designing the conversation flow and user experience. While it‘s certainly possible to build a chatbot from scratch using open-source libraries, Dialogflow provides a streamlined development process and a visual interface for training your chatbot.

Setting up a Dialogflow Agent

To get started with Dialogflow, you‘ll need to create a new agent. An agent is essentially a chatbot project that contains all the intents, entities, and dialog flows that define your bot‘s behavior.

  1. Sign in to the Dialogflow Console (https://dialogflow.cloud.google.com/).
  2. Click ‘Create Agent‘ and choose a name for your currency converter bot.
  3. Select a default language and time zone for your agent.
  4. Choose whether to use the standard or enterprise edition of Dialogflow (for this tutorial, the standard edition will suffice).
  5. Click ‘Create‘ to initialize your new agent.

Defining Intents and Entities

Intents represent the different types of user queries your chatbot can handle, while entities are the pieces of data you want to extract from those queries. For our currency converter, we‘ll need two main intents:

  1. ConvertIntent: This intent will handle queries like "convert 100 USD to EUR" or "what‘s 50 CAD in GBP?".
  2. FallbackIntent: This is a default intent that will be triggered if the user‘s query doesn‘t match any other intents.

To create the ConvertIntent:

  1. From the Intents page in Dialogflow, click ‘Create Intent‘.
  2. Name the intent ‘ConvertIntent‘.
  3. Under ‘Training Phrases‘, add examples of currency conversion queries, like:
    • "convert 100 USD to EUR"
    • "what‘s 50 CAD in GBP?"
    • "how much is 1000 JPY in USD?"
  4. Dialogflow will automatically detect the currency entities in these examples. To define them explicitly, select the currency amounts and currencies in each example and assign them the ‘@sys.unit-currency‘ and ‘@sys.currency-name‘ entities, respectively.
  5. Save the intent.

For the FallbackIntent, simply create a new intent named ‘FallbackIntent‘ and check the ‘Set this intent as the fallback intent‘ option.

Integrating a Currency Conversion API

To perform the actual currency conversion, we‘ll need to use an external API. There are several free and paid currency conversion APIs available; for this tutorial we‘ll use the free API from https://www.currencyconverterapi.com/.

  1. Sign up for a free account to get an API key.
  2. The API endpoint for converting currencies is:
    https://free.currconv.com/api/v7/convert?q=FROM_TO&compact=ultra&apiKey=YOUR_API_KEY
    where FROM is the source currency code, TO is the target currency code, and YOUR_API_KEY is your API key.

We‘ll call this API from our webhook in the next step.

Building a Webhook with Python and Flask

A webhook is a way for your Dialogflow agent to send a request to an external service and get a response back. We‘ll build our webhook using Python and the Flask web framework.

  1. Create a new file called app.py and install the required libraries (flask and requests).

  2. Here‘s the code for a basic webhook that converts currencies using the API:

from flask import Flask, request, jsonify
import requests

app = Flask(__name__)

@app.route(‘/webhook‘, methods=[‘POST‘])
def webhook():
    req = request.get_json(force=True)
    query_result = req[‘queryResult‘]

    # Extract the currency parameters
    from_currency = query_result[‘parameters‘][‘unit-currency‘][‘currency‘]
    to_currency = query_result[‘parameters‘][‘currency-name‘]
    amount = query_result[‘parameters‘][‘unit-currency‘][‘amount‘]

    # Call the currency conversion API
    api_key = ‘YOUR_API_KEY‘
    url = f‘https://free.currconv.com/api/v7/convert?q={from_currency}_{to_currency}&compact=ultra&apiKey={api_key}‘
    response = requests.get(url)
    response_json = response.json()

    # Extract the exchange rate
    exchange_rate = response_json[f‘{from_currency}_{to_currency}‘]
    print(exchange_rate)

    # Multiply the amount by the exchange rate
    converted_amount = amount * exchange_rate
    rounded_amount = round(converted_amount, 2)
    print(converted_amount)

    # Construct the response
    response = {
        "fulfillmentText": f‘{amount} {from_currency} is {rounded_amount} {to_currency}‘
    }

    return jsonify(response)

if __name__ == ‘__main__‘:
    app.run(debug=True)
  1. Replace ‘YOUR_API_KEY‘ with your actual API key.

  2. In Dialogflow, go to the ‘Fulfillment‘ section and enable the ‘Webhook‘ option. Paste in the URL where your Flask app will be running (e.g. https://your-app.com/webhook).

  3. Deploy your Flask app to a hosting service like Heroku or Google Cloud Platform, or run it locally and use a tool like ngrok to expose it to the internet.

Testing the Chatbot

With the webhook deployed and connected to your Dialogflow agent, you can now test your chatbot using the built-in web demo:

  1. In Dialogflow, go to the ‘Integrations‘ section and enable the ‘Web Demo‘ integration.
  2. Click on the URL provided to open the web demo in a new tab.
  3. Type in a currency conversion query like "convert 100 USD to EUR" and verify that the chatbot responds with the correct converted amount.

Deploying to Telegram

Dialogflow makes it easy to integrate your chatbot with various messaging platforms. Here‘s how you can deploy your currency converter bot to Telegram:

  1. Create a new Telegram bot by talking to the ‘BotFather‘ (https://telegram.me/botfather). Follow the prompts to choose a name and username for your bot, and save the API token provided.

  2. In Dialogflow, go to the ‘Integrations‘ section and enable the ‘Telegram‘ integration. Paste in your Telegram bot token.

  3. Start a chat with your Telegram bot and test it out with some currency conversion queries.

Best Practices and Tips

Here are some best practices to keep in mind when building chatbots with Dialogflow:

  • Use varied and representative training phrases for your intents to help your chatbot understand the different ways users might express a query.

  • Provide fallback responses for when the chatbot doesn‘t understand a query or when an error occurs.

  • Break up long bot responses into multiple messages to improve readability.

  • Personalize the chatbot‘s responses based on context or user data to create a more engaging experience.

  • Continuously monitor and analyze the conversations your chatbot has with users to identify areas for improvement.

  • Consider multi-language support if your userbase is international.

Next Steps

Congratulations, you now have a working currency converter chatbot that can be accessed across different platforms! Some potential enhancements you could make:

  • Expand the bot‘s capabilities to handle more complex queries, like "convert 100 USD to EUR and then to GBP".
  • Integrate the currency converter into a broader financial assistant chatbot that can also track expenses, provide budgeting tips, etc.
  • Experiment with Dialogflow‘s machine learning features to enable your chatbot to handle more open-ended conversations.

I hope this tutorial has been helpful in demonstrating the power and potential of chatbots. The combination of Dialogflow and Python makes it easy to build intelligent conversational interfaces and automate tasks across a wide range of domains. Feel free to adapt and expand upon this currency converter example for your own projects. Happy bot building!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Similar Posts