DEV Community

Cover image for Enhancing Culinary Experiences with Firebase and LangChain

Posted on • Updated on

Enhancing Culinary Experiences with Firebase and LangChain

What we are going to do here :

  • Integrate Firebase into our Python app.
  • Demonstrate how to anonymize confidential data and leverage its value with Langchain.
  • Store and post-process the OpenAI results.

With the goal of unlocking the value hidden within the company's data, our aim is to repurpose it and integrate it with OpenAI. The intention is to connect this data to OpenAI, allowing for the extraction of insights and storing the results in a real-time database. This process enables the generation of new data based on the existing information we possess.

In the constantly evolving realm of technology, companies are increasingly using data to create personalized and innovative solutions. This article demonstrates a practical example of combining Firebase, a real-time NoSQL database, with LangChain, a conversational AI language model, to enhance culinary experiences. We will explore the provided code, highlighting the practicality of Firebase and LangChain for managing data, generating insights, and making customized requests to OpenAI.

Image description

As explained by my amazing drawing talent, we have 3 different phases:

  • Pre, where the data is queried from the DB, anonymized, and prepared to be processed.
  • LLM, the request to the OpenAI API.
  • Post, the refinement of the result and storing it in the DB for future uses.

Set on "Fire" the base: Firebase Initialization

Our journey commences with the setup of Firebase. The code utilizes the Firebase Admin SDK to initialize the application with credentials and a database URL. This process is analogous to providing our system with a home and ensuring it knows where to store and retrieve data. In this scenario, the database serves as a centralized hub for culinary preferences, information such as allergies, and customer intolerance at the restaurant.

import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
Enter fullscreen mode Exit fullscreen mode

How to Write to Firebase Realtime Database Using Python
If we want to have a place where we need to fish data and store the result of the openai requests, we need a database, for easy use we use Firebase realtime db.

The immediate next step is to find out how we can connect to our database using Python. We are going to use the Admin Database API. You'll need to install the required library.

For more information on using firebase_admin for Python, check out the official docs linked here.

pip install firebase_admin

Image description

This will generate and download a file that will be used in your python app.

#prepare the firebase env
cred = credentials.Certificate("./bookin.json")
default_app = firebase_admin.initialize_app(cred, {
Enter fullscreen mode Exit fullscreen mode

*Adaptive AI with LangChain: *

The function consultant_chef acts as a culinary advisor, powered by Langchain as a prompt engineering tool for natural language conversations. It takes inputs such as food intolerances, preferred style, and mandatory ingredients. LangChain then crafts a conversation between the system and a hypothetical customer, generating a personalized recipe suggestion.

Firebase: A Data Repository

Firebase isn't just an initialization step; it's the backbone of data management. The code demonstrates how to fill the Firebase database with customer information, including names, intolerances, preferred styles, and desired ingredients. This structured data allows for easy retrieval and manipulation, setting the stage for personalized interactions.

Bringing Data to Life

The code interact with the data storage and brings data to life by generating personalized recipes based on stored preferences opf the customer. It retrieves customer information and uses LangChain to suggest a recipe for a specific customer, such as "Massimo Bottura." This dynamic pairing of data and AI creates a personalized response for each customer.

Customers in Realtime DB Firebase
In this example we try to create a bot that suggests Menu based on the preferences of the existing customers.

We have our customer Massimo Bottura who is intolerant to tomatoes, and his favorite dish is Tortellini, so we are going to propose a Menu tailored around him.

It is fundamental to pay attention to the fact that the name is completely anonymized in the OpenAI request.

As We can see the signature of the method

consultant_chef(intolerances, style, ingredients):
doesn't include the name of the customer or other personal infos that coudl be used to identify him, as age, address, sex, etc.

We are going to take the information of our customer from the DB but we are not trasfering the personal data nowhere.

In this example, we try to create a bot that suggests a menu based on the preferences of existing customers.

It is fundamental to pay attention to the fact that the name is completely anonymized in the OpenAI request.

Final step: Updating the Recipe entries

The final piece of the puzzle involves storing the generated recipes for future uses. The code pushes the resulting recipe to a separate "/Recipes" database within Firebase. This step completes the process, allowing the system to not only provide recommendations but also archive them for future reference or analysis, saving costs in case a similar request were already done in the past.

Here the rest of the code :

def consultant_chef(intolerances, style, ingredients):
        intolerances: The food that the client can't eat
        style: The target style that the client prefer, included if vegetarian
        ingredients: The mandatory ingredients that the client want

    system_template = "You are an experienced cooking michelin chef"
    system_message_prompt = SystemMessagePromptTemplate.from_template(system_template)

    human_template = "For a customer, I would to prepare a meal in a {style} style meal. " \
                     "The recipe should consider that the customer have {intolerances} intolerances and want {ingredients} as ingredients."
    human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)

    chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])

    request = chat_prompt.format_prompt(intolerances=intolerances, style=style, ingredients=ingredients).to_messages()

    chat = ChatOpenAI()
    result = chat(request)
    return result.content

def fillDB():
    ref = db.reference("/Customers")

        "Name": "Massimo Bottura",
        "intolerances": "pomodoro",
        "style": "traditional emiliana cuisine",
        "ingredients": "tortellini"

    return ref

def getDB():
    ref = db.reference("/Customers")
    return ref

# here the result as a Recipe is stored to
def pushFinalRecipe(result_recipe, ingredients):
    ref = db.reference("/Recipes")

            "Title": "Menu per " + customerName,
            "Ingredients": ingredients,
            "Instructions" : result_recipe

# get the customers that need to come for dinner
customer_for_dinner = getDB().get()

ingredients = ""
def createRecipe(name):
    for key, value in customer_for_dinner.items():
        if (value["Name"] == name):
            ingredients = value["ingredients"]
            result_recipe = consultant_chef(value["intolerances"], value["style"], value["ingredients"])
result_recipe = createRecipe(customerName)

pushFinalRecipe(result_recipe, ingredients)
Enter fullscreen mode Exit fullscreen mode

Unlocking Insights for Businesses

This code serves as a practical demonstration of how businesses can utilize Firebase and LangChain to manage customer data efficiently, generate personalized insights, and enhance user experiences. By leveraging the power of AI, companies can turn raw data into actionable recommendations, creating a seamless connection between technology and the culinary world.

Breaking the barrier of the privacy problem, in this way we can use the full potential of the ChatGPT model, without the need to share the confidential data inside the company, no matter their importance, no sharing at all.

In conclusion, this article highlights the synergy between Firebase and LangChain in the realm of culinary consultations. The provided code offers a practical guide for tech-savvy individuals, showcasing the potential of data-driven AI applications.

Top comments (0)