/how-to-build-lovable

How to build Recommendations engine with Lovable?

Learn how to build a powerful recommendations engine with Lovable. Follow our step-by-step guide to boost personalization and user engagement.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to build Recommendations engine with Lovable?

 
Prerequisites
 

  • A Lovable account to create and manage your projects.
  • Basic familiarity with Python programming.
  • An understanding of how recommendation systems determine matches based on user interests.

 
Setting Up Your Lovable Project
 

  • Log into your Lovable account and create a new project. Name it something like "RecommendationsEngine".
  • Within the project, you will have the main code editor where you can add or modify files.

 
Adding Dependencies
 

  • Since Lovable does not offer a terminal, you need to install dependencies by adding installation commands directly into your main code file.
  • Add the following code snippet at the very top of your main file (e.g., main.py) to install required packages (for example, numpy and pandas):
    • 
      import pip
      pip.main(['install', 'numpy'])   # Install numpy for numerical operations
      pip.main(['install', 'pandas'])   # Install pandas to manage data structures
            
  • If your recommendation logic requires additional libraries, add similar pip installation commands for them.

 
Creating the Recommendation Engine Module
 

  • Create a new file within your Lovable project and name it recommendations.py. This file will encapsulate the recommendation engine logic.
  • In recommendations.py, insert the following code snippet which defines a simple recommendation function:
    • 
      def get_recommendations(user_profile, items):
          recommended = []
          # Loop through each item and check if the item's category is in the user's interests
          for item in items:
              if item.get('category') in user\_profile.get('interests', []):
                  recommended.append(item)
          return recommended
            
  • This function assumes a user profile structured with an "interests" key and items that include a "category" key. Adjust the logic as needed.

 
Integrating the Recommendation Engine in Your Main Code
 

  • Open your main file (e.g., main.py) where you want to use the recommendation engine.
  • Import the recommendation function from recommendations.py and add the example testing code. Insert the following snippet in your main file at the desired location:
    • 
      from recommendations import get\_recommendations
      
      

      Example user profile with interests

      user_profile = {
      'id': 1,
      'name': 'Alice',
      'interests': ['technology', 'books']
      }

      Example list of items with categories

      items = [
      {'id': 101, 'name': 'Smartphone', 'category': 'technology'},
      {'id': 102, 'name': 'Novel', 'category': 'books'},
      {'id': 103, 'name': 'Cooking Set', 'category': 'home'},
      ]

      Obtain recommendations based on user interests

      recommended_items = get_recommendations(user_profile, items)
      print("Recommended Items:", recommended_items)




  • This snippet sets up a sample user and items, calls the function, and prints the recommended items to Lovable’s output console.

 
Testing Your Recommendation Engine
 

  • Save all your changes in Lovable.
  • Click the Run button to execute your project. The output console should display the recommended items based on the example data provided.
  • Modify the user profile or items list as needed to test different scenarios.

 
Deploying Your Recommendations Engine
 

  • Once you are satisfied with the functionality, save your changes.
  • Share your project’s URL provided by Lovable with others so they can access and benefit from your recommendation engine.
  • If you need to update or refine the logic, simply adjust the code in recommendations.py and main.py, then run again.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

How to build a Recommendations Engine with Lovable using Node.js and Express


const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());

// Calculate similarity between two users based on their preferences
function calculateSimilarity(userA, userB) {
  let similarity = 0;
  const keys = Object.keys(userA.preferences);
  keys.forEach(key => {
    if (userB.preferences[key] !== undefined) {
      similarity += 1 / (1 + Math.abs(userA.preferences[key] - userB.preferences[key]));
    }
  });
  return similarity;
}

// Generate recommendations for a given user based on what similar users loved
function getRecommendations(userId, users, items) {
  const currentUser = users.find(user => user.id === userId);
  if (!currentUser) return [];

  // Score items based on similar users' preferences and loves
  const itemScores = {};
  users.forEach(otherUser => {
    if (otherUser.id !== userId) {
      const similarity = calculateSimilarity(currentUser, otherUser);
      otherUser.lovedItems.forEach(itemId => {
        // Only consider items not already loved by current user
        if (!currentUser.lovedItems.includes(itemId)) {
          itemScores[itemId] = (itemScores[itemId] || 0) + similarity;
        }
      });
    }
  });

  // Sort items based on their score and return top 5 recommendations
  return Object.entries(itemScores)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 5)
    .map(([itemId]) => items.find(item => item.id === parseInt(itemId)));
}

// Example in-memory data structure for users and items
const users = [
  { id: 1, preferences: { romance: 8, action: 2 }, lovedItems: [101, 102] },
  { id: 2, preferences: { romance: 7, action: 3 }, lovedItems: [102, 103] },
  { id: 3, preferences: { romance: 5, action: 9 }, lovedItems: [104, 105] }
];

