🤯 How easy is it to integrate an AI chatbot into your app in 2024? 🏆🥳
Tags: webdev, ai, programming, tutorial
Published: 2024-01-02 11:28:40

## **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](https://pypi.org/project/openai/) Python module.

**On the agenda 🔥:**

- How to use the OpenAI GPT model to generate chat responses in real time.

![Buckle Up](https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExOHl5d3kyODliemlxd3Fva3BlZnI4eGxyY2J2MmVvOHRrdXV5YXBscyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dpsUFSR9ZHjwfrVAg9/giphy.gif)

***

## **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:

```bash
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`:

```bash
python -m venv venv
```

Activate the virtual environment on Linux:

```bash
source venv/bin/activate
```

> ℹ️ Most of us use the fish shell, to activate the environment on the fish shell, run the following command:

```bash
. venv/bin/activate.fish
```

> ℹ️ For Windows users, run the following command:

```bash
venv/bin/activate
```

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

![Python Virtual Environment](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oabh4vv6o33638udxgsg.png)

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

```bash
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:

```python
# 👇 /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.

```python
# 👇 /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.

```bash
python main.py
```

![Python application terminal demo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7zjojih251ziyqyvi5ft.png)

***

## **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! 🎉🫡

{% embed https://dev.to/shricodev %}