Introduction
In this tutorial, you'll learn how to create a conversational AI assistant that can analyze product searches and generate personalized recommendations using Google's Gemini API. This builds on the recent Google Search AI evolution that includes more AI-powered ads. You'll build a prototype that mimics how AI chatbots analyze user queries and surface relevant products with custom explanations.
Prerequisites
- Basic Python programming knowledge
- Google Cloud account with billing enabled
- Google Cloud Project with Gemini API enabled
- Python 3.7 or higher installed
- pip package manager
Step-by-step instructions
1. Set up Your Google Cloud Environment
1.1 Create a Google Cloud Project
First, navigate to the Google Cloud Console and create a new project or select an existing one. Enable the Vertex AI API and the Generative Language API for your project.
1.2 Generate API Credentials
Go to the IAM & Admin section, create a service account, and download the JSON key file. This key will authenticate your application to use the Gemini API.
1.3 Install Required Python Packages
Install the required packages using pip:
pip install google-generativeai python-dotenv
2. Configure Your Environment
2.1 Set Up Environment Variables
Create a .env file in your project directory with your API key:
GOOGLE_API_KEY=your_actual_api_key_here
2.2 Initialize the Gemini Client
Create a Python script to initialize the Gemini client:
import os
import google.generativeai as genai
from dotenv import load_dotenv
load_dotenv()
# Configure the API key
api_key = os.getenv('GOOGLE_API_KEY')
genai.configure(api_key=api_key)
# Initialize the model
model = genai.GenerativeModel('gemini-pro')
3. Build the Product Recommendation Engine
3.1 Create Product Database
First, create a sample product database that your AI will analyze:
products = [
{
'name': 'iPhone 15 Pro',
'category': 'smartphone',
'price': 999,
'features': ['A17 Pro chip', 'Titanium design', 'Pro camera system'],
'target_audience': 'tech enthusiasts, professionals'
},
{
'name': 'MacBook Air M2',
'category': 'laptop',
'price': 1099,
'features': ['M2 chip', '13.6-inch display', '18-hour battery'],
'target_audience': 'students, remote workers'
},
{
'name': 'Sony WH-1000XM5',
'category': 'headphones',
'price': 350,
'features': ['Active noise cancellation', '30-hour battery', 'Premium sound'],
'target_audience': 'travelers, music lovers'
}
]
3.2 Implement Query Analysis Function
Build a function that analyzes user search queries and matches them with products:
def analyze_query_and_recommend(query, products):
# Create a prompt that tells Gemini how to analyze the query
prompt = f"""
You are an AI product recommendation assistant. Analyze this search query: '{query}'
Match it with the following products:
{products}
For each matching product, generate a custom explainer that explains why this product is perfect for the user's needs.
Format your response as:
- Product Name: [explanation]
- Product Name: [explanation]
"""
# Generate response using Gemini
response = model.generate_content(prompt)
return response.text
3.3 Create the Main Recommendation Function
Combine everything into a main function that handles user input:
def main_recommendation_system():
print("AI Product Recommendation Assistant")
print("Enter your search query (or 'quit' to exit):")
while True:
user_query = input("\nQuery: ")
if user_query.lower() in ['quit', 'exit']:
break
# Get recommendations
recommendations = analyze_query_and_recommend(user_query, products)
print(f"\nRecommended products for '{user_query}':")
print(recommendations)
# Add a small delay for better readability
import time
time.sleep(1)
4. Test Your AI Assistant
4.1 Run the Application
Execute your script and test with various search queries:
if __name__ == "__main__":
main_recommendation_system()
4.2 Example Test Queries
Try these sample queries to see how your AI responds:
- "I need a laptop for video editing"">
- "Best headphones for commuting"">
- "Tech gift for a professional"">
4.3 Analyze the Output
Notice how the AI generates custom explanations for each product based on the user's query. This mimics how Google's Gemini AI creates personalized ad explanations for users.
5. Enhance Your AI Assistant
5.1 Add Product Filtering
Improve the recommendation by adding more sophisticated filtering:
def filter_products_by_query(query, products):
# Simple keyword matching for demonstration
filtered = []
query_lower = query.lower()
for product in products:
# Check if query keywords match product features
if any(keyword in query_lower for keyword in product['features']):
filtered.append(product)
elif product['category'] in query_lower:
filtered.append(product)
return filtered
5.2 Add Response Formatting
Improve the output presentation:
def format_recommendations(recommendations):
formatted = "\n" + "="*50 + "\n"
formatted += "AI RECOMMENDATIONS\n"
formatted += "="*50 + "\n"
# Simple parsing of AI response
lines = recommendations.split('\n')
for line in lines:
if line.strip() and ':' in line:
formatted += f"{line}\n"
formatted += "="*50 + "\n"
return formatted
6. Deployment Considerations
6.1 API Cost Management
Keep in mind that Gemini API usage costs money. Monitor your usage and set budget alerts in the Google Cloud Console.
6.2 Error Handling
Add proper error handling to make your assistant more robust:
def safe_generate_recommendations(query, products):
try:
return analyze_query_and_recommend(query, products)
except Exception as e:
return f"Error generating recommendations: {str(e)}"
Summary
In this tutorial, you've built a conversational AI assistant that analyzes user queries and generates personalized product recommendations using Google's Gemini API. This implementation mirrors Google's recent AI-powered search and advertising evolution. The assistant processes user input, matches it with a product database, and generates custom explanations for why each product is recommended. You've learned how to set up the Gemini API, structure prompts for optimal results, and create a working recommendation system. This foundation can be expanded with more sophisticated filtering, larger product databases, and integration with real e-commerce APIs to create a production-ready AI recommendation engine.



