Build a Python AI Chatbot Inspired by Hubspot
If you want to create a simple Python AI chatbot similar to tutorials on Hubspot, you can follow a clear process that takes you from environment setup to a working web app. This guide breaks down each step, from installing dependencies to wiring a browser form to an OpenAI-powered backend.
The tutorial here closely follows the structure of the original walkthrough at Hubspot's Python AI chatbot article, adapted into a practical, step‑by‑step format.
Overview of the Hubspot-Style Chatbot
Before you write any code, it helps to understand the basic architecture used in the Hubspot-style example:
- A Python backend that connects to the OpenAI API.
- A lightweight Flask web server to handle chat requests.
- An HTML page with a text box and chat display area.
- JavaScript in the browser to send the user message to the backend and render the response.
All of these pieces work together to create an interactive experience where visitors can ask questions and receive AI-generated answers in real time.
Prerequisites for a Hubspot-Like Python Chatbot
To follow a tutorial similar to the one on Hubspot, make sure you have the following:
- Python 3.8+ installed on your machine.
- A terminal or command prompt you can use comfortably.
- pip for installing Python packages.
- An OpenAI API key (created from your OpenAI account dashboard).
- A text editor or IDE such as VS Code, PyCharm, or similar.
Once these are ready, you can start building the chatbot project from scratch.
Step 1: Create and Activate Your Project Environment
In the Hubspot-style workflow, the first task is creating an isolated environment so dependencies don't conflict with other projects.
-
Create a project folder, for example:
mkdir python-ai-chatbot cd python-ai-chatbot -
Create a virtual environment:
python -m venv venv -
Activate the environment:
- macOS/Linux:
source venv/bin/activate - Windows (PowerShell):
venvScriptsActivate.ps1
- macOS/Linux:
With the virtual environment running, you can safely install the packages you need for your chatbot.
Step 2: Install Dependencies Used in the Hubspot Tutorial
The core stack in the Hubspot example uses Flask for the web server and the OpenAI client for model calls.
Install the basic requirements:
pip install flask openai python-dotenv
These packages provide:
- Flask: to handle HTTP requests and serve your chat interface.
- openai: to connect to OpenAI models.
- python-dotenv: to load your API key from an environment file.
Step 3: Configure Environment Variables for Your Chatbot
A Hubspot-style tutorial keeps secrets out of code by using environment variables.
-
Create a file named
.envin your project root. -
Add your OpenAI API key:
OPENAI_API_KEY="your_api_key_here" -
Ensure
.envis not committed to version control by listing it in.gitignoreif you use Git.
Loading the key from .env lets you change credentials without editing source files.
Step 4: Build the Flask Backend Like the Hubspot Example
The backend is the core of the Hubspot-inspired chatbot. It receives a message, sends it to OpenAI, and returns the answer as JSON.
Create a file named app.py and add starter code based on the style of the Hubspot article:
import os
from flask import Flask, request, jsonify, render_template
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
app = Flask(__name__)
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
@app.route("/")
def index():
return render_template("index.html")
@app.route("/chat", methods=["POST"])
def chat():
data = request.get_json()
user_message = data.get("message", "")
if not user_message:
return jsonify({"error": "Empty message"}), 400
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": user_message},
],
temperature=0.7,
)
answer = response.choices[0].message["content"]
return jsonify({"reply": answer})
if __name__ == "__main__":
app.run(debug=True)
This logic follows the same pattern highlighted in the Hubspot article: receive user input, forward it to the model, and send the result back to the browser.
Step 5: Create the HTML Interface for Your Hubspot-Style Chat
The front-end template mimics the simple conversational layout described in Hubspot tutorials. It only needs a few key elements:
- A container to show conversation history.
- An input field for the current message.
- A button (or Enter key handler) to submit messages.
Create a folder named templates and inside it add index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Python AI Chatbot</title>
<style>
body { font-family: Arial, sans-serif; max-width: 700px; margin: 0 auto; padding: 1rem; }
#chat-box { border: 1px solid #ddd; padding: 1rem; height: 400px; overflow-y: auto; margin-bottom: 1rem; }
.message { margin-bottom: 0.75rem; }
.user { font-weight: bold; }
.assistant { color: #333; }
#input-row { display: flex; gap: 0.5rem; }
#message-input { flex: 1; padding: 0.5rem; }
</style>
</head>
<body>
<h1>Python AI Chatbot</h1>
<div id="chat-box"></div>
<div id="input-row">
<input id="message-input" type="text" placeholder="Type your message..." />
<button id="send-btn">Send</button>
</div>
<script>
const chatBox = document.getElementById('chat-box');
const input = document.getElementById('message-input');
const sendBtn = document.getElementById('send-btn');
function appendMessage(role, text) {
const div = document.createElement('div');
div.classList.add('message');
div.innerHTML = role === 'user'
? `<span class="user">You:</span> ${text}`
: `<span class="assistant">Bot:</span> ${text}`;
chatBox.appendChild(div);
chatBox.scrollTop = chatBox.scrollHeight;
}
async function sendMessage() {
const text = input.value.trim();
if (!text) return;
appendMessage('user', text);
input.value = '';
try {
const res = await fetch('/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: text }),
});
const data = await res.json();
if (data.reply) {
appendMessage('assistant', data.reply);
} else if (data.error) {
appendMessage('assistant', `Error: ${data.error}`);
}
} catch (err) {
appendMessage('assistant', 'Network error. Please try again.');
}
}
sendBtn.addEventListener('click', sendMessage);
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
sendMessage();
}
});
</script>
</body>
</html>
This minimal interface echoes the user experience described in the Hubspot article: type your message, click send, and the chatbot responds in the same window.
Step 6: Run and Test Your Chatbot Locally
With the Flask backend and HTML template ready, you can launch the server.
-
Ensure your virtual environment is active.
-
Run the application:
python app.py -
Open your browser and navigate to
http://127.0.0.1:5000. -
Type a message into the input box and check that the chatbot sends back a response.
If something does not work, compare your files to the examples in the original Hubspot chatbot walkthrough to spot syntax or configuration differences.
Step 7: Improve Your Hubspot-Inspired Chatbot
Once the basic version runs, there are several ways to refine it beyond the starting point offered by Hubspot tutorials:
Enhance Conversation Flow in Your Hubspot-Style Bot
- Maintain full conversation history in memory instead of sending only the latest message.
- Adjust the system prompt to specialize the assistant for support, sales, or documentation search.
- Limit maximum context length so performance stays smooth.
Add UX Features Similar to Hubspot Interfaces
- Show a loading indicator while waiting for the model.
- Use a more polished design with CSS frameworks such as Tailwind or Bootstrap.
- Support keyboard shortcuts for faster chatting.
Deploy the Chatbot Beyond Localhost
- Containerize the Flask app with Docker and deploy it on a cloud platform.
- Serve the Python chatbot behind a production web server like Nginx.
- Add authentication if you expose it to external users.
Next Steps and Additional Resources Around Hubspot Chatbots
If you want to align your implementation with marketing or CRM workflows, you can explore how automation experts extend a basic Python chatbot into a full customer experience. Agencies focused on AI, automation, and integrations, such as Consultevo, often connect conversational assistants to CRMs, analytics, and knowledge bases.
For deeper technical details and updated screenshots, consult the original guide that inspired this tutorial on the Hubspot blog, and then iterate on your own version with more advanced flows, models, and UI refinements.
Need Help With Hubspot?
If you want expert help building, automating, or scaling your Hubspot , work with ConsultEvo, a team who has a decade of Hubspot experience.
“`