const items = [
  { id: 101, name: 'Love in Paris' },
  { id: 102, name: 'Romantic Getaway' },
  { id: 103, name: 'Charming Nights' },
  { id: 104, name: 'Action Blast' },
  { id: 105, name: 'Explosive Tales' },
  { id: 106, name: 'Unexpected Journey' }
];

// API endpoint to get recommended items for a user
app.get('/api/recommendations/:userId', (req, res) => {
  const userId = parseInt(req.params.userId, 10);
  const recommendations = getRecommendations(userId, users, items);
  res.json({ userId, recommendations });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

How to Build an Enhanced Recommendations Engine with Lovable


const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());

const users = [
  { id: 1, preferences: { adventure: 9, drama: 4 }, likedItems: [201, 202] },
  { id: 2, preferences: { adventure: 7, drama: 6 }, likedItems: [202, 203] },
];

const items = [
  { id: 201, name: 'Jungle Quest' },
  { id: 202, name: 'City Lights' },
  { id: 203, name: 'Sailing Dreams' },
  { id: 204, name: 'Mystery Tales' },
];

// Basic recommendation logic: return items not already liked by the user.
function basicRecommendations(userId) {
  const user = users.find(u => u.id === userId);
  if (!user) return [];
  return items.filter(item => !user.likedItems.includes(item.id));
}

// Function to fetch external sentiment score for an item to adjust its ranking
async function fetchExternalSentiment(itemId) {
  try {
    const response = await axios.get(`https://api.external-service.com/sentiment/${itemId}`);
    return response.data.score; // Assume API returns { score: number }
  } catch (error) {
    return 0;
  }
}

// API endpoint: enhanced recommendations merging internal logic with external sentiment scoring
app.get('/api/enhanced-recommendations/:userId', async (req, res) => {
  const userId = parseInt(req.params.userId, 10);
  const recs = basicRecommendations(userId);
  const enhancedRecommendations = await Promise.all(
    recs.map(async (item) => {
      const sentimentScore = await fetchExternalSentiment(item.id);
      return { ...item, sentimentScore };
    })
  );
  // Sort by external sentiment score descending
  enhancedRecommendations.sort((a, b) => b.sentimentScore - a.sentimentScore);
  res.json({ userId, recommendations: enhancedRecommendations });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});

How to build your personalized recommendation engine with Lovable


const express = require('express');
const app = express();
app.use(express.json());

// In-memory dataset simulating users and items
const users = [
  { id: 1, tastes: { comedy: 5, drama: 3, horror: 1 }, lovedItems: [1, 2] },
  { id: 2, tastes: { comedy: 4, drama: 4, horror: 2 }, lovedItems: [3, 2] },
  { id: 3, tastes: { comedy: 1, drama: 5, horror: 4 }, lovedItems: [4, 5] }
];

const items = [
  { id: 1, title: 'Laugh Out Loud', genres: ['comedy'] },
  { id: 2, title: 'Deep Emotions', genres: ['drama'] },
  { id: 3, title: 'Stand-Up Special', genres: ['comedy'] },
  { id: 4, title: 'Night Terrors', genres: ['horror'] },
  { id: 5, title: 'Epic Tragedy', genres: ['drama'] },
  { id: 6, title: 'Odd Blend', genres: ['comedy', 'horror'] }
];

// Compute cosine similarity between two users' taste profiles
function computeCosineSimilarity(tasteA, tasteB) {
  const keys = Object.keys(tasteA);
  let dot = 0, normA = 0, normB = 0;
  keys.forEach(key => {
    const a = tasteA[key] || 0;
    const b = tasteB[key] || 0;
    dot += a \* b;
    normA += a \* a;
    normB += b \* b;
  });
  return normA && normB ? dot / (Math.sqrt(normA) \* Math.sqrt(normB)) : 0;
}

// POST endpoint for personalized recommendations using Lovable techniques
app.post('/api/lovable-recommendation', (req, res) => {
  const { userId } = req.body;
  const currentUser = users.find(u => u.id === userId);
  if (!currentUser) return res.status(404).json({ error: 'User not found' });

  // Find similarity scores with other users
  const similarityScores = users
    .filter(u => u.id !== userId)
    .map(u => ({ id: u.id, score: computeCosineSimilarity(currentUser.tastes, u.tastes) }))
    .sort((a, b) => b.score - a.score);

  // Choose the most similar user as a basis for recommendations
  const similarUser = users.find(u => u.id === similarityScores[0].id);

  // Recommend items: those loved by the similar user that the current user hasn't loved,
  // and sharing at least one genre with any item the similar user loved.
  const recommendations = items.filter(item => {
    if (currentUser.lovedItems.includes(item.id)) return false;
    const matches = similarUser.lovedItems.some(lovedId => {
      const lovedItem = items.find(i => i.id === lovedId);
      return lovedItem && lovedItem.genres.some(genre => item.genres.includes(genre));
    });
    return matches;
  }).map(item => {
    // Enhance recommendation with a score based on user's tastes matching the movie's genres
    const enhancedScore = item.genres.reduce((sum, genre) => sum + (currentUser.tastes[genre] || 0), 0);
    return { ...item, enhancedScore };
  });

  // Return recommendations sorted by the enhanced score in descending order
  recommendations.sort((a, b) => b.enhancedScore - a.enhancedScore);
  res.json({ userId, recommendations });
});

const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
  console.log(`Recommendation engine running on port ${PORT}`);
});

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

