DEV Community

Anuj Pathak
Anuj Pathak

Posted on

How to Build a Simple AI Chatbot with GPT APIs

Building an AI chatbot has never been easier, thanks to OpenAI’s powerful GPT APIs. In this guide, we’ll walk through creating a basic chatbot using the OpenAI GPT API. By the end, you’ll have a functional chatbot capable of answering questions or holding conversations in a natural language.

What You'll Need

API Access:
Sign up for OpenAI and get your API key from the OpenAI Developer Platform.

Programming Language:
We’ll use Python for this tutorial.

Environment Setup:
Install Python on your system, and ensure you have the following libraries:

  1. openai (to interact with GPT APIs)
  2. flask (optional, for building a web interface)

Step 1: Setting Up Your Python Environment

Install Required Libraries

Run the following commands to install the necessary Python libraries:

pip install openai flask

Step 2: Writing the Chatbot Code

Here’s the code for a simple GPT-powered chatbot:

Code Example

import openai

# Set up your API key
openai.api_key = "your_openai_api_key"

def chatbot(prompt):
    try:
        # Call the GPT API
        response = openai.Completion.create(
            engine="text-davinci-003",  # You can also use 'gpt-3.5-turbo' or other models
            prompt=prompt,
            max_tokens=150,
            temperature=0.7,
        )
        # Extract and return the text
        return response.choices[0].text.strip()
    except Exception as e:
        return f"Error: {str(e)}"

if __name__ == "__main__":
    print("AI Chatbot: Type 'exit' to quit.")
    while True:
        user_input = input("You: ")
        if user_input.lower() == "exit":
            print("Goodbye!")
            break
        reply = chatbot(user_input)
        print(f"Bot: {reply}")

Enter fullscreen mode Exit fullscreen mode

Step 3: Running the Chatbot

  1. Save the code in a file, e.g., chatbot.py.
  2. Open your terminal or command prompt.
  3. Run the chatbot:

python chatbot.py

Create a Web Interface(Optional)

Using Flask, you can make your chatbot accessible through a web page. Here’s an example:

Flask Integration Code

from flask import Flask, request, jsonify
import openai

app = Flask(__name__)
openai.api_key = "your_openai_api_key"

@app.route("/chat", methods=["POST"])
def chat():
    data = request.json
    user_message = data.get("message", "")
    response = openai.Completion.create(
        engine="text-davinci-003",
        prompt=user_message,
        max_tokens=150,
        temperature=0.7,
    )
    return jsonify({"reply": response.choices[0].text.strip()})

if __name__ == "__main__":
    app.run(debug=True)

Enter fullscreen mode Exit fullscreen mode

How to Use the Web Interface:

  1. Save the Flask code in app.py.
  2. Run it

python app.py

3.Send a POST request with a JSON payload to *http://127.0.0.1:5000/chat * using tools like Postman or a frontend app:

{
"message": "Hello, how are you?"
}

You’ll get a response like:

{
"reply": "I'm just a bot, but I'm doing well! How can I assist you?"
}

Sample Output

Terminal Interaction:

AI Chatbot: Type 'exit' to quit.
You: What is the capital of France?
Bot: The capital of France is Paris.
You: Who discovered gravity?
Bot: Sir Isaac Newton is credited with the discovery of gravity.
You: exit
Goodbye!
Enter fullscreen mode Exit fullscreen mode

That's all folks! Happy coding.

Top comments (0)