In this Python ChatBot article we want to learn How to Build Python Chatbot with Rasa, so Chatbots are computer programs designed to simulate human conversation. they are becoming increasingly popular in customer service, ecommerce and other industries. building chatbot may seem like hard task, but with the right tools and a little bit of Python knowledge, it can be done quickly and easily. in this article we are going to learn building simple chatbot using Python and Rasa.
What is Rasa?
Rasa is an open source framework that allows you to build intelligent chatbots that can understand natural language and respond accordingly. it uses machine learning and natural language processing (NLP) to interpret user messages and generate appropriate responses.
So first of we need to install these libraries and we can use pip for the installation.
1 |
pip install rasa |
After installation you need to create new rasa Project, and you can use rasa init command in your terminal, after rasa init you will see this output in your terminal, and also i have not trained the model right, because when you are creating your Rasa project, it will ask you for model training, I have chosen No.
rasa init command will create several files and directories inside it, including:
- data/nlu.yml: file where you can define the intents and examples for your chatbot
- data/stories.yml: file where you can define the conversation flows for your chatbot
- actions.py: Python file where you can define custom actions for your chatbot
- config.yml: aonfiguration file where you can specify settings for your chatbot, such as the pipeline for your NLU and dialogue models
This will be the project structure after rasa init.
Once the project is set up, open the data directory and edit the nlu.yml file to add some training data for our chatbot:
1 2 3 4 5 6 7 8 9 10 11 12 |
version: "3.1" nlu: - intent: greet examples: | - hello - hi - hey - intent: inform examples: | - What's the weather like in [New York](city)? - How is the weather in [London](city) today? |
These are just few example messages for each intent, but you can add more to improve the accuracy of your chatbot.
After that we need to define some actions that our chatbot can take in response to user input. Open actions.py file in the actions directory and replace the contents with the following code:
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 |
import requests from typing import Any, Text, Dict, List from rasa_sdk import Action, Tracker from rasa_sdk.executor import CollectingDispatcher class ActionWeather(Action): def name(self) -> Text: return "action_weather" def run( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any] ) -> List[Dict[Text, Any]]: # Get the city entity from the user's message city = tracker.get_slot("city") # Call the OpenWeatherMap API to get the weather information api_key = "YOUR API KEY" url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}" response = requests.get(url).json() # Extract the temperature and weather description from the response temperature = response["main"]["temp"] description = response["weather"][0]["description"] # Convert temperature from Kelvin to Celsius temperature_celsius = round(temperature - 273.15, 2) # Respond with a message about the weather message = f"The weather in {city} is {description} and the temperature is {temperature_celsius}°C." dispatcher.utter_message(text=message) return [] |
This is Python code defining an action called “ActionWeather” for Rasa chatbot.
action is triggered when the intent and the entity city are detected in the user’s message. it uses tracker object to get the value of the city entity, which represents name of city.
after that the code processes the information by using an API to get weather information for the specified city , and finally responds with message about the weather in the city using the “dispatcher.utter_message” method.
The “return []” statement at the end of the “run” method returns an empty list of events, which means that no further events will be executed after this action.
After that we need to define story that describes the conversation flow between the user and our chatbot. open the stories.yml file in the data directory and replace the contents with the following code:
1 2 3 4 5 6 7 8 9 10 11 12 |
version: "3.1" stories: - story: greet and inform steps: - intent: greet - action: utter_greet - action: utter_ask_city - intent: inform entities: - city: "New York" - action: action_weather |
Also you need add the action in endpoints.yml.
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 |
# This file contains the different endpoints your bot can use. # Server where the models are pulled from. # https://rasa.com/docs/rasa/model-storage#fetching-models-from-a-server #models: # url: http://my-server.com/models/default_core@latest # wait_time_between_pulls: 10 # [optional](default: 100) # Server which runs your custom actions. # https://rasa.com/docs/rasa/custom-actions action_endpoint: url: "http://localhost:5055/webhook" # Tracker store which is used to store the conversations. # By default the conversations are stored in memory. # https://rasa.com/docs/rasa/tracker-stores #tracker_store: # type: redis # url: <host of the redis instance, e.g. localhost> # port: <port of your redis instance, usually 6379> # db: <number of your database within redis, e.g. 0> # password: <password used for authentication> # use_ssl: <whether or not the communication is encrypted, default false> #tracker_store: # type: mongod # url: <url to your mongo instance, e.g. mongodb://localhost:27017> # db: <name of the db within your mongo instance, e.g. rasa> # username: <username used for authentication> # password: <password used for authentication> # Event broker which all conversation events should be streamed to. # https://rasa.com/docs/rasa/event-brokers #event_broker: # url: localhost # username: username # password: password # queue: queue |
endpoints.yml is configuration file used by Rasa to define different endpoints that our bot can use. it includes endpoints for different components of bot such as server where the models are stored, server which runs custom actions, tracker store which is used to store conversations and the event broker which streams conversation events.
In our case we have added an action_endpoint to the file, which specifies the URL where our custom actions are hosted.
Now we need to train our model, you can use this command
1 |
rasa train |
After training you will see this output.
Now open two terminals, in the first one run the actions like this
1 |
rasa run actions |
And in the second terminal run this code
1 |
rasa shell |
Now you can ask the weather from ChatBot
Learn More on Python GUI
- How to Create Label in PySide6
- How to Create Button in Python & PySide6
- How to Use Qt Designer with PySide6
- How to Add Icon to PySide6 Window
- How to Load UI in Python PySide6
- How to Create RadioButton in PySide6
- How to Create ComboBox in PySide6
- How to Create CheckBox in Python PySide6
- Responsive Applications with PyQt6 Multithreading