;
Artificial intelligence March 23 ,2025

AI-Powered Chatbot Using GPT-3 in Python

In this tutorial, we'll build an AI-powered chatbot using OpenAI's GPT-3.5-turbo. Unlike rule-based chatbots, GPT-3 understands natural language and provides human-like responses by leveraging deep learning.

1. Install Dependencies

To use GPT-3, install the OpenAI Python library:

pip install openai

Additionally, make sure you have an OpenAI API key. You can get one by signing up at OpenAI.

2. Understanding How GPT-3 Chatbots Work

How GPT-3 Chatbot is Different from Rule-Based Bots

FeatureRule-Based ChatbotGPT-3 Chatbot
Response TypePredefined repliesAI-generated, dynamic responses
FlexibilityLimited to patternsUnderstands context, grammar, and tone
Learning AbilityNo learningCan generate varied responses
Use CasesFAQs, customer serviceChat assistants, creative writing

3. Python Code for AI Chatbot Using GPT-3

import openai

# Function to communicate with GPT-3
def chat_with_gpt(prompt):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": prompt}]
    )
    return response["choices"][0]["message"]["content"]

print("Chatbot: Hello! Type 'bye' to exit.")
while True:
    user_input = input("You: ")
    if user_input.lower() == "bye":
        print("Chatbot: Goodbye!")
        break
    response = chat_with_gpt(user_input)
    print("Chatbot:", response)

4. Detailed Explanation of the Code

A. Importing the Required Library

import openai
  • The openai library allows us to communicate with the GPT-3 API.

B. Defining the Function to Send Requests to GPT-3

def chat_with_gpt(prompt):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": prompt}]
    )
    return response["choices"][0]["message"]["content"]
  • The openai.ChatCompletion.create() function sends the user’s message to GPT-3.
  • We specify:
    • model="gpt-3.5-turbo" → Uses OpenAI's conversational AI model.
    • messages=[{"role": "user", "content": prompt}] → Sends the user input to GPT-3.
  • The response is extracted and returned.

C. Implementing a ChatBot

print("Chatbot: Hello! Type 'bye' to exit.")
while True:
    user_input = input("You: ")
    if user_input.lower() == "bye":
        print("Chatbot: Goodbye!")
        break
    response = chat_with_gpt(user_input)
    print("Chatbot:", response)
  • The chatbot runs continuously until the user types "bye".
  • It sends the user input to GPT-3 and prints the response.

5. Running the Chatbot

When you execute the script, the chatbot will interact like this:

Chatbot: Hello! Type 'bye' to exit.
You: Hi
Chatbot: Hello! How can I assist you today?
You: What is the capital of France?
Chatbot: The capital of France is Paris.
You: Can you tell me a joke?
Chatbot: Sure! Why don’t skeletons fight each other? Because they don’t have the guts!
You: bye
Chatbot: Goodbye!

6. Enhancing the Chatbot

A. Remembering Context in Conversations

To keep track of previous messages, we can modify the chatbot to use a list of messages:

import openai

def chat_with_gpt(conversation_history):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=conversation_history
    )
    return response["choices"][0]["message"]["content"]

print("Chatbot: Hello! Type 'bye' to exit.")
conversation_history = [{"role": "system", "content": "You are a helpful chatbot."}]

while True:
    user_input = input("You: ")
    if user_input.lower() == "bye":
        print("Chatbot: Goodbye!")
        break
    conversation_history.append({"role": "user", "content": user_input})
    response = chat_with_gpt(conversation_history)
    conversation_history.append({"role": "assistant", "content": response})
    print("Chatbot:", response)

Now, the chatbot remembers past interactions.

B. Customizing GPT-3’s Personality

You can customize GPT-3’s behavior by modifying the system message:

conversation_history = [
    {"role": "system", "content": "You are a funny chatbot who loves making jokes."}
]

This makes the chatbot respond humorously.

C. Adding an API Key Securely

Instead of storing the API key in code, store it as an environment variable:

import openai
import os

openai.api_key = os.getenv("OPENAI_API_KEY")

This prevents security risks.

7. Comparison: GPT-3 vs Rule-Based Chatbots

FeatureRule-Based ChatbotGPT-3 Chatbot
Response TypePredefinedAI-generated
FlexibilityLimitedHighly flexible
Context AwarenessNoYes
Conversational AbilityBasicAdvanced
Learning AbilityNoContinuous learning
Setup ComplexityLowMedium (requires API key)

8. Use Cases for AI Chatbots

 Customer Support – Provide instant responses
 Virtual Assistants – Answer general knowledge questions
 E-learning – Help students with programming & subjects
 Entertainment – Tell jokes, generate stories

