""" Personal Website Chatbot Application This application creates an AI-powered chatbot that impersonates the owner using their LinkedIn profile and personal summary. It uses OpenAI's GPT model with function calling to handle conversations and capture leads through Pushover notifications. """ # Import required libraries from dotenv import load_dotenv # For loading environment variables from openai import OpenAI # OpenAI API client import json # JSON processing for function calls import os # Operating system interface import requests # HTTP requests for Pushover notifications from pypdf import PdfReader # PDF text extraction import gradio as gr # Web interface framework # Load environment variables from .env file load_dotenv(override=True) # ================================ # NOTIFICATION FUNCTIONS # ================================ def push(text): """ Send a notification via Pushover API. Args: text (str): The message text to send """ requests.post( "https://api.pushover.net/1/messages.json", data={ "token": os.getenv("PUSHOVER_TOKEN"), "user": os.getenv("PUSHOVER_USER"), "message": text, } ) # ================================ # TOOL FUNCTIONS FOR OPENAI # ================================ def record_user_details(email, name="Name not provided", notes="not provided"): """ Record user contact details and send notification. This function is called by OpenAI when a user provides their contact information. Args: email (str): User's email address (required) name (str): User's name (optional) notes (str): Additional conversation context (optional) Returns: dict: Success confirmation for OpenAI """ push(f"Recording {name} with email {email} and notes {notes}") return {"recorded": "ok"} def record_unknown_question(question): """ Record questions the chatbot couldn't answer. This function is called by OpenAI when encountering unknown questions to help improve the chatbot's knowledge base. Args: question (str): The question that couldn't be answered Returns: dict: Success confirmation for OpenAI """ push(f"Recording {question}") return {"recorded": "ok"} # ================================ # OPENAI FUNCTION SCHEMAS # ================================ # Schema definition for the user details recording function record_user_details_json = { "name": "record_user_details", "description": "Use this tool to record that a user is interested in being in touch and provided an email address", "parameters": { "type": "object", "properties": { "email": { "type": "string", "description": "The email address of this user" }, "name": { "type": "string", "description": "The user's name, if they provided it" }, "notes": { "type": "string", "description": "Any additional information about the conversation that's worth recording to give context" } }, "required": ["email"], "additionalProperties": False } } # Schema definition for the unknown question recording function record_unknown_question_json = { "name": "record_unknown_question", "description": "Always use this tool to record any question that couldn't be answered as you didn't know the answer", "parameters": { "type": "object", "properties": { "question": { "type": "string", "description": "The question that couldn't be answered" }, }, "required": ["question"], "additionalProperties": False } } # Combined tools list for OpenAI function calling tools = [ {"type": "function", "function": record_user_details_json}, {"type": "function", "function": record_unknown_question_json} ] # ================================ # MAIN CHATBOT CLASS # ================================ class Me: """ Main chatbot class that handles conversations and impersonates the owner. This class loads profile data, manages OpenAI interactions, and handles function calling for lead capture and question tracking. """ def __init__(self): """ Initialize the chatbot with profile data and OpenAI client. Loads LinkedIn PDF and summary text file to create the chatbot's knowledge base about the owner. """ # Initialize OpenAI client self.openai = OpenAI() # Set the owner's name (hardcoded for now) self.name = "Gowrisankar" # Load LinkedIn profile from PDF reader = PdfReader("documents/linkedin.pdf") self.linkedin = "" for page in reader.pages: text = page.extract_text() if text: self.linkedin += text # Load personal summary from text file with open("documents/summary.txt", "r", encoding="utf-8") as f: self.summary = f.read() def handle_tool_call(self, tool_calls): """ Execute OpenAI function calls and return results. This method processes tool calls from OpenAI, executes the corresponding Python functions, and formats the results for the conversation. Args: tool_calls: List of tool calls from OpenAI response Returns: list: Formatted tool results for OpenAI conversation """ results = [] for tool_call in tool_calls: # Extract tool name and arguments tool_name = tool_call.function.name arguments = json.loads(tool_call.function.arguments) print(f"Tool called: {tool_name}", flush=True) # Get the corresponding Python function and execute it tool = globals().get(tool_name) result = tool(**arguments) if tool else {} # Format result for OpenAI results.append({ "role": "tool", "content": json.dumps(result), "tool_call_id": tool_call.id }) return results def system_prompt(self): """ Generate the system prompt with owner's profile data. Creates a comprehensive system prompt that instructs the AI to impersonate the owner using their LinkedIn profile and summary information. Returns: str: Complete system prompt for OpenAI """ system_prompt = f"""You are acting as {self.name}. You are answering questions on {self.name}'s website, \ particularly questions related to {self.name}'s career, background, skills and experience. \ Your responsibility is to represent {self.name} for interactions on the website as faithfully as possible. \ You are given a summary of {self.name}'s background and LinkedIn profile which you can use to answer questions. \ Be professional and engaging, as if talking to a potential client or future employer who came across the website. \ If 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. \ If 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.""" # Add profile data to the prompt system_prompt += f"\n\n## Summary:\n{self.summary}\n\n## LinkedIn Profile:\n{self.linkedin}\n\n" system_prompt += f"With this context, please chat with the user, always staying in character as {self.name}." return system_prompt def chat(self, message, history): """ Handle a chat message and return the AI response. This method implements the conversation loop with OpenAI, handling function calls and continuing the conversation until a final response. Args: message (str): User's input message history (list): Previous conversation history Returns: str: AI's response message """ # Build complete message history including system prompt messages = [ {"role": "system", "content": self.system_prompt()} ] + history + [ {"role": "user", "content": message} ] # Continue conversation until no more function calls done = False while not done: # Get response from OpenAI response = self.openai.chat.completions.create( model="gpt-4o-mini", messages=messages, tools=tools ) # Check if OpenAI wants to call functions if response.choices[0].finish_reason == "tool_calls": # Extract and execute function calls message_with_tools = response.choices[0].message tool_calls = message_with_tools.tool_calls tool_results = self.handle_tool_call(tool_calls) # Add function call and results to conversation messages.append(message_with_tools) messages.extend(tool_results) else: # No more function calls, conversation is complete done = True return response.choices[0].message.content # ================================ # APPLICATION ENTRY POINT # ================================ if __name__ == "__main__": # Initialize the chatbot me = Me() # Create and launch the Gradio web interface # type="messages" enables proper conversation history handling gr.ChatInterface(me.chat, type="messages", cache_examples=False).launch()