Artificial intelligence applications are becoming increasingly common. In this article, we will explain step-by-step how to develop a simple chatbot using Python and OpenAI’s GPT-3.5 Turbo model.
1. Install the OpenAI Python Library
First, you need to install the OpenAI Python SDK on your system. Run the following command in your terminal or command prompt:
pip install openai
It is recommended to use Python version 3.8 or above.
2. Create an OpenAI Account and Obtain an API Key
You need to register on the OpenAI platform and generate your API key. Follow these steps:
- Sign up via the OpenAI Sign-up Page.
- After logging in, go to the API Keys page.
- Click the “Create new secret key” button to generate a new API key.
- Store the generated key securely.
Note: Never share your API key with others.
3. Set the API Key Securely as an Environment Variable
For security reasons, avoid hardcoding the API key in your code. Instead, set it as an environment variable.
Windows (PowerShell):
setx OPENAI_API_KEY "sk-xxxxxxxxxxxxxxxxxxxx"
Mac / Linux:
export OPENAI_API_KEY="sk-xxxxxxxxxxxxxxxxxxxx"
You may need to restart your terminal after setting the environment variable.
4. Writing the Python Chatbot Code
The following Python script communicates with the OpenAI API and responds to user input, forming a basic chatbot:
import os
import openai
# Retrieve API key from environment variable
openai.api_key = os.getenv("OPENAI_API_KEY")
if not openai.api_key:
raise RuntimeError("OPENAI_API_KEY not found. Please set it as an environment variable.")
def chat_with_gpt(prompt, model="gpt-3.5-turbo"):
response = openai.ChatCompletion.create(
model=model,
messages=[{"role": "user", "content": prompt}],
max_tokens=512,
temperature=0.7
)
return response.choices[0].message.content.strip()
if __name__ == "__main__":
print("Chatbot started. Type 'quit', 'exit' or 'bye' to stop.")
while True:
user_input = input("You: ").strip()
if user_input.lower() in ("quit", "exit", "bye"):
print("Exiting program.")
break
try:
answer = chat_with_gpt(user_input)
print("Bot:", answer)
except Exception as e:
print("An error occurred:", e)
5. Running the Chatbot
After saving the Python file, run it in your terminal with the following command:
python chatbot.py
The program will prompt for input, send it to the OpenAI model, and display the response.
Recommendations and Advanced Tips
- Conversation History: To enable more natural conversations, maintain the dialogue history by appending previous messages to the
messages
list. - Model Parameters: Adjust parameters such as
temperature
andmax_tokens
to control response creativity and length. - System Messages: Define initial system messages to guide the model’s behavior.
- Error Handling: Implement error handling to manage API call failures and rate limits effectively.
With this guide, you have learned how to build a basic chatbot using Python and the OpenAI API. You can further develop the code to suit your needs or incorporate it into larger projects.