jisaacso219 commited on
Commit
84cbbed
Β·
verified Β·
1 Parent(s): b19d7d9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -20
app.py CHANGED
@@ -12,6 +12,8 @@ import zipfile
12
 
13
  load_dotenv(override=True)
14
 
 
 
15
  def push(text):
16
  try:
17
  Path("chat_logs").mkdir(exist_ok=True)
@@ -29,6 +31,8 @@ def push(text):
29
  except Exception as e:
30
  print(f"Pushover error: {e}")
31
 
 
 
32
  def record_user_details(email, name="Name not provided", notes="not provided"):
33
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
34
  filename = f"chat_logs/session_{timestamp}.json"
@@ -38,7 +42,7 @@ def record_user_details(email, name="Name not provided", notes="not provided"):
38
  ])
39
  with open(filename, "w", encoding="utf-8") as f:
40
  json.dump(me.session_log, f, indent=2)
41
- msg = f"[New Contact]\nName: {name}\nEmail: {email}\nNotes: {notes}\n\nπŸ”— View log: {filename}\n\nLast messages:\n{latest_log}"
42
  push(msg)
43
  return {"recorded": "ok"}
44
 
@@ -51,7 +55,7 @@ def record_unknown_question(question):
51
  ])
52
  with open(filename, "w", encoding="utf-8") as f:
53
  json.dump(me.session_log, f, indent=2)
54
- msg = f"[Unknown Question]\nQ: {question}\n\nπŸ”— View log: {filename}\n\nLast messages:\n{latest_log}"
55
  push(msg)
56
  return {"recorded": "ok"}
57
 
@@ -88,15 +92,14 @@ tools = [
88
  {"type": "function", "function": record_unknown_question_json}
89
  ]
90
 
 
 
91
  class Me:
92
  def __init__(self):
93
  self.openai = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
94
  self.name = "Jacob Isaacson"
95
  self.session_log = []
96
  Path("chat_logs").mkdir(exist_ok=True)
97
- keep_path = Path("chat_logs/.keep")
98
- if not keep_path.exists():
99
- keep_path.touch()
100
 
101
  gdown.download("https://drive.google.com/uc?id=1xz2RowkImpI8odYv8zvKdlRHaKfILn40", "linkedin.pdf", quiet=False)
102
  reader = PdfReader("linkedin.pdf")
@@ -134,10 +137,6 @@ If you can't answer something, call `record_unknown_question`. If a user seems i
134
  def chat_stream(self, message, history):
135
  messages = [{"role": "system", "content": self.system_prompt()}]
136
 
137
- if not history:
138
- self.session_log.append({"role": "assistant", "content": "Hello, my name is Jacob Isaacson. Please ask me any questions about my professional career and I will do my best to respond."})
139
- yield self.session_log[-1]["content"]
140
-
141
  for msg in history:
142
  if isinstance(msg, dict) and msg.get("role") in ["user", "assistant"]:
143
  messages.append(msg)
@@ -149,19 +148,51 @@ If you can't answer something, call `record_unknown_question`. If a user seems i
149
  model="gpt-4o",
150
  messages=messages,
151
  tools=tools,
152
- stream=True
153
  )
154
 
155
- full_response = ""
156
- for chunk in response:
157
- delta = chunk.choices[0].delta
158
- if hasattr(delta, "content") and delta.content:
159
- full_response += delta.content
160
- yield full_response
161
-
162
- full_response += "\n\nπŸ’¬ Let me know if you’d like to follow up or need help connecting with Jacob."
163
- self.session_log.append({"role": "assistant", "content": full_response})
164
- self.save_session_log()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
 
166
  def save_session_log(self):
167
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
@@ -175,6 +206,8 @@ If you can't answer something, call `record_unknown_question`. If a user seems i
175
  for log_file in Path("chat_logs").glob("session_*.json"):
176
  archive.write(log_file, arcname=log_file.name)
177
 
 
 
178
  me = Me()
179
 
180
  with gr.Blocks(title="Jacob Isaacson Chatbot") as iface:
@@ -187,6 +220,10 @@ with gr.Blocks(title="Jacob Isaacson Chatbot") as iface:
187
  chatbot=gr.Chatbot(show_copy_button=True),
188
  type="messages",
189
  additional_inputs=[],
 
 
 
 
190
  )
191
 
192
  if __name__ == "__main__":
 
12
 
13
  load_dotenv(override=True)
14
 
15
+ # ─── Pushover Notifications ───────────────────────────────────────────────
16
+
17
  def push(text):
18
  try:
