File size: 8,434 Bytes
2f50c94
b6a2224
37185e0
8d271f0
37185e0
0c3b71f
41f95b2
0707373
 
 
 
41f95b2
 
 
 
0707373
 
 
 
 
e1218a1
37185e0
22cd231
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f18b18e
 
 
 
 
 
 
 
 
 
 
 
 
 
22cd231
0c3b71f
 
 
b6a2224
 
0c3b71f
b6a2224
e7bb3db
0c3b71f
 
 
 
 
 
f18b18e
e7bb3db
f18b18e
 
0c3b71f
e7bb3db
0c3b71f
e7bb3db
8d271f0
 
67c2abc
8d271f0
 
 
67c2abc
 
 
 
8d271f0
 
 
 
 
f18b18e
8d271f0
 
 
 
67c2abc
8d271f0
b682b3b
f18b18e
 
b020659
 
 
 
 
 
 
 
b682b3b
 
 
8d271f0
f18b18e
8d271f0
bd877a9
e7bb3db
0c3b71f
f18b18e
e7bb3db
 
f18b18e
0c3b71f
 
f18b18e
e7bb3db
 
 
0c3b71f
e7bb3db
 
0c3b71f
f18b18e
22cd231
f18b18e
 
 
 
 
22cd231
f18b18e
22cd231
f18b18e
22cd231
 
 
 
 
 
 
f18b18e
22cd231
f18b18e
7ea79b0
 
 
 
 
 
 
ebcf536
7ea79b0
 
 
0c3b71f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
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

    # Fetch LinkedIn data via Proxycurl
    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.bio = "A professional with diverse experience."
            self.skills = ["Adaptable", "Hardworking"]
            self.experiences = ["Worked across various industries"]
        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()

    # Set default profile information if LinkedIn scraping fails
    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"}]

    # Main loop following ReAct pattern
    def run(self):
        self.fetch_linkedin_data()
        return self.autonomous_reasoning()

    # Reason and Act via LLM: Let the LLM control reasoning and actions dynamically
    def autonomous_reasoning(self):
        print("Autonomous Reasoning: Letting the LLM fully reason and act on available data...")
        
        reasoning_prompt = f"""
        You are an autonomous agent responsible for generating a job application email.
        
        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])}

        Based on this data, decide if it is sufficient to generate the email. If some information is missing or insufficient, respond with:
        1. "generate_email" to proceed with the email generation using available data.
        2. "fallback" to use default values.

        After generating the email, reflect on whether the content aligns with the role and company and whether any improvements are needed. Respond clearly with one of the above options.
        """
        
        return self.send_request_to_llm(reasoning_prompt)

    # Send request to Groq Cloud LLM with enhanced debugging and error handling
    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."

    # Function to act on the LLM's structured instructions
    def act_on_llm_instructions(self, reasoning_output):
        print(f"LLM Instruction: {reasoning_output}")
        instruction = reasoning_output.lower().strip()

        if "generate_email" in instruction:
            return self.generate_email()

        elif "fallback" in instruction:
            print("Action: Using fallback values for missing data.")
            return self.generate_email()

        else:
            print("Error: Unrecognized instruction from LLM. Proceeding with available data.")
            return self.generate_email()

    # Generate email based on the collected data
    def generate_email(self):
        print("Generating email based on the provided and/or fallback data...")
        email_content = f"""
        Subject: Application for {self.role} at {self.company_name}
        
        Dear Hiring Manager,

        I am excited to apply for the {self.role} role at {self.company_name}. With a strong background in {self.bio}, I believe my skills in {', '.join(self.skills)} would make me a valuable addition to your team.

        Please find my LinkedIn profile for more details: {self.linkedin}

        Best regards,
        {self.user_name}
        Email: {self.email}
        Phone: {self.phone}
        LinkedIn: {self.linkedin}
        """
        return email_content

# 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="Generate a professional email for a job application using LinkedIn data, company info, and role description.",
        allow_flagging="never"
    )
    
    demo.launch()

if __name__ == "__main__":
    gradio_ui()