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
Feature | Rule-Based Chatbot | GPT-3 Chatbot |
---|---|---|
Response Type | Predefined replies | AI-generated, dynamic responses |
Flexibility | Limited to patterns | Understands context, grammar, and tone |
Learning Ability | No learning | Can generate varied responses |
Use Cases | FAQs, customer service | Chat 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
Feature | Rule-Based Chatbot | GPT-3 Chatbot |
---|---|---|
Response Type | Predefined | AI-generated |
Flexibility | Limited | Highly flexible |
Context Awareness | No | Yes |
Conversational Ability | Basic | Advanced |
Learning Ability | No | Continuous learning |
Setup Complexity | Low | Medium (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