DEV Community

Cover image for Create a Python GPT chatbot
Muha-mmed
Muha-mmed

Posted on

Create a Python GPT chatbot

Let’s create a simple Python script that uses GPT AI to give the user a response based on their input.

Step 1: Install the Required Package

First, make sure you have Python installed on your computer.

Then, run this command in your terminal:

pip install openai
Enter fullscreen mode Exit fullscreen mode

Step 2: Get an API Key

Visit the OpenAI website, create an account, and request an API key.

Step 3: Write the Script

Now, let’s move on to writing the script.

import openai

openai.api_key = "your_api_key"

def chat_gpt(user_input):
    try:
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": user_input}]
        )
        return response.choices[0].message.content.strip()
    except Exception as e:
        return f"An error occurred: {str(e)}"

if __name__ == "__main__":
    while True:
        user_input = input("You: ")
        if user_input.lower() in ["quit", "exit", "bye"]:
            break
        response = chat_gpt(user_input)
        print("Chatbot:", response)
Enter fullscreen mode Exit fullscreen mode

Step 4: Run the Script

Save the file as main.py, then run it with:

python main.py
Enter fullscreen mode Exit fullscreen mode

Explaining the Code
• The chat_gpt() function allows the user to input a question. It sends the message to the GPT model and returns a response or an error message.
• The name == "main" block makes the script run in a loop. If the user types “bye”, “exit”, or “quit”, the program will stop. Otherwise, it sends the user’s input to GPT and prints the response.

Top comments (0)