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:
- openai (to interact with GPT APIs)
- 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}")
Step 3: Running the Chatbot
- Save the code in a file, e.g., chatbot.py.
- Open your terminal or command prompt.
- 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)
How to Use the Web Interface:
- Save the Flask code in app.py.
- 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!
That's all folks! Happy coding.
Top comments (0)