đ¤¯ How easy is it to integrate an AI chatbot into your app in 2024? đđĨŗ
Shrijal Acharya
Posted on January 2, 2024
TL;DR
In this tutorial, you will learn how to add AI chatbot support to your Python application in minutes.
Explore OpenAI and learn how to easily integrate it into your existing application with the OpenAI Python module.
On the agenda đĨ:
- How to use the OpenAI GPT model to generate chat responses in real time.
Let's code it up đ§đģââī¸
⨠For this tutorial, we will build a Python application from scratch with OpenAI.
Set up the environment đĨ
Create a folder for the project:
mkdir easy-build-an-ai-2024
cd easy-build-an-ai-2024
Now, let's create a virtual environment for our Python application. Run this command to create a virtual environment using venv
:
python -m venv venv
Activate the virtual environment on Linux:
source venv/bin/activate
âšī¸ Most of us use the fish shell, to activate the environment on the fish shell, run the following command:
. venv/bin/activate.fish
âšī¸ For Windows users, run the following command:
venv/bin/activate
After running the command, the virtual environment should be activated.
Now, install all the necessary packages required for the project:
pip install openai python-dotenv
đĄ To communicate with OpenAI, we will need an API key. First, create an account on OpenAI and obtain the API key.
In the project's root, create a new file named .env
, add a new environment variable called OPENAI_API_KEY
, and paste the API key you just generated.
# đ /.env
OPENAI_API_KEY=<YOUR_API_KEY>
Let's Code đ¨âđģ
Create a new file called main.py
in the project's root. Add the following chunk of code:
# đ /main.py
import os
import openai
from dotenv import find_dotenv, load_dotenv
# find .env file
dotenv_path = find_dotenv()
# load up the entries as environment variables
load_dotenv(dotenv_path)
# get the OPENAI_API_KEY from environment variable
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# set the api key for openai
openai.api_key = OPENAI_API_KEY
We are importing the required modules, retrieving the environment variables from the .env
file, and setting up the OpenAI API key with the one we just created.
Now, we need to set up the actual code that talks with the OpenAI.
# đ /main.py
...
def chat_with_openai(prompt):
try:
# Create a chat completion with OpenAI API
response = openai.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}],
)
# Extract the content of the message from the response
response_content = response.choices[0].message.content
# Strip any leading or trailing whitespace from the response content
response_content_stripped = response_content.strip()
return response_content_stripped
except Exception as e:
print(f"An error occurred: {str(e)}")
return "Sorry, something went wrong. Please try again."
if __name__ == "__main__":
while True:
user_input = input("ASK ANYTHING >> ")
if user_input.lower() in ["bye", "quit", "exit"]:
break
# Get a response from the OpenAI model
response = chat_with_openai(user_input)
print("RESPONSE: ", response)
The code uses OpenAI's GPT-3.5 Turbo
model to generate responses, and it runs a continuous loop for user input until the user decides to exit.
And, this is it. Our simple Python application with OpenAI chatbot support is all set. đ
Run the application in the terminal and talk with GPT.
python main.py
Wrap Up! â¨
By now, you have a generic understanding of how easy it is to integrate an AI chatbot into your application just with the help of a few functions from OpenAI in your Python application.
Please let me know your thoughts on the article in the comments section below. đ
The source code for this article is available here:
https://github.com/shricodev/blogs/tree/main/easy-build-an-ai-2024
So, that is it for this article. Thank you so much for reading! đđĢĄ
Posted on January 2, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
January 2, 2024
September 10, 2023