How to Build a Shopping Cart AI Chatbot
Tags: ai, webdev, openai, chatgpt
Published: 2024-06-02 08:50:35

In our [last article](https://ainiro.io/blog/create-ai-assistents-with-magic-cloud) we demonstrated our new AI functions. By building on top of these, we can build any amount of complexity into our AI chatbots - Including a shopping cart AI chatbot, such as illustrated in this article. If you want to try the AI chatbot we're building in this article you can find it below.

* [Spy Gear Shopping Cart AI Chatbot](https://thomastest-team.us.ainiro.io/spyshop)

## Video demonstration

In the following video I am demonstrating the shopping cart AI chatbot, by going through the entire shopping experience using nothing but the AI chatbot to shop. In addition I am showing additional features almost impossible to implement using a more traditional UI-based chopping cart, such as the ability to tell the AI chatbot the following, and having it intelligently respond back to you.

> _"I've got 1 million to spend, what items can I add without exceeding my budget?"_

{% embed https://www.youtube.com/watch?v=csIy6924Z8w %}

The above video is only 7 minutes long. I **seriously recommend you watch it** to understand the power of this feature.

## How it works

The whole idea of the chatbot is to allow you to use natural language to guide you through your entire shopping experience. Below is an example of how to add two items to your cart. If you look carefully at the image below you will see two green icons. These implies the AI chatbot invoked two AI functions, one for each product I asked it to add for me.

<img alt="Adding two items to your shopping cart AI chatbot" src="https://ainiro.io/assets/images/blog/buying-spy-gear-from-shopping-cart-ai-chatbot.png" style="max-width: 550px;margin-left: auto;margin-right: auto;">

In addition to adding items, it also has the following functions.

* Remove item from cart
* List all products
* List all items in my cart
* Checkout and pay for my items

The checkout process simply creates a summary email that it sends to you, but this part could easily be integrated with WooCommerce or Shopify to perform a real sale.

## Implementation

The most important part of our AI chatbot is its system message. Our system message contains references to AI functions, such as follows.

```
## Adding items to shopping cart

If the user informs you that he or she wants to buy an item and you know
the item's SKU, then respond with this EXACT response, only exchanging the
[sku] and the [quantity].

___
FUNCTION_INVOCATION[/modules/shopping-cart-demo/workflows/add-item.hl]:
{
  "sku": "[sku]",
  "quantity": "[quantity]"
}
___

If the user did not provide a quantity then do not ask the user for a quantity
but use a value of 1 by default. If you don't know the item's SKU, ask the
user to provide some more keywords for what item he or she wants to buy such
that you can find the correct SKU before responding with the above function
invocation.
```

The above instructs OpenAI to return a `FUNCTION_INVOCATION` if the user says he or she wants to add an item to his shopping cart. Such function invocations will be executed on the cloudlet, and contains references to AI workflows. Below is the AI workflow for the above function.

```
/*
 * Adds an item to your shopping cart
 *
 * [product_id] is mandatory and has to be an existing product_id from an
 * item existing in your database, and [quantity] will default to 1 if not
 * specified.
 */
.arguments
   sku:string
   quantity:int
   session:string
.description:Adds an item to your shopping cart
.type:public

// Defaulting [quantity] to 1 if not specified.
validators.default:x:@.arguments
   quantity:int:1

/*
 * Invokes the SQL CRUD Read slot with the specified parameters.
 *
 * Provide [connection-string], [database-type], [database], and [table] to
 * inform the action of what database/table you want to execute your SQL
 * towards, and add [and] or [or] arguments to filter your returns, in
 * addition to [limit] and [offset] to apply paging. Use [order]
 * and [direction] to sort either ascending or descending. Notice, you can
 * only use one of [or] or [and], and not both.
 */
execute:magic.workflows.actions.execute
   name:sql-read-products
   filename:/misc/workflows/actions/sql/sql-read.hl
   arguments
      columns
         .:product_id
      database:shopping-cart-demo
      table:products
      and
         sku:x:@.arguments/*/sku

/*
 * Invokes the SQL CRUD Create slot with the specified parameters.
 *
 * Provide [connection-string], [database-type], [database], and [table]
 * to inform the action of what database/table you want to execute your
 * SQL towards, and [values] for your actual values to insert.
 */
execute:magic.workflows.actions.execute
   name:sql-create-shopping-cart-item
   filename:/misc/workflows/actions/sql/sql-create.hl
   arguments
      database:shopping-cart-demo
      table:items
      values
         product_id:x:--/execute/=sql-read-products/*/*/product_id
         quantity:x:@.arguments/*/quantity
         session_id:x:@.arguments/*/session

// Returns the result of your last action.
return-nodes:x:@execute/*
```

Such AI functions can also be declared as training snippets, allowing you to have literally thousands of them - And 98% of the above code was created without coding using our [Hyperlambda Workflow feature](https://docs.ainiro.io/workflows/).

The end result of the above becomes that if we say stuff such as _"I want to buy the flying car"_ to our AI chatbot, then OpenAI will return a function invocation declaration that our machine learning type will execute. Our function invocation inserts a new record into our _"items"_ table in our _"shopping-cart-demo"_ database. This allows the AI chatbot to keep track of which items have been added. You can see the database schema below.

<img alt="Our shopping cart database schema" src="https://ainiro.io/assets/images/blog/shopping-cart-database-schema.png" style="max-width: 750px;margin-left: auto;margin-right: auto;">

It's a fairly naive shopping cart, but it also allows for integrating with Shopify, WooCommerce, or any other e-commerce platform you have - So don't be fooled by its simplicity.

## Security

Unless you implement this correctly, you could in theory prompt engineer the AI chatbot to return function invocations that are unsafe. We guard against this by checking if the function invocation is declared either in the system message or the type's training data before we allow for a function to being executed.

This completely eliminates _"function injection attacks"_, that are similar in nature to SQL injection attacks. However, you still have to be careful when adding function declarations to your type, and only add functions you know for a fact are safe to allow the user to execute.

In the future we might also implement support for functions that requires the user to belong to some role, in addition to some authentication and authorisation mechanism, to allow for the user to log in to the AI chatbot, changing his or her rights in regards to what functions are allowed to being executed by the user. But currently we don't have anything here. But this is a high priority feature we are working on a lot, so expect things to rapidly change here.

## Wrapping up

AI functions is the by far funniest and most rewarding thing I've worked on since I started working with OpenAI. In a way it turns a _"boring text-producing LLM"_ into a fully fledged AI assistent. Such AI assistents can be created to do incredible things, especially once we add authentication and authorisation to them. Below is a list if things we could easily do using AI functions.

* Order a plane ticket to New Zealand
* Check the weather in Los Angeles tomorrow
* What's the stock price for Apple
* Send Mike an email and tell him I'll be late for our meeting
* I need to call Jane, give me her phone number
* Create a new customer in my CRM system
* Etc, etc, etc ...

All of the above would literally be _"15 minutes job"_ using Magic Cloud. If you're interested in seeing what we can do for your organisation related to this, you can contact us below.

* [Contact us](https://ainiro.io/contact-us)