Kush1 commited on
Commit
5c032b9
·
verified ·
1 Parent(s): 3aca101

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +192 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,194 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ from langchain.tools import BaseTool
4
+ from typing import Optional, Type
5
+ from pydantic import BaseModel, Field
6
+ import os
7
+ import getpass
8
+
9
+ df = pd.read_csv(r"C:\Users\Kush\Downloads\archive\Dataset .csv")
10
+
11
+ os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter OpenAI API Key: ")
12
+
13
+ # Initialize the Chat
14
+
15
+ def initialize_conversation():
16
+ system_message = """You are a Restaurant Recommendation Agent. You will help users find restaurants based on their preferences.
17
+ Use ONLY the information provided in the given context or dataset.
18
+ Dont use any other dataset on which model was trained.
19
+ You have to ask the user questions to understand their preferences better.
20
+ If the user asks for a restaurant recommendation, you should respond with a restaurant name and its details from the dataset.
21
+ If you do not have enough information, ask the user more questions to gather details about their preferences.
22
+ Your final objective to find preferences from user like ('Cusines', 'Location', 'Budget', 'Rating', 'Currency')
23
+ Do not make up any restaurant names or details. Only use the information available in the dataset.
24
+
25
+
26
+
27
+ #####
28
+ 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
29
+ Budget to Price range mapping:
30
+ Budget < 300 : Price range 1
31
+ 300 <= Budget < 700 : Price range 2
32
+ 700 <= Budget < 1500 : Price range 3
33
+ Budget >= 1500 : Price range 4
34
+
35
+
36
+ #####
37
+ Convert Budget into Price range.
38
+ Convert Currency Symbol to complete Currency Name
39
+ 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.
40
+ 7. Return only Restaruant Names and its details in json format.
41
+
42
+
43
+ #####
44
+
45
+ First fetch all preferences from user query in json key-pair like {'cusine': 'value', 'location':'value','rating':'value', 'price_range':'value'}
46
+ Check Intent from provide user preferences using this query.
47
+
48
+ if intent_check is True, then go for fetching restaurant details using this query
49
+ else ask some more details for restaurant preferences
50
+ #####
51
+
52
+ #####
53
+ Before returning final ouput to user Validate the restaurant name from the dataset.If False, then No Restaurant Found For above preferences.
54
+ #####
55
+ 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.
56
+ #####
57
+
58
+ Use the following format for your responses:
59
+ User: [User's message]
60
+ Assistant: [Your response]
61
+ 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!"
62
+
63
+
64
+
65
+ """
66
+ conversation = [
67
+ {"role": "system", "content": system_message}
68
+ ]
69
+ return conversation
70
+
71
+
72
+ def check_intent(json_query):
73
+ print(json_query)
74
+ json_data = json_query
75
+ #json_data = json.loads(json_query)
76
+ if str(json_data.get('cuisine')) is not None and str(json_data.get('location')) is not None:
77
+ return True
78
+ else:
79
+ return False
80
+
81
+
82
+ import json
83
+ def get_restaurants_details(query_json):
84
+ query_json = json.loads(query_json)
85
+ print(query_json)
86
+ cusines = str(query_json.get('cusine'))
87
+ location = str(query_json.get('location'))
88
+ budget = str(query_json.get('price_range'))
89
+ rating = str(query_json.get('rating'))
90
+ currency = str(query_json.get('currency'))
91
+
92
+
93
+ # Convert relevant columns to string type for filtering
94
+ df['Cuisines'] = df['Cuisines'].astype(str)
95
+ df['City'] = df['City'].astype(str)
96
+ df['Price range'] = df['Price range'].astype(str)
97
+ df['Aggregate rating'] = df['Aggregate rating'].astype(str)
98
+ df['Currency'] = df['Currency'].astype(str)
99
+
100
+ is_intent = check_intent(query_json)
101
+
102
+ if not is_intent:
103
+ return 'Ask some more details/preferences for Restaurant from users'
104
+
105
+ else:
106
+
107
+ result = df.loc[(df['Cuisines'].str.contains(cusines)) |
108
+ (df['City'].str.contains(location)) |
109
+ (df['Price range'].str.contains(budget)) |
110
+ (df['Aggregate rating'].str.contains(rating))
111
+ ].values
112
+ print(result)
113
+ return result
114
+
115
+
116
+ class fetch_restaurant_tool(BaseTool):
117
+ name: str = "Fetch Restaurant" # Removed trailing space
118
+ description: str = "Fetches restaurant details based on specified criteria."
119
+
120
+ def _run(self, query):
121
+ result = get_restaurants_details(query)
122
+ return result
123
+
124
+ def _arun(self, query):
125
+ result = get_restaurants_details(query)
126
+ return result
127
+
128
+ from openai import OpenAI
129
+
130
+ def moderation(query):
131
+ client = OpenAI()
132
+ response = client.moderations.create(
133
+ model="omni-moderation-latest", # OpenAI moderation model
134
+ input=query
135
+ )
136
+ result = response.results[0]
137
+ if result.flagged:
138
+ return True
139
+
140
+ else :
141
+ return False
142
+
143
+
144
+
145
+
146
+ from langchain_openai import ChatOpenAI
147
+ from langchain.agents import initialize_agent, AgentType
148
+ ic = initialize_conversation()
149
+ # LLM
150
+ llm = ChatOpenAI(model="gpt-4o-2024-11-20", temperature=0, messages = ic)
151
+
152
+ # Tools list
153
+ tools = [fetch_restaurant_tool()]
154
+
155
+ # Initialize agent with tools
156
+ agent = initialize_agent(
157
+ tools,
158
+ llm,
159
+ handle_parsing_errors=True,
160
+ #agent=AgentType.OPENAI_FUNCTIONS, # uses function-calling paradigm
161
+ verbose=True
162
+ )
163
+
164
+ # Run query
165
+ #agent.run("Hi, I wants to restaurant which serves Japanese cusines in Makati City with rating 4 or above ")
166
+
167
+ def restaurant_agent(query):
168
+
169
+ # Pre-Moderation
170
+ pre_mod = moderation(query)
171
+ if pre_mod:
172
+ return 'Content is Flagged by OpenAI'
173
+
174
+ # Agent Invoke
175
+ response = agent.run(query)
176
+
177
+ # Post-Moderation
178
+ post_mod = moderation(query)
179
+ if post_mod :
180
+ return 'Content is Flagged by OpenAI'
181
+
182
+ return response
183
 
184
+ st.title("Restaurant Recommendation Agent")
185
+ user_input = st.text_input("Enter your restaurant preferences:")
186
+ if st.button("Get Recommendations"):
187
+ if user_input:
188
+ with st.spinner("Finding the best restaurant for you..."):
189
+ recommendations = restaurant_agent(user_input)
190
+ st.success("Here are your restaurant recommendations:")
191
+ st.write(recommendations)
192
+ else:
193
+ st.error("Please enter your restaurant preferences.")
194
+ # To run this app, use the command: streamlit run app.py