9. Conclusion

With GPT-3, we built an intelligent chatbot capable of understanding natural conversations. Unlike rule-based chatbots, GPT-3 can adapt, generate creative responses, and remember past interactions.

Next Steps:
 Improve responses using fine-tuning
 Deploy it as a web-based chatbot using Flask or FastAPI
 Connect it to WhatsApp, Telegram, or Discord

 

Purnima
0

You must logged in to post comments.

Related Blogs

What is Ar...
Artificial intelligence March 03 ,2025

What is Artificial I...

History an...
Artificial intelligence March 03 ,2025

History and Evolutio...

Importance...
Artificial intelligence March 03 ,2025

Importance and Appli...

Narrow AI,...
Artificial intelligence March 03 ,2025

Narrow AI, General A...

AI vs Mach...
Artificial intelligence March 03 ,2025

AI vs Machine Learni...

Linear Alg...
Artificial intelligence March 03 ,2025

Linear Algebra Basic...

Calculus f...
Artificial intelligence March 03 ,2025

Calculus for AI

Probabilit...
Artificial intelligence March 03 ,2025

Probability and Stat...

Probabilit...
Artificial intelligence March 03 ,2025

Probability Distribu...

Graph Theo...
Artificial intelligence March 03 ,2025

Graph Theory and AI

What is NL...
Artificial intelligence March 03 ,2025

What is NLP

Preprocess...
Artificial intelligence March 03 ,2025

Preprocessing Text D...

Sentiment...
Artificial intelligence March 03 ,2025

Sentiment Analysis a...

Word Embed...
Artificial intelligence March 03 ,2025

