Advanced ChatGPT Apps

icon picker
Sec 4 - Final Project - AI Meal Planner on Cloud

Step-by-Step Guide to Building a Streamlit App for AI-Powered Meal Planning

Creating a user-friendly meal planning application powered by AI can enhance the cooking experience by providing tailored recipe suggestions based on available ingredients, dietary restrictions, and cooking preferences. This guide details the development of the "Detikfood Meal Prep Planner," a Streamlit web application integrated with OpenAI's GPT-3.5-turbo model.

Step 1: Set Up Your Development Environment

Install Necessary Libraries:
Install Streamlit and any necessary libraries by running:
pip install streamlit streamlit_tags openai
Import Libraries:
Start your Python script by importing the required modules:
import os
import streamlit as st from streamlit_tags
import st_tags
import openai

Step 2: Configure OpenAI API

API Key:
Set up your OpenAI API key. It is critical for authenticating your requests to the GPT-3.5-turbo API.
openai.api_key = "your_openai_api_key_here"

Step 3: Define the AI Interaction Function

Create the Function to Interact with GPT-3.5-turbo:
Define a function that constructs the prompt from user inputs and sends it to the AI model:
python
Copy code
def ask_gpt3_turbo(message): response = openai.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are an AI agent acting as a skilled chef who can create recipes from limited ingredients, specializing in Indonesian and regional cuisines."}, {"role": "user", "content": message}, ] ) return response['choices'][0]['message']['content']

Step 4: Build the Streamlit User Interface

Define the Main Function:
Code the main function where you'll design the user interface and handle interactions:
python
Copy code
def main(): st.title("Detikfood Meal Prep Planner")
User Input Fields:
Implement various input fields to collect user data:
bahan = st_tags(label="List the ingredients you have:") daerah = st.text_input("Are you looking for regional recipes? (e.g., Java, Sumatra, Bali)") # Add other inputs similarly
Recipe Request Button:
Add a button that users click to generate recipes based on their inputs:
if st.button("Generate Recipes"): ai_response = ask_gpt3_turbo(construct_prompt(...)) st.markdown(ai_response, unsafe_allow_html=True)

Step 5: Run and Test Your Application

Execute the App:
Save your script and run your Streamlit application by typing in your terminal:
streamlit run your_script_name.py
Interact and Debug:
Open the provided local URL in your web browser to view and interact with your application. Ensure all functionalities work as expected and make any necessary adjustments.

Step 6: Deployment

Deploy Your App:
Consider deploying your app on platforms like Heroku, AWS, or Google Cloud to make it accessible online. Follow the specific guidelines provided by these platforms for deploying Streamlit apps.
This guide outlines creating an interactive, AI-powered meal planning application using Streamlit and OpenAI's GPT-3.5-turbo. By following these steps, you can build a functional tool that offers customized cooking solutions, making meal preparation easier and more enjoyable.

Prompt

The prompt construction in the "Detikfood Meal Prep Planner" application plays a crucial role in defining the interaction between the user and the AI model, specifically OpenAI's GPT-3.5-turbo. The prompt essentially sets the stage for how the AI will understand and respond to the user's request for meal suggestions based on their inputs. Here's a step-by-step breakdown of how the prompt is structured and its function within the application:

Understanding the Prompt Structure

1. Prompt Definition

The prompt is a structured text input that is sent to the AI model. It includes instructions and criteria that guide the AI in generating content—in this case, meal recipes. This prompt is formulated based on user input, which includes ingredients, meal types, dietary preferences, and more.

2. User Inputs Considered in the Prompt

Ingredients: The user lists the ingredients they have available.
Prepared Meals: What meals the user has already cooked.
Regional Cuisine Preferences: Specific regional cuisines the user is interested in (e.g., Java, Sumatra).
Child-Friendly Options: Whether the meals should be suitable for children.
Dietary Restrictions: Including any religious or cultural dietary restrictions (e.g., halal, vegetarian).
Recipe Complexity: Whether the user prefers simple and quick recipes or more complex ones.
Cooking Methods: Preferred methods of cooking like frying, boiling, or grilling.
Meal Type: Whether the meal is for breakfast, lunch, or dinner.
Portion Size: How many people the meal will serve.

3. AI Instructions Included in the Prompt

The system role sets up the AI’s character as an expert chef knowledgeable in Indonesian and regional cuisines, capable of suggesting recipes from limited ingredients. This background helps the AI tailor its responses more effectively.