Best Practices for Building a Recommendations engine with AI Code Generators

 
Understanding Recommendation Engines and AI Code Generators
 

  • This guide explains how to build a recommendation engine using AI Code Generators in simple terms.
  • A recommendation engine suggests items (like movies, products, or songs) based on user preferences.
  • AI Code Generators are tools that help generate programming code using artificial intelligence, making development easier—even for those without a technical background.

 
Setting Up Your Development Environment
 

  • Make sure you have a computer with internet access.
  • Install Python from the official website (python.org), as it is a popular language used in AI applications.
  • Download a code editor such as Visual Studio Code, which makes writing and testing code easier.
  • Create an account on an online AI Code Generator platform if you plan to use one for assistance.

 
Collecting and Preparing Data
 

  • Your recommendation engine works with data. This could be user information, product details, or interaction history.
  • Gather data from reliable sources like databases, CSV files, or public datasets.
  • Clean the data by removing duplicates and errors. Tools like Excel or basic Python scripts can help with this process.
  • Organize your data into a structured format (for example, a table with users as rows and items as columns).

 
Creating Your First Recommendation Model
 

  • Start by creating a simple recommendation model using Python. The AI Code Generator can help you write code if needed.
  • We will use a simple similarity approach to recommend items based on user behavior.
  • Below is an example code snippet that calculates similarity between users using a popular Python library:

import pandas as pd
from sklearn.metrics.pairwise import cosine\_similarity

# Sample data: Rows represent users and columns represent items (1 means interest, 0 means no interest)
data = {
    'item\_A': [1, 0, 1],
    'item\_B': [0, 1, 1],
    'item\_C': [1, 1, 0]
}
user_item_matrix = pd.DataFrame(data, index=['User1', 'User2', 'User3'])

# Calculate cosine similarity between users
similarity_matrix = cosine_similarity(user_item_matrix)
similarity_df = pd.DataFrame(similarity_matrix, index=user_item_matrix.index, columns=user_item_matrix.index)
print(similarity\_df)
  • This code reads your user-item interactions, computes how similar users are based on their interests, and prints out a similarity matrix.

 
Integrating AI Code Generators
 

  • AI Code Generators can help you write more complex parts of the engine faster. For example, when you need to add new features or optimize the existing code.
  • Simply describe what you want to achieve (for instance, "generate a function to filter recommendations based on similarity scores") and the AI tool will produce code for you.
  • Review the generated code to ensure it fits your requirements and integrates well with your model.

 
Evaluating and Improving Your Model
 

  • Test your recommendation engine by providing sample input data and observing the output recommendations.
  • Use simple evaluation metrics such as precision and recall, or ask users for feedback to see if the recommendations are helpful.
  • Based on feedback and results, use the AI Code Generator to help make adjustments or enhancements in the model.

 
Integrating the Recommendation Engine into Your Application
 

  • Once your recommendation engine is working as expected, integrate it into your main application.
  • This might involve connecting the engine to a website or mobile app where users can see personalized suggestions.
  • Ensure your code is modular so that the recommendation engine works as an independent component that can be updated without affecting the rest of your application.

 
Best Practices for Building a Scalable Engine
 

  • Keep your code clean and well-documented. This will help you and any collaborators understand your work at any time.
  • Automate repetitive tasks, such as data cleaning or model evaluation, using scripts or AI Code Generators.
  • Plan for future growth by designing your system to handle increasing amounts of data and users.
  • Regularly back up your data and code to prevent loss during development.

 
Maintenance and Monitoring
 

  • Monitor the performance of your recommendation engine to ensure that it continues to provide valuable suggestions.
  • Set up logging to record errors or unexpected behavior during operation.
  • Carry out regular updates and improvements. Use AI Code Generators to facilitate quick fixes and new features.
  • Engage with users to receive feedback, which will guide future improvements.

 
Conclusion
 

  • This guide provided a step-by-step overview of building a recommendation engine with the help of AI Code Generators.
  • Following these best practices will help you create a powerful and maintainable system even if

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022