Spaces:
Sleeping
Sleeping
| from dotenv import load_dotenv | |
| from openai import OpenAI | |
| import json | |
| import os | |
| import requests | |
| from pypdf import PdfReader | |
| import gradio as gr | |
| # Try to load .env for local development, but don't fail in HF Spaces | |
| try: | |
| load_dotenv(override=True) | |
| except: | |
| pass # In HF Spaces, secrets are loaded automatically | |
| def push(text): | |
| """Send push notification via Pushover API""" | |
| try: | |
| requests.post( | |
| "https://api.pushover.net/1/messages.json", | |
| data={ | |
| "token": os.getenv("PUSHOVER_TOKEN"), | |
| "user": os.getenv("PUSHOVER_USER"), | |
| "message": text, | |
| }, | |
| timeout=5 # Add timeout to prevent hanging | |
| ) | |
| except Exception as e: | |
| print(f"Failed to send push notification: {e}") | |
| def record_user_details(email, name="Name not provided", notes="not provided"): | |
| push(f"Recording {name} with email {email} and notes {notes}") | |
| return {"recorded": "ok"} | |
| def record_unknown_question(question): | |
| push(f"Recording {question}") | |
| return {"recorded": "ok"} | |
| 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 | |
| } | |
| } | |
| 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 | |
| } | |
| } | |
| tools = [{"type": "function", "function": record_user_details_json}, | |
| {"type": "function", "function": record_unknown_question_json}] | |
| class Me: | |
| def __init__(self): | |
| # Initialize OpenAI client | |
| api_key = os.getenv("OPENAI_API_KEY") | |
| if not api_key: | |
| raise ValueError("OPENAI_API_KEY not found in environment variables") | |
| self.openai = OpenAI(api_key=api_key) | |
| self.name = "Varun Singh" | |
| # Load LinkedIn PDF with error handling | |
| try: | |
| reader = PdfReader("me/linkedin.pdf") | |
| self.linkedin = "" | |
| for page in reader.pages: | |
| text = page.extract_text() | |
| if text: | |
| self.linkedin += text | |
| except FileNotFoundError: | |
| print("Warning: me/linkedin.pdf not found") | |
| self.linkedin = "LinkedIn profile information not available." | |
| except Exception as e: | |
| print(f"Error reading LinkedIn PDF: {e}") | |
| self.linkedin = "LinkedIn profile could not be loaded." | |
| # Load summary with error handling | |
| try: | |
| with open("me/summary.txt", "r", encoding="utf-8") as f: | |
| self.summary = f.read() | |
| except FileNotFoundError: | |
| print("Warning: me/summary.txt not found") | |
| self.summary = "Professional summary not available." | |
| except Exception as e: | |
| print(f"Error reading summary: {e}") | |
| self.summary = "Summary could not be loaded." | |
| def handle_tool_call(self, tool_calls): | |
| results = [] | |
| for tool_call in tool_calls: | |
| tool_name = tool_call.function.name | |
| arguments = json.loads(tool_call.function.arguments) | |
| print(f"Tool called: {tool_name}", flush=True) | |
| tool = globals().get(tool_name) | |
| try: | |
| result = tool(**arguments) if tool else {"error": "Tool not found"} | |
| except Exception as e: | |
| result = {"error": f"Tool execution failed: {str(e)}"} | |
| print(f"Error executing {tool_name}: {e}") | |
| results.append({ | |
| "role": "tool", | |
| "content": json.dumps(result), | |
| "tool_call_id": tool_call.id | |
| }) | |
| return results | |
| def system_prompt(self): | |
| 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.""" | |
| 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): | |
| try: | |
| messages = [{"role": "system", "content": self.system_prompt()}] + history + [{"role": "user", "content": message}] | |
| done = False | |
| while not done: | |
| response = self.openai.chat.completions.create( | |
| model="gpt-4o-mini", | |
| messages=messages, | |
| tools=tools, | |
| timeout=30 # Add timeout | |
| ) | |
| if response.choices[0].finish_reason == "tool_calls": | |
| message = response.choices[0].message | |
| tool_calls = message.tool_calls | |
| results = self.handle_tool_call(tool_calls) | |
| messages.append(message) | |
| messages.extend(results) | |
| else: | |
| done = True | |
| return response.choices[0].message.content | |
| except Exception as e: | |
| error_msg = f"I apologize, but I encountered an error: {str(e)}. Please try again." | |
| print(f"Chat error: {e}") | |
| return error_msg | |
| if __name__ == "__main__": | |
| try: | |
| me = Me() | |
| # Create the chat interface with custom theme | |
| with gr.Blocks(theme="soft", css=""" | |
| .header-container { | |
| text-align: center; | |
| padding: 20px 0 10px 0; | |
| } | |
| .description-text { | |
| font-size: 1.1em; | |
| color: #666; | |
| margin: 10px 0 20px 0; | |
| } | |
| .examples-header { | |
| font-size: 1.1em; | |
| font-weight: 600; | |
| margin: 20px 0 15px 0; | |
| color: #2c3e50; | |
| text-align: center; | |
| } | |
| .example-button { | |
| background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%) !important; | |
| border: 1px solid #d1d9e0 !important; | |
| border-radius: 25px !important; | |
| color: #34495e !important; | |
| transition: all 0.3s ease !important; | |
| backdrop-filter: blur(5px) !important; | |
| box-shadow: 0 2px 8px rgba(0,0,0,0.1) !important; | |
| margin: 5px !important; | |
| } | |
| .example-button:hover { | |
| border-color: #3498db !important; | |
| color: #2980b9 !important; | |
| transform: translateY(-2px) !important; | |
| box-shadow: 0 4px 12px rgba(52, 152, 219, 0.2) !important; | |
| background: rgba(255, 255, 255, 0.95) !important; | |
| } | |
| """) as demo: | |
| # Header section | |
| with gr.Row(): | |
| with gr.Column(): | |
| gr.Markdown(f""" | |
| <div class="header-container"> | |
| <h1>Chat with {me.name}</h1> | |
| <p class="description-text">I'm here to discuss my career, background, skills, and experience. Ask me anything!</p> | |
| </div> | |
| """) | |
| # Chat interface | |
| chatbot = gr.ChatInterface( | |
| me.chat, | |
| type="messages" | |
| ) | |
| # Example questions section below chat | |
| with gr.Row(): | |
| with gr.Column(): | |
| gr.Markdown("**Example questions to get started:**", elem_classes="examples-header") | |
| # Create clickable buttons for example questions | |
| with gr.Row(): | |
| btn1 = gr.Button("Tell me about your background", variant="secondary", size="sm", elem_classes="example-button") | |
| btn2 = gr.Button("What kind of AI use cases have you worked on?", variant="secondary", size="sm", elem_classes="example-button") | |
| with gr.Row(): | |
| btn3 = gr.Button("I'd like to get in touch about a potential opportunity", variant="secondary", size="sm", elem_classes="example-button") | |
| btn4 = gr.Button("What are your key achievements?", variant="secondary", size="sm", elem_classes="example-button") | |
| # Functions to handle button clicks and add messages to chat | |
| def send_question_1(history): | |
| question = "Tell me about your background" | |
| history.append({"role": "user", "content": question}) | |
| response = me.chat(question, history[:-1]) # Pass history without the current message | |
| history.append({"role": "assistant", "content": response}) | |
| return history, "" | |
| def send_question_2(history): | |
| question = "What kind of AI use cases have you worked on?" | |
| history.append({"role": "user", "content": question}) | |
| response = me.chat(question, history[:-1]) | |
| history.append({"role": "assistant", "content": response}) | |
| return history, "" | |
| def send_question_3(history): | |
| question = "I'd like to get in touch about a potential opportunity" | |
| history.append({"role": "user", "content": question}) | |
| response = me.chat(question, history[:-1]) | |
| history.append({"role": "assistant", "content": response}) | |
| return history, "" | |
| def send_question_4(history): | |
| question = "What are your key achievements?" | |
| history.append({"role": "user", "content": question}) | |
| response = me.chat(question, history[:-1]) | |
| history.append({"role": "assistant", "content": response}) | |
| return history, "" | |
| # Connect buttons to directly trigger chat responses | |
| btn1.click(send_question_1, inputs=[chatbot.chatbot], outputs=[chatbot.chatbot, chatbot.textbox]) | |
| btn2.click(send_question_2, inputs=[chatbot.chatbot], outputs=[chatbot.chatbot, chatbot.textbox]) | |
| btn3.click(send_question_3, inputs=[chatbot.chatbot], outputs=[chatbot.chatbot, chatbot.textbox]) | |
| btn4.click(send_question_4, inputs=[chatbot.chatbot], outputs=[chatbot.chatbot, chatbot.textbox]) | |
| # Footer | |
| gr.Markdown(""" | |
| <div style="text-align: center; margin-top: 20px; color: #888; font-size: 0.9em;"> | |
| Feel free to ask me anything about my professional experience, or reach out if you'd like to connect! | |
| </div> | |
| """) | |
| demo.launch(share=True) | |
| except Exception as e: | |
| print(f"Failed to start application: {e}") | |
| # Create a simple error interface if initialization fails | |
| def error_chat(message, history): | |
| return "I apologize, but the chatbot is not properly configured. Please check the application logs." | |
| gr.ChatInterface( | |
| error_chat, | |
| type="messages", | |
| title="Configuration Error", | |
| description="The application encountered an error during startup." | |
| ).launch(share=True) |