File size: 6,388 Bytes
2a6bb3d
5c032b9
 
 
 
 
 
 
7841fdd
5c032b9
7fc3bfb
5c032b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a6bb3d
5c032b9
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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