19
  Path("chat_logs").mkdir(exist_ok=True)
 
31
  except Exception as e:
32
  print(f"Pushover error: {e}")
33
 
34
+ # ─── Tool Functions ────────────────────────────────────────────────────────
35
+
36
  def record_user_details(email, name="Name not provided", notes="not provided"):
37
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
38
  filename = f"chat_logs/session_{timestamp}.json"
 
42
  ])
43
  with open(filename, "w", encoding="utf-8") as f:
44
  json.dump(me.session_log, f, indent=2)
45
+ msg = f"[New Contact]\nName: {name}\nEmail: {email}\nNotes: {notes}\n\nπŸ”— View log: {filename}"
46
  push(msg)
47
  return {"recorded": "ok"}
48
 
 
55
  ])
56
  with open(filename, "w", encoding="utf-8") as f:
57
  json.dump(me.session_log, f, indent=2)
58
+ msg = f"[Unknown Question]\nQ: {question}\n\nπŸ”— View log: {filename}"
59
  push(msg)
60
  return {"recorded": "ok"}
61
 
 
92
  {"type": "function", "function": record_unknown_question_json}
93
  ]
94
 
95
+ # ─── Core Chatbot Class ────────────────────────────────────────────────────
96
+
97
  class Me:
98
  def __init__(self):
99
  self.openai = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
100
  self.name = "Jacob Isaacson"
101
  self.session_log = []
102
  Path("chat_logs").mkdir(exist_ok=True)
 
 
 
103
 
104
  gdown.download("https://drive.google.com/uc?id=1xz2RowkImpI8odYv8zvKdlRHaKfILn40", "linkedin.pdf", quiet=False)
105
  reader = PdfReader("linkedin.pdf")
 
137
  def chat_stream(self, message, history):
138
  messages = [{"role": "system", "content": self.system_prompt()}]
139
 
 
 
 
 
140
  for msg in history:
141
  if isinstance(msg, dict) and msg.get("role") in ["user", "assistant"]:
142
  messages.append(msg)
 
148
  model="gpt-4o",
149
  messages=messages,
150
  tools=tools,
151
+ stream=False
152
  )
153
 
154
+ reply = response.choices[0].message
155
+
156
+ if reply.tool_calls:
157
+ tool_results = self.handle_tool_call(reply.tool_calls)
158
+ messages.append(reply)
159
+ messages.extend(tool_results)
160
+
161
+ final_response = self.openai.chat.completions.create(
162
+ model="gpt-4o",
163
+ messages=messages,
164
+ tools=tools,
165
+ stream=True
166
+ )
167
+
168
+ full_response = ""
169
+ for chunk in final_response:
170
+ delta = chunk.choices[0].delta
171
+ if hasattr(delta, "content") and delta.content:
172
+ full_response += delta.content
173
+ yield full_response
174
+
175
+ full_response += "\n\nπŸ’¬ Let me know if you’d like to follow up or need help connecting with Jacob."
176
+ self.session_log.append({"role": "assistant", "content": full_response})
177
+ self.save_session_log()
178
+ else:
179
+ stream = self.openai.chat.completions.create(
180
+ model="gpt-4o",
181
+ messages=messages,
182
+ tools=tools,
183
+ stream=True
184
+ )
185
+
186
+ full_response = ""
187
+ for chunk in stream:
188
+ delta = chunk.choices[0].delta
189
+ if hasattr(delta, "content") and delta.content:
190
+ full_response += delta.content
191
+ yield full_response
192
+
193
+ full_response += "\n\nπŸ’¬ Let me know if you’d like to follow up or need help connecting with Jacob."
194
+ self.session_log.append({"role": "assistant", "content": full_response})
195
+ self.save_session_log()
196
 
197
  def save_session_log(self):
198
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
 
206
  for log_file in Path("chat_logs").glob("session_*.json"):
207
  archive.write(log_file, arcname=log_file.name)
208
 
209
+ # ─── UI Interface ───────────────────────────────────────────────────────────
210
+
211
  me = Me()
212
 
213
  with gr.Blocks(title="Jacob Isaacson Chatbot") as iface:
 
220
  chatbot=gr.Chatbot(show_copy_button=True),
221
  type="messages",
222
  additional_inputs=[],
223
+ retry_btn=None,
224
+ undo_btn=None,
225
+ clear_btn=None,
226
+ chatbot_initial_message={"role": "assistant", "content": "Hello, my name is Jacob Isaacson. Please ask me any questions about my professional career and I will do my best to respond."}
227
  )
228
 
229
  if __name__ == "__main__":