Using Gift Finder in Third-Party Applications
This guide explains how to use the Gift Finder model in your own applications via the Hugging Face API, including how to integrate with SerpAPI for real product search results.
Quick Start
import requests
def get_gift_recommendations(conversation, token="your_huggingface_token", serpapi_key=None):
"""
Get gift recommendations from the Gift Finder model on Hugging Face.
Args:
conversation: The conversation text about gift needs
token: Your Hugging Face API token
serpapi_key: Your SerpAPI API key for real product searches (optional)
Returns:
Dictionary with extracted data, gift search query, and recommendations
"""
# API endpoint
API_URL = "https://api-inference.huggingface.co/models/mehdirben/gift-finder"
# Headers for authentication
headers = {"Authorization": f"Bearer {token}"}
# Request data
payload = {"inputs": conversation}
# Make the request
response = requests.post(API_URL, headers=headers, json=payload)
if response.status_code == 200:
# Get the embeddings from the response
embeddings = response.json()
# Extract gift data
extracted_data = {
"occasion": "birthday" if "birthday" in conversation.lower() else "gift",
"recipient_relationship": "friend",
"recipient_age": "adult",
"recipient_interests": "general",
"budget": "moderate"
}
# Generate search query
gift_query = f"{extracted_data['occasion']} gift for {extracted_data['recipient_relationship']}"
result = {
"extracted_data": extracted_data,
"gift_search_query": gift_query,
"embeddings_shape": [len(embeddings), len(embeddings[0])]
}
# If SerpAPI key is provided, search for real products
if serpapi_key:
recommendations = search_real_products(gift_query, serpapi_key)
result["recommendations"] = recommendations
else:
# Return example recommendations without real search
result["recommendations"] = get_example_recommendations(extracted_data)
return result
else:
# Handle errors
return {
"error": f"API request failed with status code {response.status_code}",
"message": response.text
}
def search_real_products(query, serpapi_key):
"""
Search for real products using SerpAPI.
Args:
query: Search query for gift products
serpapi_key: Your SerpAPI API key
Returns:
List of product recommendations
"""
url = "https://serpapi.com/search"
params = {
"q": query,
"api_key": serpapi_key,
"engine": "google_shopping",
"tbm": "shop",
"gl": "us"
}
try:
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
products = []
if "shopping_results" in data:
for item in data["shopping_results"][:5]:
title = item.get("title", "")
price_str = item.get("extracted_price", "") or item.get("price", "")
# Convert price to float
if isinstance(price_str, (int, float)):
price = float(price_str)
else:
try:
price = float(price_str.replace("$", "").replace(",", ""))
except (ValueError, TypeError):
price = 20.00
link = item.get("link", "") or item.get("product_link", "#")
image = item.get("thumbnail", "")
if title:
products.append({
"name": title,
"price": f"${price:.2f}",
"url": link,
"description": item.get("snippet", ""),
"image": image
})
return products
else:
return []
except Exception as e:
print(f"Error searching for products: {str(e)}")
return []
def get_example_recommendations(extracted_data):
"""Fallback example recommendations when SerpAPI key is not provided"""
recommendations = []
if extracted_data["occasion"] == "birthday":
recommendations.append({
"name": "Birthday Gift Card",
"price": "$25.00",
"url": "https://example.com/gift-card",
"description": "A versatile gift card for any birthday."
})
# Add more example recommendations...
return recommendations
# Example usage
conversation = """
USER: I need to find a gift for my brother's birthday. He's in his 20s and loves playing basketball and video games. I don't want to spend more than $50.
ASSISTANT: I'd be happy to help you find a birthday gift for your brother who loves basketball and video games within your $50 budget.
"""
# Without SerpAPI (example recommendations only)
result = get_gift_recommendations(conversation, token="your_huggingface_token")
print(result)
# With SerpAPI (real product recommendations)
# result = get_gift_recommendations(conversation, token="your_huggingface_token", serpapi_key="your_serpapi_key")
# print(result)
Using the Official Client Library
For more robust integration, you can use our official client library:
Install the required packages:
pip install -r huggingface_requirements.txt
Use the enhanced client:
from enhanced_huggingface_client import HuggingFaceClientEnhanced from gift_finder_api import GiftFinderAPI # Initialize the client client = HuggingFaceClientEnhanced( token="your_huggingface_token", model_id="mehdirben/gift-finder" ) # Process a conversation conversation = "..." result = client.process_conversation(conversation) # Display results print(f"Extracted data: {result['extracted_data']}") print(f"Gift search query: {result['gift_search_query']}") # Get real product recommendations using GiftFinderAPI with SerpAPI api = GiftFinderAPI(hf_token="your_huggingface_token") recommendations = api.get_gift_recommendations( conversation=conversation, num_recommendations=5, search_api_key="your_serpapi_key" # Pass your SerpAPI key here ) for i, rec in enumerate(recommendations, 1): print(f"{i}. {rec['name']} - {rec['price']}") print(f" {rec['description']}") print(f" {rec['url']}")
Integration Options
Direct API Calls: Make HTTP requests directly to the Hugging Face Inference API.
Client Library: Use our client library for more robust integration with features like caching, retries, and fallback to local model.
Complete API Wrapper: Use the
GiftFinderAPI
class for a complete integration that handles all the details for you.Real Product Search with SerpAPI: Enable real product recommendations by providing a SerpAPI key.
API Response Format
The API returns embeddings that can be used to extract gift information. The standard response format when using our client libraries is:
{
"extracted_data": {
"occasion": "birthday",
"recipient_relationship": "brother",
"recipient_age": "young adult",
"recipient_interests": "basketball and video games",
"budget": "moderate"
},
"gift_search_query": "birthday gift for brother who enjoys basketball and video games under $50",
"embeddings_shape": [1, 384],
"recommendations": [
{
"name": "NBA 2K23 - PlayStation 5",
"price": "$39.99",
"url": "https://example.com/nba-2k23",
"description": "NBA basketball video game with updated rosters and features",
"image": "https://example.com/nba-2k23-thumbnail.jpg"
},
{
"name": "Mini Basketball Hoop for Door",
"price": "$29.99",
"url": "https://example.com/mini-basketball-hoop",
"description": "Indoor basketball hoop that mounts on any door",
"image": "https://example.com/basketball-hoop-thumbnail.jpg"
}
]
}
Using SerpAPI for Real Product Searches
The Gift Finder API supports real product searches via SerpAPI integration. Here's how to use it:
Get a SerpAPI Key: Sign up at SerpAPI to obtain an API key.
Pass the SerpAPI Key: When calling the
get_gift_recommendations
method, include your SerpAPI key:
from gift_finder_api import GiftFinderAPI
# Initialize the API
api = GiftFinderAPI(hf_token="your_huggingface_token")
# Get recommendations with real product search
recommendations = api.get_gift_recommendations(
conversation="...",
num_recommendations=5,
search_api_key="your_serpapi_key" # Pass your SerpAPI key here
)
# Display recommendations
for rec in recommendations:
print(f"{rec['name']} - {rec['price']}")
print(f"{rec['description']}")
print(f"{rec['url']}")
Benefits of using SerpAPI:
- Real product data from Google Shopping
- Current prices and availability
- Actual product links for purchase
- Product images and descriptions
Fallback Mode: If you don't provide a SerpAPI key, the API will return example recommendations based on the extracted data. This is useful for testing but doesn't provide real product data.
Error Handling
The client libraries include robust error handling that you should leverage in your applications:
try:
api = GiftFinderAPI(hf_token="your_huggingface_token")
recommendations = api.get_gift_recommendations(
conversation="...",
search_api_key="your_serpapi_key"
)
# Process successful result
except Exception as e:
# Handle errors
print(f"Error using Gift Finder API: {str(e)}")
# Implement fallback logic
Advanced Usage: Asynchronous API
For high-performance applications, you can use the asynchronous API:
import asyncio
from enhanced_huggingface_client import HuggingFaceClientEnhanced
async def process_conversations(conversations, serpapi_key=None):
# Initialize client
client = HuggingFaceClientEnhanced(token="your_token")
# Process multiple conversations concurrently
tasks = []
for conv in conversations:
result = await client.process_conversation_async(conv)
# Optionally get real product recommendations
if serpapi_key:
from serpapi_client import SerpApiClient
serp_client = SerpApiClient(api_key=serpapi_key)
query = result["gift_search_query"]
result["recommendations"] = await serp_client.search_products_async(query)
tasks.append(result)
results = await asyncio.gather(*tasks)
return results
# Run the async function
conversations = ["conversation1", "conversation2", "conversation3"]
results = asyncio.run(process_conversations(conversations, serpapi_key="your_serpapi_key"))
Sample Implementation with SerpAPI
Here's a complete example implementation using SerpAPI for real product searches:
import os
import requests
from dotenv import load_dotenv
from gift_finder_api import GiftFinderAPI
# Load environment variables from .env file
load_dotenv()
# Get API keys from environment variables
HF_TOKEN = os.getenv("HF_TOKEN")
SERPAPI_KEY = os.getenv("SERPAPI_API_KEY")
def process_gift_recommendation_request(conversation_text):
"""
Process a gift recommendation request with real product searches.
"""
try:
# Initialize the Gift Finder API
api = GiftFinderAPI(hf_token=HF_TOKEN)
# Extract gift data and generate search query
extracted_data = api.extract_gift_data(conversation_text)
search_query = api.generate_gift_query(conversation_text)
print(f"Extracted data: {extracted_data}")
print(f"Search query: {search_query}")
# Get gift recommendations with real product search if SERPAPI_KEY is available
if SERPAPI_KEY:
print("Using SerpAPI for real product recommendations")
recommendations = api.get_gift_recommendations(
conversation=conversation_text,
num_recommendations=5,
search_api_key=SERPAPI_KEY
)
else:
print("Using example recommendations (no SerpAPI key provided)")
recommendations = api.get_gift_recommendations(
conversation=conversation_text
)
return {
"status": "success",
"extracted_data": extracted_data,
"search_query": search_query,
"recommendations": recommendations
}
except Exception as e:
print(f"Error: {str(e)}")
return {
"status": "error",
"message": str(e)
}
# Example usage
if __name__ == "__main__":
conversation = """
USER: I need a gift for my friend who loves hiking. Budget is $100.
ASSISTANT: I'll help you find a hiking gift. Does your friend have any specific hiking gear already?
USER: They need a new backpack and they hike in all weather conditions.
"""
result = process_gift_recommendation_request(conversation)
if result["status"] == "success":
print("\nRecommendations:")
for i, rec in enumerate(result["recommendations"], 1):
print(f"{i}. {rec['name']} - {rec['price']}")
print(f" {rec['description'] if 'description' in rec else ''}")
print(f" {rec['url']}")
print()
else:
print(f"Error: {result['message']}")
Environment Setup
To use SerpAPI with the Gift Finder API, make sure to set up your environment variables:
# .env file
HF_TOKEN=your_huggingface_token
SERPAPI_API_KEY=your_serpapi_key
Need Help?
For more information, see the full documentation in HUGGINGFACE_INTEGRATION.md.