ChatGPT still leads the chatbot market but its dominance is slipping as Google's Gemini gains ground
Back to Tutorials
aiTutorialbeginner

ChatGPT still leads the chatbot market but its dominance is slipping as Google's Gemini gains ground

March 12, 202616 views4 min read

Learn how to create a simple chatbot using OpenAI's API that communicates with AI models like ChatGPT. This beginner-friendly tutorial teaches you to build a conversational interface with Python.

Introduction

In this tutorial, you'll learn how to interact with large language models (LLMs) using Python, similar to how ChatGPT and Google's Gemini operate. You'll build a simple chatbot interface that can communicate with these AI systems. This tutorial focuses on using the OpenAI API, which powers ChatGPT, and demonstrates the core concepts behind modern chatbots.

Prerequisites

  • A basic understanding of Python programming
  • An OpenAI API key (free to get at platform.openai.com)
  • Python 3.6 or higher installed on your computer
  • Basic knowledge of command line operations

Step-by-Step Instructions

1. Setting Up Your Python Environment

1.1 Install Required Packages

First, you'll need to install the OpenAI Python library. Open your terminal or command prompt and run:

pip install openai

This installs the official Python client for OpenAI's API, which makes it easy to communicate with models like GPT-3.5 and GPT-4.

1.2 Create Your Python Script

Create a new file called chatbot.py in your preferred code editor. This will be your main program file.

2. Configuring Your API Key

2.1 Get Your API Key

Visit https://platform.openai.com/ and sign in to your account. Navigate to the "API Keys" section and click "Create new secret key". Copy this key and keep it secure.

2.2 Set Up Your Environment Variables

It's best practice to store your API key in environment variables rather than hardcoding it in your script. On Windows, open Command Prompt and run:

setx OPENAI_API_KEY "your_api_key_here"

On macOS or Linux, run:

export OPENAI_API_KEY="your_api_key_here"

Replace "your_api_key_here" with your actual API key.

3. Writing Your Chatbot Code

3.1 Import Libraries and Initialize the Client

Open your chatbot.py file and add this code:

import os
from openai import OpenAI

# Initialize the OpenAI client
client = OpenAI(
    api_key=os.getenv("OPENAI_API_KEY"),
)

This creates a client object that will communicate with OpenAI's API using your key.

3.2 Create a Function to Generate Responses

Add this function to your script:

def get_response(prompt):
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": prompt}
        ],
        max_tokens=150,
        temperature=0.7
    )
    return response.choices[0].message.content

This function sends a message to the GPT-3.5 model and returns the AI's response. The system message sets the AI's personality, and the user message is what you're asking it.

3.3 Create a Simple Chat Loop

Add this code to create a conversation interface:

def chatbot_interface():
    print("Chatbot initialized! Type 'quit' to exit.")
    while True:
        user_input = input("You: ")
        if user_input.lower() in ["quit", "exit"]:
            print("Goodbye!")
            break
        
        response = get_response(user_input)
        print(f"Bot: {response}")

This loop allows you to have a conversation with your chatbot. It keeps asking for input until you type 'quit' or 'exit'.

3.4 Run the Chatbot

Add this final line to your script to start the chatbot:

if __name__ == "__main__":
    chatbot_interface()

This ensures the chatbot starts only when you run the script directly.

4. Testing Your Chatbot

4.1 Run the Script

In your terminal, navigate to the folder containing chatbot.py and run:

python chatbot.py

You should see the message "Chatbot initialized! Type 'quit' to exit."

4.2 Have a Conversation

Try asking simple questions like:

  • "What is Python?"
  • "Tell me a joke"
  • "How do I install packages in Python?"

Notice how the chatbot responds to your questions using AI technology similar to what powers ChatGPT.

Summary

In this tutorial, you've built a basic chatbot that communicates with OpenAI's GPT models. You learned how to:

  • Install and use the OpenAI Python library
  • Set up your API key securely
  • Create a chat interface that sends messages to an AI model
  • Receive and display responses from the AI

This demonstrates the fundamental technology behind modern chatbots like ChatGPT and Gemini. As these systems evolve, they're becoming more accessible through simple APIs, allowing developers to integrate AI into their applications.

Source: The Decoder

Related Articles