vasiukm commited on
Commit
4357218
·
verified ·
1 Parent(s): df98476

Upload folder using huggingface_hub

Browse files
Files changed (4) hide show
  1. .gitattributes +1 -0
  2. README.md +3 -9
  3. menu.py +234 -0
  4. menu_restorana.pdf +3 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ menu_restorana.pdf filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,12 +1,6 @@
1
  ---
2
- title: Menu Bot
3
- emoji: 📚
4
- colorFrom: indigo
5
- colorTo: green
6
  sdk: gradio
7
- sdk_version: 6.3.0
8
- app_file: app.py
9
- pinned: false
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: menu_bot
3
+ app_file: menu.py
 
 
4
  sdk: gradio
5
+ sdk_version: 5.49.1
 
 
6
  ---
 
 
menu.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ from openai import OpenAI
3
+ import json
4
+ import os
5
+ import requests
6
+ from pathlib import Path
7
+ from pypdf import PdfReader
8
+ from pydantic import BaseModel
9
+ import gradio as gr
10
+
11
+ load_dotenv(override=True)
12
+ pushover_token = os.getenv("PUSHOVER_TOKEN")
13
+ pushover_user = os.getenv("PUSHOVER_USER")
14
+ pushover_base_url = "https://api.pushover.net/1/messages.json"
15
+ gemini_api_key = os.getenv("GEMINI_API_KEY")
16
+ GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai/"
17
+
18
+
19
+ class Evaluation(BaseModel):
20
+ is_acceptable: bool
21
+ feedback: str
22
+
23
+ def push(text):
24
+ requests.post(
25
+ pushover_base_url,
26
+ data = {
27
+ "token": pushover_token,
28
+ "user": pushover_user,
29
+ "message": text
30
+ }
31
+ )
32
+
33
+ def record_booking_table(email, name = "name not provided", date = "date not provided", time = "time not provided"):
34
+ push(f"{name} has booked tables on {date} at {time}. You can connect him via {email}")
35
+ return {"recorded": "ok"}
36
+
37
+ def record_feedback(feedback):
38
+ push(f"Somebody has left feedback: {feedback}")
39
+ return {"recorded": "ok"}
40
+
41
+ record_booking_table_json = {
42
+ "name" : "record_booking_table",
43
+ "description" : "Use this tool to record, when a user wants to book a table and provided his email.",
44
+ "parameters": {
45
+ "type": "object",
46
+ "properties":{
47
+ "email":{
48
+ "type": "string",
49
+ "description": "The email address of a user"
50
+ },
51
+ "name":{
52
+ "type": "string",
53
+ "description": "The user's name, if they provided it"
54
+ },
55
+ "date":{
56
+ "type": "string",
57
+ "description": "Date, when user wants to book a table like (xxth of month), if they provided it."
58
+ },
59
+ "time":{
60
+ "type": "string",
61
+ "description": "Time, when user wants to book a table like (hh:mm), if they provided it."
62
+ }
63
+ },
64
+ "required": ["email"],
65
+ "additionalProperties": False
66
+ }
67
+ }
68
+
69
+ record_feedback_json = {
70
+ "name": "record_feedback",
71
+ "description": "Always use this tool to record structured feedback about our restaurant. If feedback isn`t related to restaurant, don`t use this tool.",
72
+ "parameters":{
73
+ "type": "object",
74
+ "properties":{
75
+ "feedback": {
76
+ "type": "string",
77
+ "description": "The feedback that was given."
78
+ }
79
+ },
80
+ "required": ["feedback"],
81
+ "additionalProperties": False
82
+ }
83
+ }
84
+
85
+ tools = [{"type": "function", "function": record_booking_table_json},
86
+ {"type": "function", "function": record_feedback_json}]
87
+
88
+
89
+ class RestaurantBot:
90
+ def __init__(self):
91
+ self.gemini = OpenAI(base_url = GEMINI_BASE_URL, api_key=gemini_api_key)
92
+ self.name = "Night City"
93
+ pdf_path = Path(__file__).resolve().parent / "menu_restorana.pdf"
94
+ reader = PdfReader(str(pdf_path))
95
+ self.menu = ""
96
+ for page in reader.pages:
97
+ text = page.extract_text()
98
+ if text:
99
+ self.menu += text
100
+
101
+ def handle_tool_call(self, tool_calls):
102
+ results =[]
103
+ for tool_call in tool_calls:
104
+ tool_name = tool_call.function.name
105
+ arguments = json.loads(tool_call.function.arguments)
106
+ tool = globals().get(tool_name)
107
+ result = tool(**arguments) if tool else {}
108
+ results.append({"role": "tool", "content": json.dumps(result), "tool_call_id": tool_call.id})
109
+ return results
110
+
111
+ def system_prompt(self):
112
+ system_instructions = f"""
113
+ You are Alexander, the professional and welcoming head hostess of the '{self.name}' restaurant.
114
+ Your primary goal is to assist guests with the menu, answer questions about dishes, and facilitate table reservations.
115
+
116
+ ### OPERATIONAL DETAILS:
117
+ * **Working Hours**: We are open from 10:00 to 22:00 every day.
118
+ * **Contact Numbers**: (097) 454 6555 or (063) 584 65 55.
119
+ * **Official Website**: night-city.com.ua[cite: 7, 11].
120
+
121
+ ### GUIDELINES:
122
+ 1. **Persona**: Be polite, sophisticated, and helpful. Treat every user as a valued guest entering our establishment.
123
+ 2. **Menu Knowledge**: Use the provided menu context to describe dishes, ingredients, and prices.
124
+ 3. **Upselling**: When a guest shows interest in meat or fish dishes, suggest a matching wine from our Georgian or French collections.
125
+ 4. **Reservations**:
126
+ - Actively encourage guests to book a table if they seem interested in visiting.
127
+ - You MUST obtain an **email address** to complete a booking.
128
+ - Try to collect the guest's name, preferred date, and time.
129
+ - Once you have the email, use the `record_booking_table` tool immediately.
130
+ 5. **Feedback & Edge Cases**:
131
+ - If a guest wants to leave a review, complaint, or suggestion, use the `record_feedback` tool.
132
+ - If you are asked a question you cannot answer based on the menu, or if the request is unrelated to the restaurant, politely inform the guest that you will pass this to the manager and use the `record_feedback` tool to log it.
133
+
134
+ ### RESTAURANT MENU:
135
+ {self.menu}
136
+
137
+ Act as Alexander. Always stay in character and respond in the language used by the guest.
138
+ """
139
+ return system_instructions
140
+
141
+ def evaluator_system_prompt(self):
142
+ # Follow the evaluation pattern from 3_lab3.ipynb, adapted to the restaurant persona
143
+ system = (
144
+ "You are an evaluator that decides whether a response to a restaurant guest is acceptable.\n"
145
+ "You are provided with a conversation between a Guest and Alexander (the restaurant host).\n"
146
+ "Your task is to decide whether Alexander's latest response is acceptable quality.\n"
147
+ "Alexander must be polite, professional, knowledgeable about the menu, and helpful with reservations.\n"
148
+ "Alexander has been given detailed instructions and the full restaurant menu as context:\n\n"
149
+ f"{self.system_prompt()}\n\n"
150
+ "With this context, please evaluate the latest response, replying with whether the response is acceptable and your feedback."
151
+ )
152
+ return system
153
+
154
+ def evaluator_user_prompt(self, reply, message, history):
155
+ user_prompt = f"Here's the conversation between the Guest and Alexander: \n\n{history}\n\n"
156
+ user_prompt += f"Here's the latest message from the Guest: \n\n{message}\n\n"
157
+ user_prompt += f"Here's the latest response from Alexander: \n\n{reply}\n\n"
158
+ user_prompt += "Please evaluate the response, replying with whether it is acceptable and your feedback."
159
+ return user_prompt
160
+
161
+ def evaluate(self, reply, message, history) -> Evaluation:
162
+ messages = [
163
+ {"role": "system", "content": self.evaluator_system_prompt()},
164
+ {"role": "user", "content": self.evaluator_user_prompt(reply, message, history)},
165
+ ]
166
+ response = self.gemini.beta.chat.completions.parse(
167
+ model="gemini-2.5-flash", messages=messages, response_format=Evaluation
168
+ )
169
+ return response.choices[0].message.parsed
170
+
171
+ def rerun(self, reply, message, history, feedback):
172
+ # Same rerun pattern as in 3_lab3.ipynb: augment system prompt with rejection info
173
+ updated_system_prompt = self.system_prompt() + "\n\n## Previous answer rejected\n"
174
+ updated_system_prompt += "You just tried to reply, but the quality control rejected your reply.\n"
175
+ updated_system_prompt += f"## Your attempted answer:\n{reply}\n\n"
176
+ updated_system_prompt += f"## Reason for rejection:\n{feedback}\n\n"
177
+ messages = [{"role": "system", "content": updated_system_prompt}] + history + [
178
+ {"role": "user", "content": message}
179
+ ]
180
+ response = self.gemini.chat.completions.create(
181
+ model="gemini-2.5-flash", messages=messages, tools=tools
182
+ )
183
+ return response.choices[0].message.content
184
+
185
+ def chat(self, message, history):
186
+ # Clean history like in the lab note so providers don't choke on extra keys
187
+ history = [{"role": h["role"], "content": h["content"]} for h in history]
188
+
189
+ messages = [{"role": "system", "content": self.system_prompt()}] + history + [
190
+ {"role": "user", "content": message}
191
+ ]
192
+ done = False
193
+ response = None
194
+ while not done:
195
+ response = self.gemini.chat.completions.create(
196
+ model="gemini-2.5-flash", messages=messages, tools=tools
197
+ )
198
+ if response.choices[0].finish_reason == "tool_calls":
199
+ msg_obj = response.choices[0].message
200
+ tool_calls = msg_obj.tool_calls
201
+ results = self.handle_tool_call(tool_calls)
202
+ # Store a plain-dict version of the assistant message
203
+ if hasattr(msg_obj, "model_dump"):
204
+ messages.append(msg_obj.model_dump())
205
+ elif hasattr(msg_obj, "to_dict"):
206
+ messages.append(msg_obj.to_dict())
207
+ else:
208
+ messages.append(
209
+ {
210
+ "role": "assistant",
211
+ "content": getattr(msg_obj, "content", None),
212
+ "tool_calls": tool_calls,
213
+ }
214
+ )
215
+ messages.extend(results)
216
+ else:
217
+ done = True
218
+
219
+ reply = response.choices[0].message.content
220
+
221
+ # Run evaluation just like in 3_lab3.ipynb
222
+ evaluation = self.evaluate(reply, message, history)
223
+ if evaluation.is_acceptable:
224
+ print("Passed evaluation - returning reply")
225
+ return reply
226
+ else:
227
+ print("Failed evaluation - retrying")
228
+ print(evaluation.feedback)
229
+ return self.rerun(reply, message, history, evaluation.feedback)
230
+
231
+
232
+ if __name__ == "__main__":
233
+ restaurant_bot = RestaurantBot()
234
+ gr.ChatInterface(restaurant_bot.chat, type="messages").launch()
menu_restorana.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:264974c7fc9e46ebe57c4dba84decf34539f3a6a63e37e94c40411f3a9b89d6b
3
+ size 219346