DEV Community

Cover image for đŸ¤¯ How easy is it to integrate an AI chatbot into your app in 2024? 🏆đŸĨŗ
Shrijal Acharya
Shrijal Acharya

Posted on • Updated on

đŸ¤¯ How easy is it to integrate an AI chatbot into your app in 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.

Buckle Up


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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Activate the virtual environment on Linux:

source venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

ℹī¸ Most of us use the fish shell, to activate the environment on the fish shell, run the following command:

. venv/bin/activate.fish
Enter fullscreen mode Exit fullscreen mode

ℹī¸ For Windows users, run the following command:

venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

After running the command, the virtual environment should be activated.

Python Virtual Environment

Now, install all the necessary packages required for the project:

pip install openai python-dotenv
Enter fullscreen mode Exit fullscreen mode

💡 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>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Python application terminal demo


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! 🎉đŸĢĄ

Top comments (3)

Collapse
 
shricodev profile image
Shrijal Acharya

I want to share something with you. Just two years ago, I created a simple application in Python with a bunch of if-else statements and named it an AI application 😂. There was nothing like ChatGPT at that time.

github.com/shricodev/VoiceAI

See how far tech has come in just a few years. That's why there's a saying: "If you miss just a few days or weeks in the tech industry, you miss out everything."

Collapse
 
ori_dcr109 profile image
Oriliana D Cruz

Cool! By the way, you could have actually implemented this in a Python web app, either with Django or Flask then it would be even better.

Collapse
 
shricodev profile image
Shrijal Acharya

This is just a simple demonstration of integrating OpenAI in a Python Application. In future articles, I will try to include it in a functional web app.