Introduction
In this tutorial, you'll learn how to create an AI-powered messaging system similar to what Meta AI is implementing in Facebook Marketplace. You'll build a Python application that can automatically generate personalized replies to buyer inquiries based on product listing information. This system demonstrates key concepts in natural language processing, API integration, and automated content generation that are increasingly important in modern e-commerce platforms.
Prerequisites
- Basic Python programming knowledge
- Python 3.7 or higher installed
- Access to OpenAI API key (or alternative LLM API)
- Basic understanding of REST APIs and HTTP requests
- Installed packages: openai, python-dotenv
Step-by-Step Instructions
Step 1: Set Up Your Development Environment
1.1 Create a Project Directory
First, create a new directory for your project and navigate into it:
mkdir marketplace-ai-replier
cd marketplace-ai-replier
1.2 Install Required Dependencies
Install the necessary Python packages using pip:
pip install openai python-dotenv
1.3 Create Environment Configuration
Create a .env file to securely store your API key:
API_KEY=your_openai_api_key_here
Important: Never commit your API keys to version control. The .env file should be added to your .gitignore.
Step 2: Initialize the AI Client
2.1 Create the Main Application File
Create a file called marketplace_ai.py and start with the basic imports:
import os
from openai import OpenAI
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Initialize the OpenAI client
client = OpenAI(api_key=os.getenv('API_KEY'))
2.2 Configure API Parameters
Set up default parameters for your AI responses:
DEFAULT_RESPONSE_PARAMS = {
'model': 'gpt-3.5-turbo',
'temperature': 0.7,
'max_tokens': 150
}
The temperature setting controls creativity - 0.7 provides a good balance between helpfulness and consistency.
Step 3: Create Product Listing Structure
3.1 Define Product Data Model
Create a function to structure your product information:
def create_product_listing(name, description, price, location, availability):
return {
'name': name,
'description': description,
'price': price,
'location': location,
'availability': availability
}
3.2 Sample Product Data
Add sample product data to test your system:
sample_product = create_product_listing(
name='Vintage Leather Jacket',
description='Genuine leather jacket from 1980s, excellent condition',
price='$85',
location='San Francisco, CA',
availability='In stock - ready for pickup'
)
Step 4: Build the AI Response Generator
4.1 Create the Prompt Template
Design a prompt template that instructs the AI how to respond:
def generate_response_prompt(product_info, buyer_message):
return f"""
You are a helpful seller responding to a buyer's inquiry about a product.
Product Information:
Name: {product_info['name']}
Description: {product_info['description']}
Price: {product_info['price']}
Location: {product_info['location']}
Availability: {product_info['availability']}
Buyer's Message: {buyer_message}
Please provide a helpful, professional response that addresses the buyer's inquiry using the product information above. Keep your response concise but informative.
"""
4.2 Implement the Response Generation Function
Create the main function that calls the AI API:
def generate_ai_response(product_info, buyer_message):
try:
prompt = generate_response_prompt(product_info, buyer_message)
response = client.chat.completions.create(
messages=[
{'role': 'system', 'content': 'You are a helpful marketplace seller responding to buyer inquiries.'},
{'role': 'user', 'content': prompt}
],
**DEFAULT_RESPONSE_PARAMS
)
return response.choices[0].message.content.strip()
except Exception as e:
return f"Error generating response: {str(e)}"
Step 5: Test Your System
5.1 Create Test Cases
Set up test scenarios to validate your implementation:
def test_ai_replier():
# Test inquiry about availability
inquiry1 = "Is this jacket still available?"
response1 = generate_ai_response(sample_product, inquiry1)
print(f"Inquiry: {inquiry1}")
print(f"Response: {response1}\n")
# Test inquiry about price
inquiry2 = "How much does it cost?"
response2 = generate_ai_response(sample_product, inquiry2)
print(f"Inquiry: {inquiry2}")
print(f"Response: {response2}\n")
# Test inquiry about pickup location
inquiry3 = "Where can I pick it up?"
response3 = generate_ai_response(sample_product, inquiry3)
print(f"Inquiry: {inquiry3}")
print(f"Response: {response3}")
5.2 Run the Test
Add the main execution block to run your tests:
if __name__ == '__main__':
test_ai_replier()
Step 6: Enhance with Error Handling and Logging
6.1 Add Comprehensive Error Handling
Improve your system with better error handling:
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Enhanced response generation with logging
def generate_ai_response_enhanced(product_info, buyer_message):
try:
logger.info(f"Generating response for inquiry: {buyer_message[:50]}...")
prompt = generate_response_prompt(product_info, buyer_message)
response = client.chat.completions.create(
messages=[
{'role': 'system', 'content': 'You are a helpful marketplace seller responding to buyer inquiries.'},
{'role': 'user', 'content': prompt}
],
**DEFAULT_RESPONSE_PARAMS
)
ai_response = response.choices[0].message.content.strip()
logger.info("Response generated successfully")
return ai_response
except Exception as e:
logger.error(f"Error generating response: {str(e)}")
return "I'm sorry, I encountered an issue processing your request. Please try again."
6.2 Add Response Validation
Implement basic validation to ensure responses meet requirements:
def validate_response(response):
# Basic validation
if not response or len(response.strip()) < 10:
return False
# Check for common AI response patterns
if 'I cannot' in response.lower() or 'I am unable' in response.lower():
return False
return True
Summary
In this tutorial, you've built an AI-powered messaging system that can automatically generate personalized responses to buyer inquiries based on product information. You've learned key concepts including API integration, prompt engineering, error handling, and system design for automated content generation. This system demonstrates how modern AI can enhance e-commerce experiences by reducing response time while maintaining personalization. The implementation uses OpenAI's GPT models but can be adapted to other LLM providers by modifying the API calls. This foundation can be extended to integrate with actual marketplace APIs, add more sophisticated product data handling, or incorporate additional features like sentiment analysis or multi-language support.



