Building AI-powered e-commerce applications using Angular and Firebase AI Logic (formerly Vertex AI in Firebase)
A Practical Guide to Integrating Generative AI into Your Online Store with Angular and Firebase
The landscape of online shopping has undergone a dramatic transformation. From the early days of simple digital catalogs, e-commerce has evolved into a dynamic, personalized, and highly competitive space. Today, the next frontier in this evolution is the integration of Artificial Intelligence (AI), which promises to make online retail more efficient and intuitive than ever before. AI is rapidly becoming a pivotal force in automating repetitive tasks, personalizing user experiences, and ultimately, driving sales and customer satisfaction.
This article will guide you through building a modern, AI-powered e-commerce application using Angular for the front end and leveraging the capabilities of Google's Firebase AI Logic (formerly Vertex AI in Firebase). We will explore how to implement intelligent features by referencing code snippets from the "Bytewise" e-commerce application, a practical example I created, available on GitHub.
The Inevitable Rise of AI in E-commerce
Initially, e-commerce platforms focused on providing a convenient way to browse and purchase products. As the market matured, the focus shifted towards enhancing the user experience through features like customer reviews, wishlists, and basic recommendation engines. However, with the explosion of online stores and product variety, a new set of challenges emerged. Shoppers became overwhelmed with choices, and businesses struggled to differentiate themselves.
This is where AI steps in. By harnessing the power of machine learning and large language models (LLMs), e-commerce businesses can now:
Automate Customer Support: AI-powered chatbots can handle a vast range of customer inquiries 24/7, from order tracking to product questions, freeing up human agents to tackle more complex issues.
Personalize Shopping Experiences: AI algorithms can analyze user behavior, purchase history, and even real-time interactions to provide highly personalized product recommendations, search results, and marketing content.
Optimize Inventory and Pricing: Predictive analytics can forecast demand, helping businesses manage their stock levels more effectively and implement dynamic pricing strategies to maximize revenue.
Streamline Product Discovery: AI can power intelligent search functionalities that understand natural language queries, making it easier for customers to find exactly what they are looking for.
Introducing Firebase AI Logic: The Brains of Your E-commerce App
Firebase AI Logic is a powerful suite of tools that allows developers to easily integrate Google's cutting-edge generative AI models, like Gemini, directly into their web and mobile applications. It acts as a bridge between your application and powerful AI capabilities, handling the complexities of model deployment and scaling.
Firebase has evolved from "Vertex AI in Firebase" to the more robust "Firebase AI Logic," offering greater flexibility in building AI features. Developers can now use either the free Gemini Developer API or the Vertex AI Gemini API, and importantly, there's no need to include your Gemini API key directly in your app's code.
Gemini Developer API—billing is optional (available on the no-cost Spark plan)
Vertex AI Gemini API—billing is required (requires the pay-as-you-go Blaze plan)
Building an AI-Powered E-commerce App with Angular and Firebase
Let's dive into the practical aspects of building our AI-powered e-commerce application, "Bytewise." The application is built with Angular, a popular framework for creating dynamic single-page applications, and utilizes Firebase for its backend services, including Firebase AI Logic for its intelligent features.
You can find the complete source code for the Bytewise application on GitHub: https://github.com/waynegakuo/bytewise
About Bytewise
ByteWise is a fictional e-commerce platform that showcases electronic products with an integrated AI shopping assistant. The application features:
Product catalog with detailed product information
AI assistant that can answer questions about products
Voice recognition for hands-free interaction with the AI assistant
Shopping cart functionality
Responsive UI with modern design
Screenshot: ByteWise app in action
Setting Up the Project🚀
This article assumes familiarity with Angular and Firebase setup. For setup instructions, please refer to the "Setting Up Locally" section before cloning the project.
Alternatively, you can open the ByteWise project on Firebase Studio, which will provide you with a web-based IDE with the requirements provisioned, and follow along.
Firebase Project and Firebase AI Logic Setup 🔥
Next, you'll need a Firebase project with a web application configured. You will also need to enable Firebase AI Logic on your Firebase project.
Follow the directions in Step 1 to create a project and a web app. You do not need to add any SDK code snippets during this step, as this example project already includes them.
After creating your Firebase project, go to the Firebase AI Logic page in the Firebase console. Click "Get Started" and select "Get started with this API" for the Gemini Developer API. This API is preferable as it avoids the need to provide billing details.
Register your web app by clicking on the web icon as shown in the screenshot below:
Leave the Firebase Hosting checkbox unchecked. After obtaining your Firebase credentials (firebaseConfig
), copy the entire contents; you'll need them in the next step.
Back in our codebase, in the environment.ts
file, paste the contents of the Firebase configuration details into the firebaseConfig
object.
// src/environments/environment.ts
export const environment = {
production: false,
firebaseConfig: {
apiKey: "<your-api-key>",
authDomain: "<your-app-domain>",
projectId: "<your-project-id>",
storageBucket: "<your-storage-bucket-id>",
messagingSenderId: "<your-message-sender-id>",
appId: "<your-app-id>",
measurementId: "<your-measurement-id>"
},
};
Install dependencies:
npm install
Running the Application 🏃♂️
With the configuration complete, you can now start the development server:
ng serve
This command will build your Angular application and start a local development server. You can then access the application in your web browser at http://localhost:4200
Core Architecture
Product State Management with Signals
The foundation of our system uses Angular's signal-based state management:
// src/app/services/product.service.ts
@Injectable({
providedIn: 'root'
})
export class ProductService {
private readonly products = signal<Product[]>([]);
private readonly cart = signal<Product[]>([]);
readonly cartCount = computed(() => this.cart().length);
readonly totalPrice = computed(() =>
this.cart().reduce((sum, item) => sum + item.price, 0)
);
constructor() {
// Initialize with default products
this.products.set([
{ id: 1, name: 'Laptop', price: 85000 },
{ id: 2, name: 'Smartphone', price: 35000 }
]);
}
getProducts() {
return this.products();
}
addToCart(product: Product) {
this.cart.update(current => [...current, product]);
}
clearCart() {
this.cart.set([]);
}
}
AI Service
One of the most common and effective uses of AI in e-commerce is a customer support chatbot. In the Bytewise application, we have a AiService
that handles the interaction with the Firebase AI Logic.
// src/app/services/ai.service.ts
@Injectable({
providedIn: 'root'
})
export class AiService {
private readonly productService = inject(ProductService);
private readonly model: GenerativeModel;
private readonly chat: ChatSession;
...
}
This service utilizes Angular's dependency injection system to maintain a clean, modular architecture. The service manages both the AI model and chat session, creating a seamless interface between user interactions and AI responses.
AI Configuration and Tool Integration
The system defines specific e-commerce operations through a structured tool set:
// src/app/services/ai.service.ts
const productsToolSet: FunctionDeclarationsTool = {
functionDeclarations: [
{
name: "getTotalNumberOfProducts",
description: "Get the total number of products available in the store.",
},
{
name: "getProducts",
description: "Get an array of the products with the name and price of each product.",
}
// Additional function declarations...
]
};
This tool set enables the AI to perform specific actions within the e-commerce system, from checking inventory to managing shopping carts.
Strong Type Safety with Schema Definitions
Product data integrity is maintained through robust schema definitions:
// src/app/services/ai.service.ts
...
Schema.object({
properties: {
productsToAdd: Schema.array({
items: Schema.object({
properties: {
name: Schema.string({
description: "The name of the product.",
}),
price: Schema.number({
description: "The numerical price of the product.",
}),
},
required: ["name", "price"],
}),
}),
},
})
...
This schema ensures that all product-related operations maintain data consistency and type safety.
Gemini Developer API Setup and System Instructions
The integration with Google's Gemini AI is configured with specific business rules:
// src/app/services/ai.service.ts
...
const geminiAI = getAI(this.firebaseApp, {backend: new GoogleAIBackend()});
const systemInstruction =
"Welcome to ByteWise. You are a superstar agent for this ecommerce store..." ;
this.model = getGenerativeModel(geminiAI , {
model: "gemini-2.0-flash",
systemInstruction: systemInstruction,
tools: [productsToolSet],
});
...
The code initializes a Gemini AI-powered chatbot for the e-commerce store, which will interact with the inventory system and shopping cart, and is equipped with tools to perform various shopping-related functions.
The systemInstruction
property is crucial as it helps the AI model understand its context and maintain consistent formatting when interacting with users about products and prices in the ByteWise ecommerce store.
AI Interaction Processing
The system handles AI interactions through a sophisticated message processing system:
// src/app/services/ai.service.ts
...
async askAgent(userPrompt: string) {
let result = await this.chat.sendMessage(userPrompt);
const functionCalls = result.response.functionCalls();
if(functionCalls && functionCalls.length > 0) {
for (const functionCall of functionCalls) {
switch (functionCall.name) {
case "getTotalNumberOfProducts": {
const functionResult = this.getTotalNumberOfProducts();
// Process response
break;
}
// Additional case handling...
}
}
}
return result.response.text();
}
...
The askAgent
function takes a user's prompt (their question or message) as input, sends it to the Gemini model via Firebase AI Logic, and returns the model's generated text response.
Think of it as a smart assistant for an e-commerce store that can understand user requests and perform actions. Here's how it works:
Taking User Input:
When a user types something (like "How many products do you have?" or "Add this to my cart"), the method takes this message as a
userPrompt
It sends this message to an AI chat system
Checking for Actions:
The AI analyzes the message and decides if it needs to perform any specific actions (called "function calls")
For example, if you ask "How many products are there?", it will need to check the actual product count
Handling Different Actions: The method can handle four main types of actions:
getTotalNumberOfProducts
: Counts all products in the storegetProducts
: Gets the list of all available productsclearCart
: Empties the shopping cartaddToCart
: Adds specific products to the cart
Completing the Conversation:
After performing any necessary actions, it sends the results back to the AI
The AI then forms a natural response to the user
This response is returned to be shown to the user
It's like having a helpful store assistant who can both answer questions and perform actions for you!
Service Integration in Components
Bringing it all together in the user interface:
// src/app/components/agent-window.component.ts
@Component({
selector: 'app-agent-window',
...
})
export class AgentWindowComponent {
private readonly aiService = inject(AiService);
readonly productService = inject(ProductService);
....
constructor() {
this.productList.set(this.productService.getProducts());
...
}
async sendMessage(): Promise<void> {
if (this.userInput.trim() === '') return;
// Add user message
this.messageHistory.update((history) =>
[...history, { text: this.userInput, isUser: true }]
);
// Clear input
const userQuestion = this.userInput;
this.userInput = '';
...
try {
const response = await this.aiService.askAgent(userQuestion);
this.messageHistory.update((history) => [
...history,
{ isUser: false, text: response }
]);
} finally {
// Set thinking state to false regardless of success or failure
this.isThinking.set(false);
}
}
...
}
This component serves as the main interface for user-AI interaction in your e-commerce platform, providing a clean and intuitive chat experience while maintaining a reactive and performant implementation using Angular’s signals.
Conclusion
The integration of AI is no longer a futuristic concept in e-commerce; it's a present-day necessity for creating engaging, efficient, and personalized online shopping experiences. By combining the power of a versatile front-end framework like Angular with the accessible and powerful AI capabilities of Firebase AI Logic, developers can build the next generation of e-commerce applications.
The Bytewise example provides a solid foundation for understanding the practical implementation of these concepts. As AI models continue to evolve and become more sophisticated, the possibilities for innovation in e-commerce are boundless. The journey to a truly intelligent online store starts with embracing these powerful tools and reimagining what's possible in the world of online retail.