4. Example of a Constructed Prompt

Here’s how the user's inputs might be transformed into a detailed prompt for the AI:
Buatkan saya 3 resep masakan berbeda berdasarkan kriteria berikut ini, perlu dicatat anda tidak perlu memakai semua bahan untuk satu resep, anda bisa menambahkan bumbu-bumbu dasar pada resep, dan anda bisa menggunakan alat dapur dasar dalam proses masak.

Bahan-bahan: [user-provided ingredients]
Makanan yang sudah saya siapkan: [prepared meals]
Jenis masakan daerah: [regional cuisine preference]
Opsi ramah anak: [child-friendly option]
Pertimbangan agama/budaya: [dietary restrictions]
Kesederhanaan resep: [recipe complexity]
Metode memasak: [cooking methods]
Jenis makanan: [meal type]
Porsi: [portion size] orang

Format output:
#[Nama Resep]
##Bahan-Bahan:
[ingredients list]

##Cara Memasak:
[cooking instructions]

##Cara penyajian:
[serving instructions]

Function of the Prompt in AI Interaction

The prompt directs the AI on how to process the user's data and what kind of response to generate. By structuring the prompt with clear instructions and contextual details, the AI can produce more relevant and practical recipes. This structured approach ensures the AI understands the user's needs and culinary context, which is essential for generating customized and creative meal ideas.

Full Code

import streamlit as st
from streamlit_tags import st_tags
import openai

# flake8: noqa
# Set the OpenAI API key
openai.api_key = "sk-proj-IIzp0SNx3rAuwPPSCax4T3BlbkFJFrK7NpFaZuH7lIqjxbTN"


# Define the function to call GPT-3.5-turbo API
def ask_gpt3_turbo(message, chat_log=None):
response = openai.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "system",
"content": "Anda adalah AI agent yang bertindak sebagai chef andal yang bisa memikirikan resep makan dari bahan-bahan yang terbatas. Anda adalah chef yang sangat ahli dalam masakan Indonesia dan nusantara.",
},
{"role": "user", "content": message},
],
)
# Returning the response
return response.choices[0].message.content


# Streamlit app
def main():
st.title("Detikfood Meal Prep Planner")

bahan = st_tags(label="Daftarkan bahan-bahan di dapur Anda")
makanan = st_tags(
label="(optional) Sebutkan makanan apa saja yang sudah Anda masak"
)
daerah = st.text_input(
"(optional) Anda mencari resep khas daerah mana? (Misalnya: Jawa, Sumatera, Bali)"
)
ramah_anak = st.radio("Opsi makanan ramah anak", ("Tidak", "Ya"))
agama_budaya = st.text_input(
"(optional) Apakah Anda memiliki batasan seperti halal atau vegetarian?"
)
kompleks = st.radio(
"Anda mencari resep yang sederhana dan cepat atau yang lebih kompleks?",
("Sederhana dan cepat", "Kompleks"),
)
metode = st.multiselect("Preferensi metode memasak", ["goreng", "rebus", "bakar"])
jenis = st.radio(
"Anda mencari resep untuk?", ("sarapan", "makan siang", "makan malam")
)
porsi = st.number_input(
"Untuk berapa orang Anda akan memasak?", min_value=1, max_value=5, step=1
)

if st.button("Kirim"):

prompt = f"""
Buatkan saya 3 resep masakan berbeda berdasarkan kriteria berikut ini, perlu dicatat anda tidak perlu memakai semua bahan untuk satu resep, anda bisa menambahkan bumbu-bumbu dasar pada resep, dan anda bisa menggunakan alat dapur dasar dalam proses masak.

Bahan-bahan: {bahan}
Makanan yang sudah saya siapkan: {makanan}
Jenis masakan daerah: {daerah}
Opsi ramah anak: {ramah_anak}
Pertimbangan agama/budaya: {agama_budaya}
Kesederhanaan resep: {kompleks}
metode memasak: {metode}
jenis makanan: {jenis}
porsi: {porsi} orang

Format output:
#[Nama Resep]
##Bahan-Bahan:
[konten]

##Cara Memasak:
[konten]

##Cara penyajian:
[konten]
"""

# user_input += additional_prompt
ai_response = ask_gpt3_turbo(prompt)

# print(ai_response)
st.markdown(f"{ai_response}", unsafe_allow_html=True)


if __name__ == "__main__":
main()

Requirements

Put in requirements.txt
streamlit
streamlit-tags
openai
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.