🔨 In Development — This section is still being developed and may change.
This example shows how to build a sophisticated e-commerce assistant that can help customers find products, get recommendations, and manage orders using Freddy's AI capabilities.
We'll create an e-commerce assistant that:
- Understands natural language product queries
- Provides personalized product recommendations
- Helps with order tracking and management
- Handles customer inquiries and support
- Integrates with inventory and order systems
- Freddy API account with function calling enabled
- E-commerce platform integration (we'll use a mock API)
- Product catalog and inventory data
- Customer order management system
Create functions for product search, recommendations, and order management:
import json
from typing import List, Dict, Optional
from freddy_ecommerce import EcommerceAPI # Your e-commerce integration
class EcommerceFunctions:
def __init__(self, api_key: str):
self.ecommerce = EcommerceAPI(api_key)
def search_products(self, query: str, category: str = None,
min_price: float = None, max_price: float = None,
limit: int = 10) -> Dict:
"""
Search for products based on user query and filters.
Args:
query: Search query (e.g., "wireless headphones")
category: Product category filter
min_price: Minimum price filter
max_price: Maximum price filter
limit: Maximum number of results
Returns:
Dictionary with search results and metadata
"""
try:
results = self.ecommerce.search_products(
query=query,
category=category,
price_range=(min_price, max_price) if min_price or max_price else None,
limit=limit
)
return {
"products": results["products"],
"total_count": results["total"],
"query": query,
"filters_applied": {
"category": category,
"price_range": [min_price, max_price] if min_price or max_price else None
}
}
except Exception as e:
return {"error": f"Search failed: {str(e)}"}
def get_product_details(self, product_id: str) -> Dict:
"""Get detailed information about a specific product."""
try:
product = self.ecommerce.get_product(product_id)
return {
"product": product,
"related_products": self.ecommerce.get_related_products(product_id),
"reviews": self.ecommerce.get_product_reviews(product_id)
}
except Exception as e:
return {"error": f"Failed to get product details: {str(e)}"}
def get_personalized_recommendations(self, customer_id: str,
limit: int = 5) -> Dict:
"""Get personalized product recommendations for a customer."""
try:
recommendations = self.ecommerce.get_recommendations(
customer_id=customer_id,
limit=limit
)
return {"recommendations": recommendations}
except Exception as e:
return {"error": f"Failed to get recommendations: {str(e)}"}
def track_order(self, order_id: str) -> Dict:
"""Track the status of an order."""
try:
order = self.ecommerce.get_order_status(order_id)
return {
"order_id": order_id,
"status": order["status"],
"tracking_number": order.get("tracking_number"),
"estimated_delivery": order.get("estimated_delivery"),
"items": order["items"]
}
except Exception as e:
return {"error": f"Failed to track order: {str(e)}"}
def place_order(self, customer_id: str, items: List[Dict],
shipping_address: Dict, payment_method: str) -> Dict:
"""Place a new order."""
try:
order = self.ecommerce.create_order(
customer_id=customer_id,
items=items,
shipping_address=shipping_address,
payment_method=payment_method
)
return {
"order_id": order["id"],
"status": "confirmed",
"estimated_delivery": order.get("estimated_delivery"),
"total_amount": order["total"]
}
except Exception as e:
return {"error": f"Failed to place order: {str(e)}"}import os
from freddy import Freddy
# Initialize functions
ecommerce_functions = EcommerceFunctions(os.getenv("ECOMMERCE_API_KEY"))
# Create the assistant
assistant = freddy.assistants.create(
name="E-commerce Assistant",
instructions="""You are a helpful e-commerce assistant. Your role is to:
1. Help customers find products they're looking for
2. Provide personalized recommendations based on their preferences
3. Assist with order tracking and management
4. Answer questions about products, shipping, and returns
5. Guide customers through the shopping process
When customers ask about products:
- Ask clarifying questions if the query is too vague
- Provide detailed product information including price, features, and availability
- Suggest related or complementary products
- Be transparent about inventory and shipping times
For orders:
- Help track existing orders
- Assist with placing new orders
- Explain return and exchange policies
- Handle complaints professionally
Always:
- Be friendly and professional
- Use clear, conversational language
- Provide accurate information
- Respect customer privacy
- Follow up on incomplete requests""",
model="gpt-4",
tools=[
{
"type": "function",
"function": {
"name": "search_products",
"description": "Search for products based on user query and filters",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"},
"category": {"type": "string", "description": "Product category"},
"min_price": {"type": "number", "description": "Minimum price"},
"max_price": {"type": "number", "description": "Maximum price"},
"limit": {"type": "integer", "description": "Max results"}
}
}
}
},
{
"type": "function",
"function": {
"name": "get_product_details",
"description": "Get detailed information about a specific product",
"parameters": {
"type": "object",
"properties": {
"product_id": {"type": "string", "description": "Product ID"}
},
"required": ["product_id"]
}
}
},
{
"type": "function",
"function": {
"name": "get_personalized_recommendations",
"description": "Get personalized product recommendations",
"parameters": {
"type": "object",
"properties": {
"customer_id": {"type": "string", "description": "Customer ID"},
"limit": {"type": "integer", "description": "Number of recommendations"}
},
"required": ["customer_id"]
}
}
},
{
"type": "function",
"function": {
"name": "track_order",
"description": "Track the status of an order",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "string", "description": "Order ID"}
},
"required": ["order_id"]
}
}
}
]
)# Create a shopping session
thread = freddy.threads.create()
# Example conversation flow
conversations = [
"Hi! I'm looking for wireless headphones under $100",
"Can you show me more details about the Sony WH-1000XM4?",
"What are some good alternatives in the same price range?",
"I'd like to track my order #12345",
"What's your return policy?"
]
for user_message in conversations:
# Send user message
freddy.threads.messages.create(
thread_id=thread.id,
role="user",
content=user_message
)
# Run assistant
run = freddy.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id
)
# Wait for completion
while run.status not in ["completed", "failed"]:
run = freddy.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)
if run.status == "completed":
messages = freddy.threads.messages.list(thread_id=thread.id)
latest = messages.data[-1]
print(f"Assistant: {latest.content[0].text.value}")def enhance_recommendations_with_ai(customer_preferences: Dict) -> List[Dict]:
"""Use AI to enhance product recommendations based on customer preferences."""
# Analyze purchase history
purchase_history = ecommerce_functions.get_customer_history(customer_id)
# Analyze browsing behavior
browsing_data = ecommerce_functions.get_browsing_behavior(customer_id)
# Generate enhanced recommendations
recommendations = ecommerce_functions.get_personalized_recommendations(
customer_id,
base_preferences=customer_preferences,
purchase_context=purchase_history,
browsing_context=browsing_data
)
return recommendationsdef handle_order_inquiries(order_query: str) -> Dict:
"""Handle various order-related inquiries."""
if "track" in order_query.lower():
# Extract order ID from natural language
order_id = extract_order_id(order_query)
return ecommerce_functions.track_order(order_id)
elif "cancel" in order_query.lower():
order_id = extract_order_id(order_query)
return ecommerce_functions.cancel_order(order_id)
elif "return" in order_query.lower():
return {
"policy": "30-day return policy",
"process": "Contact support or use returns portal",
"requirements": "Original packaging, proof of purchase"
}
else:
return {"error": "Please specify your order inquiry more clearly"}def check_inventory_availability(product_ids: List[str]) -> Dict:
"""Check real-time inventory for products."""
availability = {}
for product_id in product_ids:
stock = ecommerce_functions.check_inventory(product_id)
availability[product_id] = {
"in_stock": stock["available"] > 0,
"quantity": stock["available"],
"backorder_available": stock.get("backorder", False)
}
return availability- Product Search: "Find me red running shoes"
- Price Filtering: "Show me laptops between $800 and $1200"
- Product Details: "Tell me about iPhone 14 Pro"
- Order Tracking: "Where is my order #12345?"
- Recommendations: "What would you recommend for a photographer?"
- Cache product data for frequently searched items
- Implement pagination for large result sets
- Use async functions for multiple API calls
- Monitor and handle rate limits
- Implement fallback responses for API failures
- Natural Language Processing: Design functions that handle various ways customers express needs
- Error Handling: Provide helpful error messages and fallback options
- Privacy: Never expose sensitive customer data
- Scalability: Design for high-volume customer interactions
- Analytics: Track conversation success rates and common failure points
- Monitor API usage and costs
- Implement proper logging for debugging
- Set up alerts for system failures
- Regular updates to product catalog
- A/B testing for response optimization
Functions not called: Ensure function definitions match the assistant's tool configuration exactly.
Poor search results: Fine-tune search algorithms and consider implementing fuzzy matching.
Slow responses: Optimize API calls and consider implementing response caching.
Customer confusion: Improve natural language understanding and provide clearer guidance.
For more help, check the Function Calling Guide or API Reference.