FaiazAI commited on
Commit
f1e6b6d
·
verified ·
1 Parent(s): bbd234e

Update final_professional_persona_agent.py

Browse files
Files changed (1) hide show
  1. final_professional_persona_agent.py +330 -291
final_professional_persona_agent.py CHANGED
@@ -1,292 +1,331 @@
1
- import os
2
-
3
- import json
4
-
5
- import requests
6
-
7
- from groq import Groq
8
-
9
- from PyPDF2 import PdfReader
10
-
11
- import gradio as gr
12
-
13
- from openai import OpenAI
14
-
15
- from dotenv import load_dotenv
16
-
17
- load_dotenv(override=True)
18
-
19
- groq_api_key = os.getenv('GROQ_API_KEY')
20
-
21
- openai_api_key = os.getenv('OPENAI_API_KEY')
22
-
23
- pushover_user_key = os.getenv('PUSHOVER_USER_KEY')
24
-
25
- pushover_api_key = os.getenv('PUSHOVER_API_KEY')
26
-
27
- pushover_url = 'https://api.pushover.net/1/messages.json'
28
-
29
- groq_client = Groq()
30
-
31
- openai_client = OpenAI()
32
-
33
- def push_message(message):
34
-
35
- print(f"Pushing message: {message}")
36
-
37
- payload = {
38
-
39
- "user": pushover_user_key,
40
-
41
- "token": pushover_api_key,
42
-
43
- "message": message
44
-
45
- }
46
- response = requests.post(pushover_url, data=payload)
47
-
48
- return response.json()
49
-
50
- def register_user_details(email, name="not provided", notes="not provided"):
51
-
52
- push_message(f"Registering interest from {name} with {email} and notes {notes}")
53
-
54
- return {"Registered": "Ok"}
55
-
56
- def register_unknown_question(question):
57
-
58
- print(f"Registering {question} which was asked and really challenging even for me to answer")
59
-
60
- return {"Registered": "Ok"}
61
-
62
- register_user_details_json = {
63
-
64
-
65
- "name" : "register_user_details",
66
-
67
- "description" : " Use this tool to register the user who is interested to be in touch provided the email address",
68
-
69
- "parameters" : {
70
-
71
- "email" : {
72
-
73
- "type" : "string",
74
-
75
- "description" : "The email address of this user"
76
- },
77
-
78
- "name" : {
79
-
80
- "type" : "string",
81
-
82
- "description" : "The name of the user, if they provided it"
83
- },
84
-
85
- "notes" : {
86
-
87
- "type" : "string",
88
-
89
- "description" : "Any interesting information about the conversation that is worth keeping a note of to enhance context"
90
- }
91
-
92
- },
93
-
94
- "required" : ["email"],
95
-
96
- "additionalProperties" : False
97
-
98
-
99
- }
100
-
101
- register_unknown_question_json = {
102
-
103
-
104
- "name" : "register_unknown_question",
105
-
106
- "description" : "Use this tool to register any question that you could not answer as you were not 100% confident.",
107
-
108
- "parameters" : {
109
-
110
-
111
- "type" : "object",
112
-
113
- "properties" : {
114
-
115
-
116
- "question" : {
117
-
118
- "type" : "string",
119
-
120
- "description" : "The question which was challenging to answer"
121
- },
122
-
123
- },
124
-
125
- "required" : ["question"],
126
-
127
- "additionalProperties" : False
128
- }
129
-
130
- }
131
-
132
- llm_tools = [{"type" : "function", "function" : register_user_details_json},
133
-
134
- {"type" : "function", "function" : register_unknown_question_json}]
135
-
136
-
137
- class FaiazAhmed:
138
-
139
- def __init__(self):
140
-
141
- self.groq = groq_client
142
-
143
- self.name = "Faiaz Ahmed"
144
-
145
- pdf_reader = PdfReader("FaiazDocs\\LinkedIn_Profile_PDF.pdf")
146
-
147
- self.linkedin_profile = ""
148
-
149
- for page in pdf_reader.pages:
150
-
151
- text = page.extract_text()
152
-
153
- if text:
154
-
155
- self.linkedin_profile += text
156
-
157
- with open("FaiazDocs\\summary.txt", "r" ,encoding = "utf-8") as f:
158
-
159
- self.professional_summary = f.read()
160
-
161
-
162
- def utilize_tools(self, tools):
163
-
164
- results = []
165
-
166
- for tool in tools:
167
-
168
- tool_name = tool.function.name
169
-
170
- tool_arguments = json.loads(tool.function.arguments)
171
-
172
- print(f"Tool loaded: {tool_name}", flush = True)
173
-
174
- if tool_name == "register_user_details":
175
-
176
- result = register_user_details(**tool_arguments)
177
-
178
- results.append({"role" : "tool", "content" : json.dumps(result), "tool_call_id" : tool.id})
179
-
180
- elif tool_name == "register_unknown_question":
181
-
182
- result = register_unknown_question(**tool_arguments)
183
-
184
- results.append({"role" : "tool", "content" : json.dumps(result), "tool_call_id" : tool.id})
185
-
186
- return results
187
-
188
-
189
- def agent_prompt(self):
190
-
191
- agent_prompt = f"""
192
-
193
- You are taking up the identity as {self.name} and your job is to answer questions to users who comes across {self.name}'s professional profile relating to {self.name}'s background, experience and skills.
194
-
195
- Be as faithful, convincing and genuine as possible. Assume that you are being interviewed by a recruiter or a hiring manager who is specifically hiring for Tech roles with you being provided with self.{self.name}'s professional summary and linkedin profile, prove them why you are different from other potential candidates and why they should hire you.
196
-
197
- If you unable give an answer to a specific query to a question, use your register_unknown_question tool to register the question that you could not answer, even if it's something trivial and unrelated to career.
198
-
199
- While discussion, if the user is taking more interest, then try your ultimate best to steer the user towards getting in touch with {self.name} via email, ask for their email and register it using your register_user_details tool.
200
-
201
- """
202
-
203
- agent_prompt += f"Professional Summary of {self.name} : {self.professional_summary}"
204
-
205
- agent_prompt += f"LinkedIn Profile of {self.name} : {self.linkedin_profile}"
206
-
207
- agent_prompt += f"With this provided professional context, chat and interact with a friendly, professional tone with the user, keeping in mind that you are {self.name}"
208
-
209
- return agent_prompt
210
-
211
- def initialize_chat(self, message, history=None):
212
-
213
- if history is None:
214
-
215
- history = []
216
-
217
- filtered_history = []
218
-
219
- for msg in history:
220
-
221
- if isinstance(msg, dict):
222
-
223
- role = msg.get("role")
224
-
225
- content = msg.get("content")
226
-
227
- if role in ["user", "assistant"] and isinstance(content, str):
228
-
229
- filtered_history.append({"role": role, "content": content})
230
-
231
- messages = [{"role": "system", "content": self.agent_prompt()}] + filtered_history + [{"role": "user", "content": message}]
232
-
233
- done = False
234
-
235
- while not done:
236
-
237
- chatbot_response = groq_client.chat.completions.create(
238
-
239
- model='llama-3.3-70b-versatile',
240
-
241
- messages=messages,
242
-
243
- tools=llm_tools
244
- )
245
-
246
- finish_reason = chatbot_response.choices[0].finish_reason
247
-
248
- if finish_reason == "tool_calls":
249
-
250
- message = chatbot_response.choices[0].message
251
-
252
- tool_calls = message.tool_calls
253
-
254
- result = self.utilize_tools(tool_calls)
255
-
256
- messages.append(message)
257
-
258
- messages.extend(result)
259
- else:
260
- done = True
261
-
262
- return chatbot_response.choices[0].message.content
263
-
264
- #def main():
265
-
266
- # Test the setup
267
- # push_message("System initialized successfully!")
268
-
269
- # Create a simple Gradio interface
270
- # with gr.Blocks() as demo:
271
- #gr.Markdown("# Professional Persona Agent")
272
- #with gr.Row():
273
- # email = gr.Textbox(label="Email")
274
- #name = gr.Textbox(label="Name (optional)")
275
- #notes = gr.Textbox(label="Notes (optional)")
276
- #submit_btn = gr.Button("Register Interest")
277
- #output = gr.JSON()
278
-
279
- #submit_btn.click(
280
- #fn=register_user_details,
281
- #inputs=[email, name, notes],
282
- #outputs=output
283
- #)
284
-
285
- #demo.launch()
286
-
287
- if __name__ == "__main__":
288
-
289
- faiaz = FaiazAhmed()
290
-
291
- gr.ChatInterface(faiaz.initialize_chat, type = "messages").launch(debug = True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
 
 
1
+ import os
2
+
3
+ import json
4
+
5
+ import requests
6
+
7
+ from groq import Groq
8
+
9
+ from PyPDF2 import PdfReader
10
+
11
+ import gradio as gr
12
+
13
+ from openai import OpenAI
14
+
15
+ from dotenv import load_dotenv
16
+
17
+ load_dotenv(override=True)
18
+
19
+ # Get API keys with explicit error handling
20
+ def get_required_env_var(var_name):
21
+ value = os.getenv(var_name)
22
+ if not value:
23
+ raise ValueError(f"{var_name} environment variable is not set. Please set it in your Hugging Face Space secrets.")
24
+ return value
25
+
26
+ try:
27
+ # Get required API keys
28
+ groq_api_key = get_required_env_var('GROQ_API_KEY')
29
+ openai_api_key = get_required_env_var('OPENAI_API_KEY')
30
+
31
+ # Optional API keys
32
+ pushover_user_key = os.getenv('PUSHOVER_USER_KEY')
33
+ pushover_api_key = os.getenv('PUSHOVER_API_KEY')
34
+ pushover_url = 'https://api.pushover.net/1/messages.json'
35
+
36
+ # Initialize clients
37
+ groq_client = Groq(api_key=groq_api_key)
38
+ openai_client = OpenAI(api_key=openai_api_key)
39
+
40
+ except Exception as e:
41
+ print(f"Error during initialization: {str(e)}")
42
+ raise
43
+
44
+ def push_message(message):
45
+
46
+ print(f"Pushing message: {message}")
47
+
48
+ payload = {
49
+
50
+ "user": pushover_user_key,
51
+
52
+ "token": pushover_api_key,
53
+
54
+ "message": message
55
+
56
+ }
57
+ response = requests.post(pushover_url, data=payload)
58
+
59
+ return response.json()
60
+
61
+ def register_user_details(email, name="not provided", notes="not provided"):
62
+
63
+ push_message(f"Registering interest from {name} with {email} and notes {notes}")
64
+
65
+ return {"Registered": "Ok"}
66
+
67
+ def register_unknown_question(question):
68
+
69
+ print(f"Registering {question} which was asked and really challenging even for me to answer")
70
+
71
+ return {"Registered": "Ok"}
72
+
73
+ register_user_details_json = {
74
+
75
+
76
+ "name" : "register_user_details",
77
+
78
+ "description" : " Use this tool to register the user who is interested to be in touch provided the email address",
79
+
80
+ "parameters" : {
81
+
82
+ "email" : {
83
+
84
+ "type" : "string",
85
+
86
+ "description" : "The email address of this user"
87
+ },
88
+
89
+ "name" : {
90
+
91
+ "type" : "string",
92
+
93
+ "description" : "The name of the user, if they provided it"
94
+ },
95
+
96
+ "notes" : {
97
+
98
+ "type" : "string",
99
+
100
+ "description" : "Any interesting information about the conversation that is worth keeping a note of to enhance context"
101
+ }
102
+
103
+ },
104
+
105
+ "required" : ["email"],
106
+
107
+ "additionalProperties" : False
108
+
109
+
110
+ }
111
+
112
+ register_unknown_question_json = {
113
+
114
+
115
+ "name" : "register_unknown_question",
116
+
117
+ "description" : "Use this tool to register any question that you could not answer as you were not 100% confident.",
118
+
119
+ "parameters" : {
120
+
121
+
122
+ "type" : "object",
123
+
124
+ "properties" : {
125
+
126
+
127
+ "question" : {
128
+
129
+ "type" : "string",
130
+
131
+ "description" : "The question which was challenging to answer"
132
+ },
133
+
134
+ },
135
+
136
+ "required" : ["question"],
137
+
138
+ "additionalProperties" : False
139
+ }
140
+
141
+ }
142
+
143
+ llm_tools = [{"type" : "function", "function" : register_user_details_json},
144
+
145
+ {"type" : "function", "function" : register_unknown_question_json}]
146
+
147
+
148
+ class FaiazAhmed:
149
+
150
+ def __init__(self):
151
+
152
+ self.groq = groq_client
153
+
154
+ self.name = "Faiaz Ahmed"
155
+
156
+ # Initialize with default values
157
+ self.linkedin_profile = ""
158
+ self.professional_summary = ""
159
+
160
+ # Debug: Print current working directory and list files
161
+ print(f"Current working directory: {os.getcwd()}")
162
+ print("Contents of current directory:")
163
+ print(os.listdir("."))
164
+ print("\nContents of FaiazDocs directory:")
165
+ try:
166
+ print(os.listdir("./FaiazDocs"))
167
+ except Exception as e:
168
+ print(f"Error listing FaiazDocs directory: {str(e)}")
169
+
170
+ try:
171
+ # Try to read LinkedIn profile PDF
172
+ pdf_path = "./FaiazDocs/LinkedIn_Profile_PDF.pdf"
173
+ print(f"\nAttempting to read PDF from: {pdf_path}")
174
+ print(f"File exists: {os.path.exists(pdf_path)}")
175
+ pdf_reader = PdfReader(pdf_path)
176
+ for page in pdf_reader.pages:
177
+ text = page.extract_text()
178
+ if text:
179
+ self.linkedin_profile += text
180
+ except FileNotFoundError as e:
181
+ print(f"Error reading LinkedIn profile: {str(e)}")
182
+ self.linkedin_profile = "Experienced software engineer with expertise in AI and machine learning."
183
+ except Exception as e:
184
+ print(f"Unexpected error reading PDF: {str(e)}")
185
+ self.linkedin_profile = "Experienced software engineer with expertise in AI and machine learning."
186
+
187
+ try:
188
+ # Try to read summary file
189
+ summary_path = "./FaiazDocs/summary.txt"
190
+ print(f"\nAttempting to read summary from: {summary_path}")
191
+ print(f"File exists: {os.path.exists(summary_path)}")
192
+ with open(summary_path, "r", encoding="utf-8") as f:
193
+ self.professional_summary = f.read()
194
+ except FileNotFoundError as e:
195
+ print(f"Error reading summary: {str(e)}")
196
+ self.professional_summary = "Passionate about AI and software development with a focus on creating innovative solutions."
197
+ except Exception as e:
198
+ print(f"Unexpected error reading summary: {str(e)}")
199
+ self.professional_summary = "Passionate about AI and software development with a focus on creating innovative solutions."
200
+
201
+ def utilize_tools(self, tools):
202
+
203
+ results = []
204
+
205
+ for tool in tools:
206
+
207
+ tool_name = tool.function.name
208
+
209
+ tool_arguments = json.loads(tool.function.arguments)
210
+
211
+ print(f"Tool loaded: {tool_name}", flush = True)
212
+
213
+ if tool_name == "register_user_details":
214
+
215
+ result = register_user_details(**tool_arguments)
216
+
217
+ results.append({"role" : "tool", "content" : json.dumps(result), "tool_call_id" : tool.id})
218
+
219
+ elif tool_name == "register_unknown_question":
220
+
221
+ result = register_unknown_question(**tool_arguments)
222
+
223
+ results.append({"role" : "tool", "content" : json.dumps(result), "tool_call_id" : tool.id})
224
+
225
+ return results
226
+
227
+
228
+ def agent_prompt(self):
229
+
230
+ agent_prompt = f"""
231
+
232
+ You are taking up the identity as {self.name} and your job is to answer questions to users who comes across {self.name}'s professional profile relating to {self.name}'s background, experience and skills.
233
+
234
+ Be as faithful, convincing and genuine as possible. Assume that you are being interviewed by a recruiter or a hiring manager who is specifically hiring for Tech roles with you being provided with self.{self.name}'s professional summary and linkedin profile, prove them why you are different from other potential candidates and why they should hire you.
235
+
236
+ If you unable give an answer to a specific query to a question, use your register_unknown_question tool to register the question that you could not answer, even if it's something trivial and unrelated to career.
237
+
238
+ While discussion, if the user is taking more interest, then try your ultimate best to steer the user towards getting in touch with {self.name} via email, ask for their email and register it using your register_user_details tool.
239
+
240
+ """
241
+
242
+ agent_prompt += f"Professional Summary of {self.name} : {self.professional_summary}"
243
+
244
+ agent_prompt += f"LinkedIn Profile of {self.name} : {self.linkedin_profile}"
245
+
246
+ agent_prompt += f"With this provided professional context, chat and interact with a friendly, professional tone with the user, keeping in mind that you are {self.name}"
247
+
248
+ return agent_prompt
249
+
250
+ def initialize_chat(self, message, history=None):
251
+
252
+ if history is None:
253
+
254
+ history = []
255
+
256
+ filtered_history = []
257
+
258
+ for msg in history:
259
+
260
+ if isinstance(msg, dict):
261
+
262
+ role = msg.get("role")
263
+
264
+ content = msg.get("content")
265
+
266
+ if role in ["user", "assistant"] and isinstance(content, str):
267
+
268
+ filtered_history.append({"role": role, "content": content})
269
+
270
+ messages = [{"role": "system", "content": self.agent_prompt()}] + filtered_history + [{"role": "user", "content": message}]
271
+
272
+ done = False
273
+
274
+ while not done:
275
+
276
+ chatbot_response = groq_client.chat.completions.create(
277
+
278
+ model='llama-3.3-70b-versatile',
279
+
280
+ messages=messages,
281
+
282
+ tools=llm_tools
283
+ )
284
+
285
+ finish_reason = chatbot_response.choices[0].finish_reason
286
+
287
+ if finish_reason == "tool_calls":
288
+
289
+ message = chatbot_response.choices[0].message
290
+
291
+ tool_calls = message.tool_calls
292
+
293
+ result = self.utilize_tools(tool_calls)
294
+
295
+ messages.append(message)
296
+
297
+ messages.extend(result)
298
+ else:
299
+ done = True
300
+
301
+ return chatbot_response.choices[0].message.content
302
+
303
+ #def main():
304
+
305
+ # Test the setup
306
+ # push_message("System initialized successfully!")
307
+
308
+ # Create a simple Gradio interface
309
+ # with gr.Blocks() as demo:
310
+ #gr.Markdown("# Professional Persona Agent")
311
+ #with gr.Row():
312
+ # email = gr.Textbox(label="Email")
313
+ #name = gr.Textbox(label="Name (optional)")
314
+ #notes = gr.Textbox(label="Notes (optional)")
315
+ #submit_btn = gr.Button("Register Interest")
316
+ #output = gr.JSON()
317
+
318
+ #submit_btn.click(
319
+ #fn=register_user_details,
320
+ #inputs=[email, name, notes],
321
+ #outputs=output
322
+ #)
323
+
324
+ #demo.launch()
325
+
326
+ if __name__ == "__main__":
327
+
328
+ faiaz = FaiazAhmed()
329
+
330
+ gr.ChatInterface(faiaz.initialize_chat, type = "messages").launch(debug = True)
331