Word Embeddings (Wor...

Transforme...
Artificial intelligence March 03 ,2025

Transformer-based Mo...

Building C...
Artificial intelligence March 03 ,2025

Building Chatbots wi...

Basics of...
Artificial intelligence March 03 ,2025

Basics of Computer V...

Image Prep...
Artificial intelligence March 03 ,2025

Image Preprocessing...

Object Det...
Artificial intelligence March 03 ,2025

Object Detection and...

Face Recog...
Artificial intelligence March 03 ,2025

Face Recognition and...

Applicatio...
Artificial intelligence March 03 ,2025

Applications of Comp...

Implementi...
Artificial intelligence March 03 ,2025

Implementing a Basic...

Implementa...
Artificial intelligence March 03 ,2025

Implementation of Ob...

Implementa...
Artificial intelligence March 03 ,2025

Implementation of Ob...

Implementa...
Artificial intelligence March 03 ,2025

Implementation of Fa...

Deep Reinf...
Artificial intelligence March 03 ,2025

Deep Reinforcement L...

Deep Reinf...
Artificial intelligence March 03 ,2025

Deep Reinforcement L...

Deep Reinf...
Artificial intelligence March 03 ,2025

Deep Reinforcement L...

Introducti...
Artificial intelligence March 03 ,2025

Introduction to Popu...

Introducti...
Artificial intelligence March 03 ,2025

Introduction to Popu...

Introducti...
Artificial intelligence March 03 ,2025

Introduction to Popu...

Introducti...
Artificial intelligence March 03 ,2025

Introduction to Popu...

Tools for...
Artificial intelligence March 03 ,2025

Tools for Data Handl...

Tool for D...
Artificial intelligence March 03 ,2025

Tool for Data Handli...

Cloud Plat...
Artificial intelligence April 04 ,2025

Cloud Platforms for...

Deep Dive...
Artificial intelligence April 04 ,2025

Deep Dive into AWS S...

Cloud Plat...
Artificial intelligence April 04 ,2025

Cloud Platforms for...

Cloud Plat...
Artificial intelligence April 04 ,2025

Cloud Platforms for...

Visualizat...
Artificial intelligence April 04 ,2025

Visualization Tools...

Data Clean...
Artificial intelligence April 04 ,2025

Data Cleaning and Pr...

Explorator...
Artificial intelligence April 04 ,2025

Exploratory Data Ana...

Explorator...
Artificial intelligence April 04 ,2025

Exploratory Data Ana...

Feature En...
Artificial intelligence April 04 ,2025

Feature Engineering...

Data Visua...
Artificial intelligence April 04 ,2025

Data Visualization w...

Working wi...
Artificial intelligence April 04 ,2025

Working with Large D...

Understand...
Artificial intelligence April 04 ,2025

Understanding Bias i...

Ethics in...
Artificial intelligence April 04 ,2025

Ethics in AI Develop...

Fairness i...
Artificial intelligence April 04 ,2025

Fairness in Machine...

The Role o...
Artificial intelligence April 04 ,2025

The Role of Regulati...

Responsibl...
Artificial intelligence April 04 ,2025

Responsible AI Pract...

Artificial...
Artificial intelligence April 04 ,2025

Artificial Intellige...

AI in Fina...
Artificial intelligence April 04 ,2025

AI in Finance and Ba...

AI in Auto...
Artificial intelligence April 04 ,2025

AI in Autonomous Veh...

AI in Gami...
Artificial intelligence April 04 ,2025

AI in Gaming and Ent...

AI in Soci...
Artificial intelligence April 04 ,2025

AI in Social Media a...

Building a...
Artificial intelligence April 04 ,2025

Building a Spam Emai...

Creating a...
Artificial intelligence April 04 ,2025

Creating an Image Cl...

Developing...
Artificial intelligence April 04 ,2025

Developing a Sentime...

Implementi...
Artificial intelligence April 04 ,2025

Implementing a Recom...

Generative...
Artificial intelligence April 04 ,2025

Generative AI: An In...

Explainabl...
Artificial intelligence April 04 ,2025

Explainable AI (XAI)

AI for Edg...
Artificial intelligence April 04 ,2025

AI for Edge Devices...

Quantum Co...
Artificial intelligence April 04 ,2025

Quantum Computing an...

AI for Tim...
Artificial intelligence April 04 ,2025

AI for Time Series F...

Emerging T...
Artificial intelligence May 05 ,2025

Emerging Trends in A...

AI and the...
Artificial intelligence May 05 ,2025

AI and the Job Marke...

The Role o...
Artificial intelligence May 05 ,2025

The Role of AI in Cl...

AI Researc...
Artificial intelligence May 05 ,2025

AI Research Frontier...

Preparing...
Artificial intelligence May 05 ,2025

Preparing for an AI-...

4 Popular...
Artificial intelligence May 05 ,2025

4 Popular AI Certifi...

Building a...
Artificial intelligence May 05 ,2025

Building an AI Portf...

How to Pre...
Artificial intelligence May 05 ,2025

How to Prepare for A...

AI Career...
Artificial intelligence May 05 ,2025

AI Career Opportunit...

Staying Up...
Artificial intelligence May 05 ,2025

Staying Updated in A...

Part 1-  T...
Artificial intelligence May 05 ,2025

Part 1- Tools for T...

Implementi...
Artificial intelligence May 05 ,2025

Implementing ChatGPT...

Part 2-  T...
Artificial intelligence May 05 ,2025

Part 2- Tools for T...

Part 1- To...
Artificial intelligence May 05 ,2025

Part 1- Tools for Te...

Technical...
Artificial intelligence May 05 ,2025

Technical Implementa...

Part 2- To...
Artificial intelligence May 05 ,2025

Part 2- Tools for Te...

Part 1- To...
Artificial intelligence May 05 ,2025

Part 1- Tools for Te...

Step-by-St...
Artificial intelligence May 05 ,2025

Step-by-Step Impleme...

Part 2 - T...
Artificial intelligence May 05 ,2025

Part 2 - Tools for T...

Part 4- To...
Artificial intelligence May 05 ,2025

Part 4- Tools for Te...

Part 1- To...
Artificial intelligence May 05 ,2025

Part 1- Tools for Te...

Part 2- To...
Artificial intelligence May 05 ,2025

Part 2- Tools for Te...

Part 3- To...
Artificial intelligence May 05 ,2025

Part 3- Tools for Te...

Step-by-St...
Artificial intelligence May 05 ,2025

Step-by-Step Impleme...

Part 1- To...
Artificial intelligence June 06 ,2025

Part 1- Tools for Im...

Implementa...
Artificial intelligence June 06 ,2025

Implementation of D...

Part 2- To...
Artificial intelligence June 06 ,2025

Part 2- Tools for Im...

Part 1- To...
Artificial intelligence June 06 ,2025

Part 1- Tools for Im...

Implementa...
Artificial intelligence June 06 ,2025

Implementation of Ru...

Part 1- To...
Artificial intelligence June 06 ,2025

Part 1- Tools for Im...

Part 2- To...
Artificial intelligence June 06 ,2025

Part 2- Tools for Im...

Step-by-St...
Artificial intelligence June 06 ,2025

Step-by-Step Impleme...

Part 1-Too...
Artificial intelligence June 06 ,2025

Part 1-Tools for Ima...

Part 2- To...
Artificial intelligence June 06 ,2025

Part 2- Tools for Im...

Implementa...
Artificial intelligence June 06 ,2025

Implementation of Pi...

Get In Touch

123 Street, New York, USA

+012 345 67890

techiefreak87@gmail.com

© Design & Developed by HW Infotech