If you’re running an e-commerce store, you’re familiar with the countless questions customers have about products. Today, we’ll build a chatbot that can provide product details based on a user’s queries. We’ll be using Python along with the OpenAI API.
1. Setting up the Environment
Before diving into the code, ensure you have the prerequisites:
- Install Python from python.org.
- Set up a virtual environment. This isn’t mandatory but can be helpful:
python -m venv myenv
source myenv/bin/activate # On Windows use `myenv\Scripts\activate`
Install the necessary packages:
pip install openai
2. Preparing the Product Data
Our bot will fetch product details from a JSON file. Let’s structure our data:
[
{
"product": "Smart TV",
"details": "42-inch 4K UHD",
"price": "$500",
"delivery_time": "5-7 days",
"estimated_delivery": "7th Oct",
"location": "New York",
"buy_link": "http://example.com/smarttv"
},
// ... add more products as you like
]
3. Crafting the Chatbot Logic
Here’s a breakdown of the Python code for our chatbot:
a) Initialize OpenAI and Load the Data
import openai
import json
# Initialize OpenAI
openai.api_key = 'YOUR_API_KEY'
with open('product_data.json', 'r') as file:
products = json.load(file)
b) Querying OpenAI and Getting Product Details
We define a function to get details of a specified product:
def get_product_detail(product_name):
for product in products:
if product_name.lower() in product["product"].lower():
return product
return None
c) Initiating the Chat
The chat function will guide the interaction:
def chat():
system_prompt = "Welcome! I'm here to help you find products. What product are you interested in?"
print(system_prompt)
product_name = input("You: ")
product_detail = get_product_detail(product_name)
if not product_detail:
print("Sorry, I couldn't find that product.")
return
details_to_ask = ["details", "price", "delivery_time", "estimated_delivery", "location"]
for detail in details_to_ask:
question = f"Would you like to know the {detail.replace('_', ' ')} of {product_name}?"
print(question)
user_response = input("You: ")
if "yes" in user_response.lower():
print(f"The {detail.replace('_', ' ')} of {product_name} is {product_detail[detail]}.")
print(f"Would you like to buy the {product_name}? Here's the link: {product_detail['buy_link']}")
chat()
4. Making the Code Production-Ready
Consider these steps for a robust chatbot:
- Diversify your product JSON data.
- Handle errors for product unavailability or API issues.
- Add user confirmation before showing purchase links.
- For a UI-based experience, integrate with Flask or Django.
- Ensure the OpenAI API key is stored securely.
- Implement logging for troubleshooting.
- Conduct thorough testing with diverse inputs.
In Conclusion
The above implementation provides a basic yet comprehensive chatbot for querying product details and guiding potential customers. Remember to conduct robust testing before taking the chatbot live.
Happy coding and selling!