November 21, 2024
Perplexity is, historically speaking, one of the "standard" evaluation metrics for language models. And while…
Introduction
I. Prompting for Developers: A Guideline
II. Building a Shopbot using OpenAI and CometLLM
III. Reference
Conclusion
OpenAI makes it easier than ever to create chatbots for your e-commerce business, eliminating the need for complex deep learning algorithms. Discover simple and effective approaches to increase customer engagement and optimize the online shopping experience. This step-by-step tutorial will walk you through the key components and make it easy to bring your own AI-powered ShopBot to life. Easily transform your e-commerce platform into an interactive, customer-centric shopping destination.
💡I write about Machine Learning on Medium || Github || Kaggle || Linkedin. 🔔 Follow “Nhi Yen” for future updates!
👉 Get UNLIMITED access to every story on Medium with just $1/week — HERE
“‘xxx’”
), triple backticks (```
), triple dashes ( — -
), angle brackets (< >
), and XML tags. These act as navigational aids, precisely guiding the model through the various components of the message.Now, considering the concept of complex indicators, these principles can be applied to indicators that cover at least 3 of the following parameters:
Example:
You are a travel assistant.
Please plan a week-long itinerary for a solo traveler visiting Paris.
The traveler is interested in art, history, and local cuisine. They prefer walking and public transportation.
Follow the steps below:
- Provide a list of must-visit art museums and historical sites.
- Suggest walking routes that connect these attractions efficiently.
- Recommend local restaurants for each day, considering the traveler's preference for diverse cuisine.
Present the itinerary in a clear and organized document, with each day's plan distinctively outlined.
Keep the budget moderate, and consider any current travel restrictions or events in Paris.
Create an engaging and culturally rich itinerary that balances art, history, and local culinary experiences for the solo traveler.
Want to learn how to build modern software with LLMs using the newest tools and techniques in the field? Check out this free LLMOps course from industry expert Elvis Saravia of DAIR.AI!
Before we dive into the code, let’s understand the main components and features of a chatbot. This chatbot, called ShopBot, helps customers find products, provides information, and guides them through the checkout process. It is friendly and helpful and can recommend products based on customer preferences.
👉 Feel free to check out this GitHub repository as we move forward in the process.
First, we’ll use Github Codespace and Python in conjunction with the OpenAI GPT-3.5 Turbo model for natural language processing. Make sure you have the required Python packages installed and obtain your OpenAI API and Comet API keys. (Reference: OpenAI Help Center — Where can I find my API key?; CometLLM — Obtaining your API key)
The provided code snippet initializes the required components.
import os
from openai import OpenAI
import comet_llm
from IPython.display import display
import ipywidgets as widgets
import time
import dotenv
# Input API keys
MY_OPENAI_KEY = os.getenv('MY_OPENAI_KEY')
MY_COMET_KEY = os.getenv('MY_COMET_KEY')
comet_llm.init(project="ecom_shopbot_openai",
api_key=MY_COMET_KEY)
The e-commerce chatbot needs information about the products available in your store. Product list includes details such as name, price, available sizes, colors, etc. This information is stored in a structured format, making it easier for chatbots to provide accurate details to customers.
product_list = '''
# Fashion Shop Product List
## Women's Clothing:
- T-shirt
- Price: $20
- Available Sizes: Small, Medium, Large, XL
- Available Colors: Red, White, Black, Gray, Navy
# ... (Other product categories and details)
'''
This step allows you to enter the product list for your store. Keep in mind that the more complex your product list, the more detailed its context
needs to be so that the generative AI can clearly understand its requirements.
context = [{'role': 'system',
'content': f"""
You are ShopBot, an AI assistant for my online fashion shop - Nhi Yen.
Your role is to assist customers in browsing products, providing information, and guiding them through the checkout process.
Be friendly and helpful in your interactions.
We offer a variety of products across categories such as Women's Clothing, Men's clothing, Accessories, Kids' Collection, Footwears and Activewear products.
Feel free to ask customers about their preferences, recommend products, and inform them about any ongoing promotions.
The Current Product List is limited as below:
```{product_list}```
Make the shopping experience enjoyable and encourage customers to reach out if they have any questions or need assistance.
"""}]
After you configure your environment and define your product information, you can create your ShopBot chatbot. The get_completion_from_messages
function sends messages to the OpenAI GPT-3.5 Turbo model and retrieves responses from the model.
def get_completion_from_messages(messages, model="gpt-3.5-turbo"):
client = OpenAI(
api_key=MY_OPENAI_KEY,
)
chat_completion = client.chat.completions.create(
messages=messages,
model=model,
)
return chat_completion.choices[0].message.content
To interact with customers, use a simple user interface with text entry for customer messages and a button to start a conversation. The collect_messages
function processes user input, updates conversation context, and displays chat history.
# Interacting with Customers
def collect_messages(_):
user_input = inp.value
inp.value = ''
context.append({'role':'user', 'content':f"{user_input}"})
# Record the start time
start_time = time.time()
response = get_completion_from_messages(context)
# Record the end time
end_time = time.time()
# Calculate the duration
duration = end_time - start_time
# Log to comet_llm
comet_llm.log_prompt(
prompt=user_input,
output=response,
duration=duration,
metadata={
"role": context[-1]['role'],
"content": context[-1]['content'],
"context": context,
"product_list": product_list
},
)
context.append({'role': 'assistant', 'content': f"{response}"})
user_pane = widgets.Output()
with user_pane:
display(widgets.HTML(f"<b>User:</b> {user_input}"))
assistant_pane = widgets.Output()
with assistant_pane:
display(widgets.HTML(f"<b>Assistant:</b> {response}"))
display(widgets.VBox([user_pane, assistant_pane]))
inp = widgets.Text(value="Hi", placeholder='Enter text here…')
button_conversation = widgets.Button(description="Chat!")
button_conversation.on_click(collect_messages)
dashboard = widgets.VBox([inp, button_conversation])
display(dashboard)
Let’s play with the bot. Tailor the context to your own needs by following the Prompting for Developers: A Guideline above.
In this project, I’m using comet_llm
to keep track of what users ask, how the bot responds, and how long each interaction takes. The information is logged to this comet project. This helps in improving the model for future training. You can learn more about experiment tracking with Comet LLM.
# Log to comet_llm
comet_llm.log_prompt(
prompt=user_input,
output=response,
duration=duration,
metadata={
"role": context[-1]['role'],
"content": context[-1]['content'],
"context": context,
"product_list": product_list
},
)
The logs in the Comet UI appear like this. By analyzing these logs, you can use various strategies to make responses quicker, improve accuracy, enhance customer satisfaction, and eliminate unnecessary steps in your ecommerce operations.
Additional: Summarize the order details and send to the user and the respective departments as follows:
messages = context.copy()
messages.append(
{'role':'system'
, 'content':'create a table summary of the previous order.'}
)
response = get_completion_from_messages(messages)
print(response)
Output:
Certainly! Here's a summary of your previous order:
| Product Name | Type | Size | Color | Price |
|---------------------|----------|----------|-----------|-----------|
| Red T-shirt | Women | Small | Red | $20 |
| Comfortable Sneakers| Women | 12 | Black | $55 |
If you have any other questions or need further assistance, please let me know.
For a more advanced e-commerce chatbot, additional training is necessary. Comet LLM simplifies the development of chatbot language models and improves workflow by serving as a valuable tool for logging and viewing messages and threads. It helps you identify effective strategies, streamline problem solving, ensure reproducibility of workflows, and provides insights for efficient model development and optimization.
👉 Explore Comet in action by reviewing my past hands-on projects.
With this simple chatbot, e-commerce stores can offer their customers a personalized and interactive shopping experience. Don’t forget to continually improve and expand your chatbot’s functionality based on user feedback and evolving business needs. Incorporating chatbots into your platform can improve customer satisfaction, increase sales, and make the online purchasing process more enjoyable for everyone involved.
#ChatbotDevelopment #EcommerceChatbot #OpenAI #SimpleChatbot #NoDeepLearning