Kush1's picture
Update src/streamlit_app.py
7841fdd verified
import streamlit as st
import pandas as pd
from langchain.tools import BaseTool
from typing import Optional, Type
from pydantic import BaseModel, Field
import os
import getpass
df = pd.read_csv(r"src/Dataset .csv")
#os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter OpenAI API Key: ")
# Initialize the Chat
def initialize_conversation():
system_message = """You are a Restaurant Recommendation Agent. You will help users find restaurants based on their preferences.
Use ONLY the information provided in the given context or dataset.
Dont use any other dataset on which model was trained.
You have to ask the user questions to understand their preferences better.
If the user asks for a restaurant recommendation, you should respond with a restaurant name and its details from the dataset.
If you do not have enough information, ask the user more questions to gather details about their preferences.
Your final objective to find preferences from user like ('Cusines', 'Location', 'Budget', 'Rating', 'Currency')
Do not make up any restaurant names or details. Only use the information available in the dataset.
#####
If user mention budget then you have to check Average Cost for two column in dataset and then you have to map it with Price range column
Budget to Price range mapping:
Budget < 300 : Price range 1
300 <= Budget < 700 : Price range 2
700 <= Budget < 1500 : Price range 3
Budget >= 1500 : Price range 4
#####
Convert Budget into Price range.
Convert Currency Symbol to complete Currency Name
6. Once you have all the required information, filter the dataset based on the user's preferences and recommend a restaurant that best matches their criteria.
7. Return only Restaruant Names and its details in json format.
#####
First fetch all preferences from user query in json key-pair like {'cusine': 'value', 'location':'value','rating':'value', 'price_range':'value'}
Check Intent from provide user preferences using this query.
if intent_check is True, then go for fetching restaurant details using this query
else ask some more details for restaurant preferences
#####
#####
Before returning final ouput to user Validate the restaurant name from the dataset.If False, then No Restaurant Found For above preferences.
#####
Return Values from dataset only without changing it or searching from other sources. Only given source is allowed for retierval. Otherwise, heavy penality will be given.
#####
Use the following format for your responses:
User: [User's message]
Assistant: [Your response]
7. If user says thank you or anything similar then you have to respond with "You're welcome! If you have any more questions or need further assistance, feel free to ask. Enjoy your meal!"
"""
conversation = [
{"role": "system", "content": system_message}
]
return conversation
def check_intent(json_query):
print(json_query)
json_data = json_query
#json_data = json.loads(json_query)
if str(json_data.get('cuisine')) is not None and str(json_data.get('location')) is not None:
return True
else:
return False
import json
def get_restaurants_details(query_json):
query_json = json.loads(query_json)
print(query_json)
cusines = str(query_json.get('cusine'))
location = str(query_json.get('location'))
budget = str(query_json.get('price_range'))
rating = str(query_json.get('rating'))
currency = str(query_json.get('currency'))
# Convert relevant columns to string type for filtering
df['Cuisines'] = df['Cuisines'].astype(str)
df['City'] = df['City'].astype(str)
df['Price range'] = df['Price range'].astype(str)
df['Aggregate rating'] = df['Aggregate rating'].astype(str)
df['Currency'] = df['Currency'].astype(str)
is_intent = check_intent(query_json)
if not is_intent:
return 'Ask some more details/preferences for Restaurant from users'
else:
result = df.loc[(df['Cuisines'].str.contains(cusines)) |
(df['City'].str.contains(location)) |
(df['Price range'].str.contains(budget)) |
(df['Aggregate rating'].str.contains(rating))
].values
print(result)
return result
class fetch_restaurant_tool(BaseTool):
name: str = "Fetch Restaurant" # Removed trailing space
description: str = "Fetches restaurant details based on specified criteria."
def _run(self, query):
result = get_restaurants_details(query)
return result
def _arun(self, query):
result = get_restaurants_details(query)
return result
from openai import OpenAI
def moderation(query):
client = OpenAI()
response = client.moderations.create(
model="omni-moderation-latest", # OpenAI moderation model
input=query
)
result = response.results[0]
if result.flagged:
return True
else :
return False
from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent, AgentType
ic = initialize_conversation()
# LLM
llm = ChatOpenAI(model="gpt-4o-2024-11-20", temperature=0, messages = ic)
# Tools list
tools = [fetch_restaurant_tool()]
# Initialize agent with tools
agent = initialize_agent(
tools,
llm,
handle_parsing_errors=True,
#agent=AgentType.OPENAI_FUNCTIONS, # uses function-calling paradigm
verbose=True
)
# Run query
#agent.run("Hi, I wants to restaurant which serves Japanese cusines in Makati City with rating 4 or above ")
def restaurant_agent(query):
# Pre-Moderation
pre_mod = moderation(query)
if pre_mod:
return 'Content is Flagged by OpenAI'
# Agent Invoke
response = agent.run(query)
# Post-Moderation
post_mod = moderation(query)
if post_mod :
return 'Content is Flagged by OpenAI'
return response
st.title("Restaurant Recommendation Agent")
user_input = st.text_input("Enter your restaurant preferences:")
if st.button("Get Recommendations"):
if user_input:
with st.spinner("Finding the best restaurant for you..."):
recommendations = restaurant_agent(user_input)
st.success("Here are your restaurant recommendations:")
st.write(recommendations)
else:
st.error("Please enter your restaurant preferences.")
# To run this app, use the command: streamlit run app.py