Nidso/NidBot
0
1from dotenv import load_dotenv2from openai import OpenAI3import json4import os5import smtplib6from email.mime.text import MIMEText7from email.utils import formataddr8from pypdf import PdfReader9import gradio as gr10 11load_dotenv(override=True)12 13def send_email(to_email, name):14 sender_email = os.getenv("SMTP_EMAIL")15 sender_password = os.getenv("SMTP_PASSWORD")16 smtp_server = os.getenv("SMTP_SERVER")17 smtp_port = int(os.getenv("SMTP_PORT", 587))18 admin_email = os.getenv("ADMIN_EMAIL")19 20 user_msg = MIMEText(21 f"Dear {name},\n\nThank you for contacting me! "22 "I'll get back to you shortly.\n\nBest regards,\n{os.getenv('YOUR_NAME')}"23 )24 user_msg['Subject'] = "Thank you for reaching out!"25 user_msg['From'] = formataddr((os.getenv("YOUR_NAME"), sender_email))26 user_msg['To'] = to_email27 28 admin_msg = MIMEText(f"New contact: {name} <{to_email}>")29 admin_msg['Subject'] = "New Website Contact"30 admin_msg['From'] = sender_email31 admin_msg['To'] = admin_email32 33 try:34 with smtplib.SMTP(smtp_server, smtp_port) as server:35 server.starttls()36 server.login(sender_email, sender_password)37 server.sendmail(sender_email, to_email, user_msg.as_string())38 server.sendmail(sender_email, admin_email, admin_msg.as_string())39 except Exception as e:40 print(f"Email failed: {str(e)}")41 42def record_user_details(email, name="Name not provided", notes="not provided"):43 if name == "Name not provided":44 email_name = "User"45 else:46 email_name = name.split()[0]47 48 send_email(email, email_name)49 return {"recorded": "ok"}50 51def record_unknown_question(question):52 sender_email = os.getenv("SMTP_EMAIL")53 sender_password = os.getenv("SMTP_PASSWORD")54 smtp_server = os.getenv("SMTP_SERVER")55 smtp_port = int(os.getenv("SMTP_PORT", 587))56 admin_email = os.getenv("ADMIN_EMAIL")57 58 msg = MIMEText(f"Unanswered question: {question}")59 msg['Subject'] = "New Unanswered Question"60 msg['From'] = sender_email61 msg['To'] = admin_email62 63 try:64 with smtplib.SMTP(smtp_server, smtp_port) as server:65 server.starttls()66 server.login(sender_email, sender_password)67 server.sendmail(sender_email, admin_email, msg.as_string())68 except Exception as e:69 print(f"Notification failed: {str(e)}")70 71 return {"recorded": "ok"}72 73record_user_details_json = {74 "name": "record_user_details",75 "description": "Use this tool to record that a user is interested in being in touch and provided an email address",76 "parameters": {77 "type": "object",78 "properties": {79 "email": {80 "type": "string",81 "description": "The email address of this user"82 },83 "name": {84 "type": "string",85 "description": "The user's name, if they provided it"86 }87 ,88 "notes": {89 "type": "string",90 "description": "Any additional information about the conversation that's worth recording to give context"91 }92 },93 "required": ["email"],94 "additionalProperties": False95 }96}97 98record_unknown_question_json = {99 "name": "record_unknown_question",100 "description": "Always use this tool to record any question that couldn't be answered as you didn't know the answer",101 "parameters": {102 "type": "object",103 "properties": {104 "question": {105 "type": "string",106 "description": "The question that couldn't be answered"107 },108 },109 "required": ["question"],110 "additionalProperties": False111 }112}113 114tools = [{"type": "function", "function": record_user_details_json},115 {"type": "function", "function": record_unknown_question_json}]116 117 118class Me:119 120 def __init__(self):121 self.openai = OpenAI()122 self.name = "Nidhish Sonavale"123 reader = PdfReader("me/Nidhish_Sonavale_Resume.pdf")124 self.resume = ""125 for page in reader.pages:126 text = page.extract_text()127 if text:128 self.resume += text129 with open("me/summary.txt", "r", encoding="utf-8") as f:130 self.summary = f.read()131 132 133 def handle_tool_call(self, tool_calls):134 results = []135 for tool_call in tool_calls:136 tool_name = tool_call.function.name137 arguments = json.loads(tool_call.function.arguments)138 print(f"Tool called: {tool_name}", flush=True)139 tool = globals().get(tool_name)140 result = tool(**arguments) if tool else {}141 results.append({"role": "tool","content": json.dumps(result),"tool_call_id": tool_call.id})142 return results143 144 def system_prompt(self):145 system_prompt = f"You are acting as {self.name}. You are answering questions on {self.name}'s website, \146particularly questions related to {self.name}'s career, background, skills and experience. \147Your responsibility is to represent {self.name} for interactions on the website as faithfully as possible. \148You are given a summary of {self.name}'s background and LinkedIn profile which you can use to answer questions. \149Be professional and engaging, as if talking to a potential client or future employer who came across the website. \150If you don't know the answer to any question, use your record_unknown_question tool to record the question that you couldn't answer, even if it's about something trivial or unrelated to career. \151If the user is engaging in discussion, try to steer them towards getting in touch via email; ask for their email and record it using your record_user_details tool. "152 153 system_prompt += f"\n\n## Summary:\n{self.summary}\n\n## LinkedIn Profile:\n{self.resume}\n\n"154 system_prompt += f"With this context, please chat with the user, always staying in character as {self.name}."155 return system_prompt156 157 def chat(self, message, history):158 messages = [{"role": "system", "content": self.system_prompt()}] + history + [{"role": "user", "content": message}]159 done = False160 while not done:161 response = self.openai.chat.completions.create(model="gpt-4o-mini", messages=messages, tools=tools)162 if response.choices[0].finish_reason=="tool_calls":163 message = response.choices[0].message164 tool_calls = message.tool_calls165 results = self.handle_tool_call(tool_calls)166 messages.append(message)167 messages.extend(results)168 else:169 done = True170 return response.choices[0].message.content171 172 173if __name__ == "__main__":174 me = Me()175 gr.ChatInterface(me.chat, type="messages").launch()176 