Quick Summary:
Learn how to build an AI chatbot for Shopify store using the OpenAI Assistant API and Next.js. This guide covers everything from setup to deployment, helping you enhance customer interactions, streamline support, and boost sales with a seamless, intelligent AI Chatbot Development solution integrated directly into your e-commerce platform.
Introduction
AI is transforming e-commerce, making it possible to offer personalized product recommendations, intelligent search, and dynamic customer interactions. Partnering with an AI Chatbot development company to integrate OpenAI’s Assistant API with a Shopify store using Next.js provides a modern and scalable way to enhance the user experience. This AI chatbot for shopify will be able to:
- Recommend products based on customer preferences.
- Provide order status updates.
- Answer frequently asked questions.
Let’s dive into building this powerful tool step by step.
Prerequisites
To follow this tutorial, you’ll need:
- Shopify Admin API Credentials:
– For fetching store data like products and orders. - OpenAI API Key: To interact with OpenAI’s Assistant API.
- Next.js Installed: The React Framework for the Web.
- Basic knowledge of REST APIs and React.
Setting Up the Prerequisites
1. Shopify Admin API Credentials
Shopify Admin API credentials are necessary for fetching store data, such as products and orders. Follow these steps to obtain them:
1.1 Login to Shopify Admin:
Go to your Shopify admin panel.
1.2 Create a Custom App:
- Navigate to Settings > Apps and Sales channels > Develop App > Create an app.
- Enter a name for the custom app, e.g., Shopify Chatbot.
1.3 Configure API Permissions:
- Select the app, and click on Configure admin API scopes.
- Add permissions such as:
read_products: Access product details.
read_orders: Fetch order data.
Note: You can add as per your requirements - Save the configuration.
1.4 Generate an Admin API Token:
- Install the app within your Shopify store.
- Copy the Admin API access token displayed and the Shopify store domain.
2. OpenAI API Key
To enable chatbot interactions, you need an OpenAI API key. Here’s how to get it:
2.1 Sign Up at OpenAI:
- Visit OpenAI’s API platform.
- Create an account or log in.
2.2 Generate API Key:
- Go to the API Keys section in your OpenAI dashboard.
- Click Create New Secret Key and copy the generated key.
Note: This key is required to make API requests to OpenAI Assistant API.
2.3 Create an Assistant in OpenAI Playground
To customize and refine your chatbot’s behavior, you need to create an Assistant in the OpenAI Playground. You can also programmatically create the assistant but for this demo, I will directly create it from Openai assistant playground. Here’s how:
2.3.1 Access the Playground:
- Log in to your OpenAI account and navigate to the Playground.
2.3.2 Set Up the Assistant:
- In the Playground, select Assistants > Create Assistant.
- Configure your Assistant’s behavior by providing instructions in the System Instructions field. For example:
System Instructions:
Greet customers warmly and engage in a brief conversation to understand their needs before assisting with product recommendations on Shopify. Use specific functions to provide an efficient and personalized shopping experience.
Utilize the following functions effectively:
– **”find_product”**: Search for specific products based on customer inquiries.
— **”get_customer_orders”**: Retrieve customer order history using their email to refine suggestions.
— **”get_products”**: Access a comprehensive list of products to offer additional options.
— **”get_reference”**: Use to address queries not related to the functions above.
Responses should be provided in HTML format, with clear instructions and product images included when available.
# Steps
1. Welcome the customer and engage in a friendly conversation to ascertain their interests or needs.
2. Analyze their inquiry to determine the best approach for assistance.
3. Utilize the “find_product” function to locate items matching their needs.
4. Access past purchase information via “get_customer_orders” (with the customer’s email) to offer tailored recommendations.
5. Use “get_products” to suggest additional options that align with their inquiry.
6. Answer unrelated queries using the “get_reference” function.
7. Structure responses in HTML, employing tags like “<p>” for text and “<img>” for visuals, ensuring a pleasant and informative customer experience.
8. Include product images with “<img>” tags when links are available, specifying descriptive alt text.
# Output Format
– HTML format: Responses should be structured with appropriate HTML tags for instructions and embedded images.
— Use “<p>” for paragraphs of text and “<img>” for product images to enhance visual clarity and customer engagement.
# Examples
**Example Start**
**Input:**
Customer asks about vegan skincare products.
**Output:**
<p>Hello! It’s wonderful to assist you today. Interested in vegan skincare products? Let me find some great options for you.</p>
<div>Product 1: Vegan Cleanser <img src=”https://example.com/cleanser.jpg” alt=”Vegan Cleanser”></div>
<div>Product 2: Vegan Moisturizer <img src=”https://example.com/moisturizer.jpg” alt=”Vegan Moisturizer”></div>
<p>Feel free to explore these options, and let me know if you need further information or have any specific preferences!</p>
**Example End**
# Notes
– Ensure the HTML structure is clean and organized to optimize user comprehension and satisfaction.
— Always include product images when available for a better shopping experience.
— Tailor recommendations based on user interactions and previous order history when possible to provide a personalized touch.
- Add the Openai assistant functions. You can create your functions as needed by your application.
Functions used for this demo are:
// Function 1
{
"name": "get_products",
"description": "This function will get the product to suggest/recommed products to customers",
"strict": false,
"parameters": {
"required": [],
"type": "object",
"properties": {}
}
}
// Function 2
{
"name": "get_customer_orders",
"description": "This function will get all the customer order based on the email id.",
"strict": false,
"parameters": {
"type": "object",
"properties": {
"email": {
"type": "string",
"description": "The email of customer"
}
},
"required": []
}
}
// Function 3
{
"name": "find_product",
"description": "This function will find the product with the given product details.",
"strict": false,
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The name of the product"
}
},
"required": []
}
}
- Adjust the temperature, max tokens, and other parameters to control the Assistant’s response style.
2.3.3 Name the Assistant:
- Give your Assistant a name (e.g., “Shopify Assistant”).
- Copy the Assistant ID just below the Assitant Name
2.3.4 Copy the Assistant ID:
- Once saved, go to the Assistants section in your OpenAI dashboard.
- Find your assistant on the list and copy its ID.
Note: This ID will be required in your Next.js application to interact with your customized Assistant.
3. Install Next.js
Next.js is the framework we’ll use for the chatbot. Set it up as follows:
- Run the following command in your terminal to initialize a Next.js project:
npx create-next-app@latest shopify-chatbot
cd shopify-chatbot
2. Now install 2 npm @shopify/shopify-api & openai
npm i @shopify/shopify-api openai
3. Set the four .env variables so that they are not exposed in the browser.
- Create a .env file under the root folder & copy the below 4 variables and add your secrets tokens to it.
OPENAI_API_KEY=""
OPENAI_ASSISTANT_ID=""
SHOPIFY_STORE=""
SHOPIFY_TOKEN=""
4. Verify the setup by running:
npm run dev
Open http://localhost:3000 to confirm the project is running.
4. Basic Knowledge
Before proceeding, ensure you have a foundational understanding of:
- REST APIs: Sending GET and POST requests to interact with external services.
- React: Creating components and managing state.
Building Shopify Demo
With the setup complete, let’s start with building the chat component and its associated API routes. This will form the heart of the chatbot, allowing users to send messages and receive responses.
Got it! I’ll structure the blog according to the folder hierarchy you provided in the image, keeping only the essential logic for each part and avoiding redundant code. Here’s how the blog outline would look:
Building AI Chatbot for Shopify with OpenAI Assistant API
This blog explains how to integrate the OpenAI Assistant API with Shopify to build an AI chatbot. We’ll outline the folder structure and integrate core backend API logic. For full code, refer to the GitHub repository (link at the end).
Folder Structure
The project uses the following folder hierarchy:
app/
├── api/
│ ├── assistants/
│ │ ├── threads/
│ │ │ ├── [threadId]/
│ │ │ │ └── route.ts
│ │ │ ├── messages/
│ │ │ │ └── route.ts
│ │ │ └── route.ts
│ ├── shopify/
│ │ ├── orders/
│ │ │ └── route.ts
│ │ ├── products/
│ │ │ └── route.ts
├── components/
│ └── Chat.tsx
├── fonts/
├── page.tsx
├── assistant-config.ts
├── openai.ts
Backend API Implementation
1. Assistant Threads
- Route: /api/assistants/threads (Create Thread)
- Purpose: Start a new assistant thread.
- Code:
// Create a new thread
export async function POST() {
const thread = await openai.beta.threads.create();
return Response.json({ threadId: thread.id });
}
2. Route: /api/assistants/threads/[threadId]/messages (Send Message)
- Purpose: Send user messages to the assistant thread.
- Code:
// Send a new message to a thread
export async function POST(request: any, { params: { threadId } }: any) {
const { content } = await request.json();
await openai.beta.threads.messages.create(threadId, {
role: "user",
content: content,
});
const stream = openai.beta.threads.runs.stream(threadId, {
assistant_id: assistantId,
});
return new Response(stream.toReadableStream());
}
3. Route: /api/assistants/threads/[threadId]/actions (Handle Actions)
- Purpose: Process required actions (e.g., tool calls).
- Code:
// Send a new message to a thread
export async function POST(request: any, { params }: any) {
const { threadId } = await params;
const { toolCallOutputs, runId } = await request.json();
const stream = openai.beta.threads.runs.submitToolOutputsStream(
threadId,
runId,
{ tool_outputs: toolCallOutputs }
);
return new Response(stream.toReadableStream());
}
2. Shopify API Endpoints
- Route: /api/shopify/products (Fetch Product Details)
- Purpose: Retrieve product data from Shopify.
- Code:
// function to find the products
export async function POST(_request: any) {
const response = await fetch(
`https://${shop}/admin/api/2024-10/graphql.json`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Shopify-Access-Token": accessToken!, // Include access token
},
body: JSON.stringify({ query }),
}
);
const responseData = await response.json();
/// prepare the data
const products = responseData?.data?.products?.edges?.map(
(product: any) => {
return {
id: product.node.id,
title: product.node.title,
description: product.node.description,
price: product.node.priceRange.minVariantPrice.amount,
currency: product.node.priceRange.minVariantPrice.currencyCode,
images: product.node.images.edges.map((image: any) => {
return {
url: image.node.url,
altText: image.node.altText,
};
}),
};
}
);
return new Response(JSON.stringify(products), {
headers: {
"Content-Type": "application/json",
},
});
}
/// get products from the shopify store
export async function GET(_request: any) {
const response = await fetch(
`https://${shop}/admin/api/2024-10/graphql.json`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Shopify-Access-Token": accessToken!, // Include access token
},
body: JSON.stringify({ query }),
}
);
const responseData = await response.json();
/// prepare the data
const products = responseData?.data?.products?.edges?.map(
(product: any) => {
return {
id: product.node.id,
title: product.node.title,
description: product.node.description,
price: product.node.priceRange.minVariantPrice.amount,
currency: product.node.priceRange.minVariantPrice.currencyCode,
images: product.node.images.edges.map((image: any) => {
return {
url: image.node.url,
altText: image.node.altText,
};
}),
};
}
);
return new Response(JSON.stringify(products), {
headers: {
"Content-Type": "application/json",
},
});
}
2. Route: /api/shopify/orders (Fetch Customer Orders)
- Purpose: Retrieve order details by customer email.
- Code:
// function to get the customer orders
export async function POST(_request: any) {
const response = await fetch(
`https://${shop}/admin/api/2024-10/graphql.json`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Shopify-Access-Token": accessToken!, // Include access token
},
body: JSON.stringify({ query }),
}
);
const responseData = await response.json();
/// prepare the data
const orders = responseData?.data?.customers?.edges?.map(
(customer: any) => {
return {
id: customer.node.id,
firstName: customer.node.firstName,
lastName: customer.node.lastName,
email: customer.node.email,
orders: customer.node.orders.edges.map((order: any) => {
return {
id: order.node.id,
name: order.node.name,
processedAt: order.node.processedAt,
totalPrice: order.node.totalPriceSet.shopMoney.amount,
currency: order.node.totalPriceSet.shopMoney.currencyCode,
lineItems: order.node.lineItems.edges.map((lineItem: any) => {
return {
title: lineItem.node.title,
quantity: lineItem.node.quantity,
};
}),
};
}),
};
}
);
return new Response(JSON.stringify(orders), {
headers: {
"Content-Type": "application/json",
},
});
}
Frontend Components
1. Chat Component
File: /components/Chat.tsx
The Chat component provides the user interface for the AI chatbot. It communicates with the backend APIs, handles message display, and manages the conversation thread.
Key Features:
- User Input: Allows users to type and send messages.
- Message Display: Shows messages from both the user and the assistant.
- Streaming Responses: Handles real-time streaming of assistant responses.
"use client";
import React, { useState, useEffect, useRef } from "react";
import styles from "./chat.module.css";
import { AssistantStream } from "openai/lib/AssistantStream";
// Define types for message roles
type MessageProps = {
role: "user" | "assistant" | "code";
text: string;
};
// Components for rendering different message types
const UserMessage = ({ text }: { text: string }) => <div>{text}</div>;
const AssistantMessage = ({ text }: { text: string }) => <div>{text}</div>;
// Main Chat Component
const Chat = ({ functionCallHandler }: any) => {
const [userInput, setUserInput] = useState("");
const [messages, setMessages] = useState([]);
// Fetch thread ID when the chat is initialized
useEffect(() => {
fetch(`/api/assistants/threads`, { method: "POST" })
.then((res) => res.json())
.then((data) => setMessages([{ role: "assistant", text: "Chat started!" }]));
}, []);
const sendMessage = async () => {
const response = await fetch(
`/api/assistants/threads/<threadId>/messages`,
{ method: "POST", body: JSON.stringify({ content: userInput }) }
);
const stream = AssistantStream.fromReadableStream(response.body);
// Handle stream here...
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
sendMessage();
};
return (
<div>
<div>
{messages.map((msg, index) => (
<div key={index}>{msg.text}</div>
))}
</div>
<form onSubmit={handleSubmit}>
<input
value={userInput}
onChange={(e) => setUserInput(e.target.value)}
/>
<button type="submit">Send</button>
</form>
</div>
);
};
export default Chat;
2. Page Component
File: /page.tsx
This component serves as the main page for the AI chatbot interface. It integrates the Chat component and provides the function handlers for tool calls.
Code Snippet:
"use client";
import Chat from "./components/Chat";
export default function Home() {
const functionCallHandler = async (toolCall: any) => {
const { functionName, arguments: args } = toolCall;
if (functionName === "find_product") {
/// get the product name and return the product details
const response = await fetch("/api/shopify/products", {
method: "POST",
body: JSON.stringify({ product_name: args.query }),
});
if (response.ok) {
return JSON.stringify({ success: true, data: await response.json() });
}
} else if (functionName === "get_customer_orders") {
/// get the customer orders and return the orders
const response = await fetch("/api/shopify/orders", {
body: JSON.stringify({
email: args.email,
}),
method: "POST",
});
if (response.ok) {
return JSON.stringify({ success: true, data: await response.json() });
}
} else if (functionName === "get_products") {
/// get product recommendation / suggestion
const response = await fetch("/api/shopify/products", {
method: "GET",
});
if (response.ok) {
return JSON.stringify({ success: true, data: await response.json() });
}
}
};
return (
<main>
<Chat functionCallHandler={functionCallHandler} />
</main>
);
}
Conclusion
This project showcases the seamless integration of OpenAI’s Assistant API with Shopify, creating a powerful platform for automating customer interactions and streamlining e-commerce workflows. By leveraging tools like function calls and real-time message handling, businesses can enhance user experiences, improve efficiency, and provide personalized support to their customers.
With the provided backend architecture, API routes, and detailed implementation, developers can easily customize and expand the solution to fit their unique requirements. Whether it’s fetching product details, handling customer orders, or creating a conversational shopping assistant, this implementation serves as a robust starting point.
For those looking to dive deeper, explore the resources below, including a GitHub repository with the complete codebase, video demonstrations, and references for further learning. Alternatively, partnering with an AI Chatbot development company can provide expert guidance, customized solutions, and faster deployment. Such companies bring industry expertise and tailored strategies to help businesses unlock the full potential of AI-powered e-commerce, ensuring a seamless and impactful implementation. The possibilities for building smarter, AI-powered solutions are endless, and this project is just the beginning!
References:
Access the Full Codebase Here:
GitHub link: https://github.com/juzarantri/shopify-chatbot