Recommendation and Personalization with LLMs

Recommendation and Personalization with LLMs

Introduction

Language models can be used to build sophisticated recommendation systems and personalized experiences. This tutorial explores the different ways to implement these features with LLMs.

Types of Recommendation

1. Content Recommendation

2. Behavioral Recommendation

3. Contextual Recommendation

Implementation

1. Recommendation System

from openai import OpenAI
import json
from typing import List, Dict, Any
import numpy as np

class RecommendationSystem:
    def __init__(self, api_key: str):
        self.client = OpenAI(api_key=api_key)
    
    def generate_recommendations(self, user_profile: Dict[str, Any], 
                               available_items: List[Dict[str, Any]], 
                               recommendation_type: str = "content") -> List[Dict[str, Any]]:
        prompt = self._create_recommendation_prompt(user_profile, available_items, recommendation_type)
        
        response = self.client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "Tu es un expert en systèmes de recommandation."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.5
        )
        
        return json.loads(response.choices[0].message.content)
    
    def _create_recommendation_prompt(self, user_profile: Dict[str, Any], 
                                    available_items: List[Dict[str, Any]], 
                                    recommendation_type: str) -> str:
        return f"""
        Génère des recommandations {recommendation_type} pour l'utilisateur suivant :
        
        Profil utilisateur : {json.dumps(user_profile, indent=2)}
        Items disponibles : {json.dumps(available_items, indent=2)}
        
        Pour chaque recommandation, fournis :
        1. L'item recommandé
        2. Le score de pertinence
        3. Les raisons de la recommandation
        4. Des alternatives
        
        Réponds au format JSON.
        """