skip to Main Content
Join Us for Comet's Annual Convergence Conference on May 8-9:

Create a Simple E-commerce Chatbot With OpenAI

    Words By
    November 22, 2023

Forget about complicated Deep Learning algorithms — making a chatbot is way simpler with OpenAI and CometLLM

Create an e-commerce chatbot / shopbot with OpenAI and CometLLM
Chatbot in Ecommerce (Credit: Maksym Pundyk in ideainyou.com)

Table of Contents

Introduction

I. Prompting for Developers: A Guideline

II. Building a Shopbot using OpenAI and CometLLM

  1. Understanding the Basics
  2. Setting Up the Environment
  3. Defining Product Information
  4. Creating the Chatbot
  5. Interacting with Customers

III. Reference

Conclusion

Introduction

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

I. Prompting for Developers: A Guideline

Principle 1: Write Clear and Specific Instructions

  1. Delimiters for Precision: start clearly. Use delimiters such as triple quotes (“‘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.
  2. Structured output for increased accuracy: Specify the desired format of the output (HTML or JSON). A structured framework ensures that the model accurately understands and fulfills requests, avoiding misunderstandings.
  3. Validate trust assumptions: Validate whether the required conditions are met before assigning a task. Clearly explain the prerequisites required for the task and ensure that your understanding of the model aligns with your expectations for safe execution.
  4. Few-Shot Prompting for Guidance: Before instructing the model, provide examples of successful task completion. This not only guides the model on the right path, but also increases the probability of accurate results.

Principle 2: Give the Model Time to “Think”

  1. Comprehensive task steps: Break down complex tasks into step-by-step instructions. This allows the model to understand the complexity of the task and increases the likelihood of accurate and complete results.
  2. Encourage thoughtful solutions: Give it time to find its own solutions instead of urging the model’s conclusions. This patient approach reduces the potential for error caused by hasty action and encourages more thoughtful responses., enhancing the likelihood of accurate and comprehensive outputs.

A Complex prompt

Now, considering the concept of complex indicators, these principles can be applied to indicators that cover at least 3 of the following parameters:

  1. Role: Assign an expert role to a task.
  2. Task: Enter a brief summary of the task.
  3. Context: Provide relevant background.
  4. Steps to complete the task: Provide specific steps.
  5. Output format: Specify the desired format, style, or tone.
  6. Limitations: Please note any limitations or requirements.
  7. Purpose: Describe the purpose for the results.

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!

II. Building a Shopbot using OpenAI and CometLLM

1. Understanding the Basics

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.

2. Setting Up the Environment

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)

3. Defining Product Information

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.
"""}]

4. Creating the Chatbot

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

5. Interacting with Customers

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.

Demo Shopbot (Image by Author)

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.

Further LLM training based on the logs (Image by Author)

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.

III. Reference

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.

Conclusion

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

Nhi Yen

Back To Top