Profit Engine — AI-Powered Content Network
Artificial intelligence is no longer science fiction—it's a practical tool you can build yourself. In this comprehensive tutorial, you'll learn how to create a custom AI chatbot using Python and the OpenAI API. Whether you're a developer looking to automate customer support, a hobbyist exploring AI, or a professional wanting to integrate smart conversations into your apps, this guide covers everything from prerequisites to deployment. By the end, you'll have a functional chatbot that responds intelligently to user queries, with tips to customize it for your needs.
Before diving into the code, ensure you have the following tools and accounts ready. This tutorial assumes basic familiarity with Python, but we'll explain each step clearly.
Tip: If you're new to Python, consider setting up a virtual environment to manage dependencies. We'll cover that in Step 1.
First, create a dedicated folder for your chatbot project. Open your terminal and run:
mkdir ai-chatbot cd ai-chatbotNow, create a virtual environment to isolate dependencies:
python -m venv venvActivate it:
venv\Scripts\activatesource venv/bin/activateYou should see (venv) in your terminal prompt, indicating the environment is active. Next, install the required packages:
pip install openai python-dotenvWhy these? The openai package lets us call the API, and python-dotenv helps securely manage your API key. Create a file named .env in your project folder and add your key:
OPENAI_API_KEY=your-api-key-hereReplace your-api-key-here with the actual key. Never commit this file to version control—add .env to your .gitignore.
Create a new Python file, chatbot.py, and open it in your editor. We'll build a simple command-line chatbot that takes user input and returns AI-generated responses.
Start by importing libraries and loading your API key:
<import os from openai import OpenAI from dotenv import load_dotenv load_dotenv() client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))Now, define a function to get a response from OpenAI's GPT model. We'll use gpt-3.5-turbo for cost-effectiveness, but you can swap it for gpt-4 if you have access:
def get_chatbot_response(user_input, conversation_history): messages = [{"role": "system", "content": "You are a helpful assistant."}] for entry in conversation_history: messages.append(entry) messages.append({"role": "user", "content": user_input}) response = client.chat.completions.create( model="gpt-3.5-turbo", messages=messages, max_tokens=150, temperature=0.7 ) return response.choices[0].message.contentExplanation: The conversation_history list stores previous messages to maintain context. The system message sets the bot's persona. max_tokens limits response length, and temperature controls creativity (0 = deterministic, 1 = very creative).
Finally, create the main loop:
def main(): print("AI Chatbot (type 'quit' to exit)") conversation_history = [] while True: user_input = input("You: ") if user_input.lower() in ["quit", "exit"]: break response = get_chatbot_response(user_input, conversation_history) print(f"Bot: {response}") conversation_history.append({"role": "user", "content": user_input}) conversation_history.append({"role": "assistant", "content": response}) if __name__ == "__main__": main()Save the file. Run it with python chatbot.py and test it. Type a question like "What is the capital of France?" and see the response. Type "quit" to exit.
Our basic bot remembers context within a session, but it has a token limit. For longer conversations, implement a sliding window. Modify get_chatbot_response to trim history when it exceeds a threshold:
MAX_HISTORY_TOKENS = 2000 # Adjust based on model limits def trim_history(conversation_history): total_tokens = 0 trimmed = [] for entry in reversed(conversation_history): entry_tokens = len(entry["content"].split()) # Rough estimate if total_tokens + entry_tokens > MAX_HISTORY_TOKENS: break trimmed.insert(0, entry) total_tokens += entry_tokens return trimmedCall trim_history(conversation_history) before building the messages list. This ensures you don't exceed model token limits (e.g., 4096 for gpt-3.5-turbo).
Change the system message to tailor behavior. For example, a customer support bot:
{"role": "system", "content": "You are a friendly customer support agent for a tech company. Answer questions politely and provide step-by-step solutions."}Or a sarcastic bot:
{"role": "system", "content": "You are a witty assistant who answers with dry humor. Be helpful but sarcastic."}Experiment with different system prompts to see how how to guide the AI's tone. You can also add context about your business or app in the system message.
To make your chatbot accessible via a web interface, use Flask. Install Flask:
pip install flaskCreate app.py:
from flask import Flask, request, jsonify from chatbot import get_chatbot_response app = Flask(__name__) @app.route("/chat", methods=["POST"]) def chat(): data = request.json user_input = data.get("message", "") history = data.get("history", []) response = get_chatbot_response(user_input, history) return jsonify({"response": response}) if __name__ == "__main__": app.run(debug=True, port=5000)Run python app.py. Use a tool like Postman or a simple HTML form to send POST requests to http://localhost:5000/chat with JSON body: {"message": "Hello!"}. This is a minimal API—consider adding authentication and error handling for production.