import gradio as gr import requests import os import json class AutonomousEmailAgent: def __init__(self, linkedin_url, company_name, role, word_limit, user_name, email, phone, linkedin): self.linkedin_url = linkedin_url self.company_name = company_name self.role = role self.word_limit = word_limit self.user_name = user_name self.email = email self.phone = phone self.linkedin = linkedin self.bio = None self.skills = [] self.experiences = [] self.company_info = None self.role_description = None self.attempts = 0 # Counter for iterations self.max_attempts = 5 # Set maximum number of iterations def fetch_linkedin_data(self): proxycurl_api_key = os.getenv("PROXYCURL_API_KEY") if not self.linkedin_url: print("Action: No LinkedIn URL provided, using default bio.") self.use_default_profile() else: print("Action: Fetching LinkedIn data via Proxycurl.") headers = {"Authorization": f"Bearer {proxycurl_api_key}"} url = f"https://nubela.co/proxycurl/api/v2/linkedin?url={self.linkedin_url}" response = requests.get(url, headers=headers) if response.status_code == 200: data = response.json() self.bio = data.get("summary", "No bio available") self.skills = data.get("skills", []) self.experiences = data.get("experiences", []) print("LinkedIn data fetched successfully.") else: print("Error: Unable to fetch LinkedIn profile. Status Code:", response.status_code) self.use_default_profile() def use_default_profile(self): print("Using default profile values.") self.bio = "A professional with a versatile background and extensive experience." self.skills = ["Leadership", "Communication", "Problem-solving"] self.experiences = [{"title": "Project Manager"}, {"title": "Team Leader"}] def run(self): self.fetch_linkedin_data() return self.autonomous_reasoning() def autonomous_reasoning(self): print("Autonomous Reasoning: Letting the LLM fully reason and act on available data...") reasoning_prompt = f""" You are an AI agent tasked with generating a professional job application email using Simon Sinek's Start with Why model. The email must start with why the candidate is passionate about the role, then explain how their skills and experience align with the company and role, and finally describe specific achievements that demonstrate their capabilities. Make sure the email encourages the employer to engage further and ends on a positive note. Here’s the current data: - LinkedIn profile: {self.linkedin_url} - Company Name: {self.company_name} - Role: {self.role} - Candidate's Bio: {self.bio} - Candidate's Skills: {', '.join(self.skills)} - Candidate's Experiences: {', '.join([exp['title'] for exp in self.experiences])} Ensure the email is formatted correctly and adheres to a maximum of {self.word_limit} words. """ return self.send_request_to_llm(reasoning_prompt) def send_request_to_llm(self, prompt): print("Sending request to Groq Cloud LLM...") api_key = os.getenv("GROQ_API_KEY") if not api_key: print("Error: API key not found. Please set the GROQ_API_KEY environment variable.") return "Error: API key not found." headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } data = { "model": "llama-3.1-70b-versatile", "messages": [{"role": "user", "content": prompt}] } response = requests.post("https://api.groq.com/openai/v1/chat/completions", headers=headers, json=data) print(f"Status Code: {response.status_code}") if response.status_code == 200: try: result = response.json() print(f"LLM Response: {json.dumps(result, indent=2)}") choices = result.get("choices", []) if choices and "message" in choices[0]: content = choices[0]["message"]["content"] print(f"Content: {content}") return self.act_on_llm_instructions(content) else: print("Error: Unrecognized format in LLM response.") return "Error: Unrecognized response format." except json.JSONDecodeError: print("Error: Response from Groq Cloud LLM is not valid JSON.") return "Error: Response is not in JSON format." else: print(f"Error: Unable to connect to Groq Cloud LLM. Status Code: {response.status_code}") return "Error: Unable to generate response." def act_on_llm_instructions(self, llm_response): if self.attempts >= self.max_attempts: print("Max attempts reached. Proceeding with fallback option.") return self.generate_fallback_email() print(f"LLM Instruction: {llm_response}") if "scrape" in llm_response.lower(): self.attempts += 1 print(f"Scraping attempt {self.attempts}...") return self.autonomous_reasoning() elif "generate_email" in llm_response.lower(): return self.format_email(llm_response) elif "fallback" in llm_response.lower(): return self.generate_fallback_email() else: print("Error: Unrecognized instruction from LLM. Proceeding with available data.") self.attempts += 1 return self.autonomous_reasoning() def format_email(self, llm_response): # Clean and format the email lines = [line.strip() for line in llm_response.split("\n") if line.strip()] formatted_email = "\n\n".join(lines) # Truncate the email if it exceeds the word limit words = formatted_email.split() if len(words) > self.word_limit: truncated_email = " ".join(words[:self.word_limit]) + "..." formatted_email = truncated_email # Add a call to action in the closing section closing_section = ( "\n\nI would love the opportunity to discuss how my background and skills align with the goals of " f"{self.company_name}. I am eager to contribute and support the mission of your organization.\n\n" "Thank you for considering my application. I look forward to hearing from you.\n" ) # Prepare the signature signature = ( f"Best regards,\n{self.user_name}\n" f"Email: {self.email}\nPhone: {self.phone}\nLinkedIn: {self.linkedin}" ) # Ensure only one "Best regards" section and remove any duplicate signatures if "Best regards" in formatted_email: formatted_email = formatted_email.split("Best regards")[0].strip() return f"{formatted_email}{closing_section}\n{signature}" def generate_fallback_email(self): # Generate a more impactful fallback email if max attempts are reached return f"""Subject: Application for {self.role} at {self.company_name} Dear Hiring Manager, I am excited to apply for the {self.role} position at {self.company_name}. My experience in business development and leadership has prepared me to make a significant impact in this role. I have led global marketing efforts, managed international teams, and developed strategic initiatives that align closely with the goals of your organization. I would appreciate the opportunity to discuss how my skills can contribute to {self.company_name}'s mission and success. Please feel free to contact me at your earliest convenience. Best regards, {self.user_name} Email: {self.email} Phone: {self.phone} LinkedIn: {self.linkedin} """ # Gradio UI setup remains unchanged def gradio_ui(): name_input = gr.Textbox(label="Your Name", placeholder="Enter your name") company_input = gr.Textbox(label="Company Name or URL", placeholder="Enter the company name or website URL") role_input = gr.Textbox(label="Role Applying For", placeholder="Enter the role you are applying for") email_input = gr.Textbox(label="Your Email Address", placeholder="Enter your email address") phone_input = gr.Textbox(label="Your Phone Number", placeholder="Enter your phone number") linkedin_input = gr.Textbox(label="Your LinkedIn URL", placeholder="Enter your LinkedIn profile URL") word_limit_slider = gr.Slider(minimum=50, maximum=300, step=10, label="Email Word Limit", value=150) email_output = gr.Textbox(label="Generated Email", placeholder="Your generated email will appear here", lines=10) def create_email(name, company_name, role, email, phone, linkedin_url, word_limit): agent = AutonomousEmailAgent(linkedin_url, company_name, role, word_limit, name, email, phone, linkedin_url) return agent.run() demo = gr.Interface( fn=create_email, inputs=[name_input, company_input, role_input, email_input, phone_input, linkedin_input, word_limit_slider], outputs=[email_output], title="Email Writing AI Agent with ReAct", description="Generates a job application email using dynamic and adaptive reasoning." ) demo.launch() if __name__ == "__main__": gradio_ui()