File size: 12,027 Bytes
2f50c94
b6a2224
37185e0
6c7c3ab
37185e0
6c7c3ab
 
 
 
 
37185e0
0c3b71f
41f95b2
0707373
 
 
 
41f95b2
 
 
 
0707373
 
 
 
 
e50fdf4
37185e0
0c3b71f
 
 
b6a2224
e7bb3db
b6a2224
0c3b71f
b6a2224
e7bb3db
0c3b71f
 
 
 
 
 
 
 
b6a2224
e7bb3db
 
 
 
0c3b71f
e7bb3db
0c3b71f
e7bb3db
0c3b71f
6c7c3ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd877a9
e7bb3db
0c3b71f
e7bb3db
 
 
e50fdf4
 
 
0c3b71f
 
e7bb3db
0c3b71f
 
e7bb3db
 
 
 
 
 
 
 
0c3b71f
e7bb3db
 
0c3b71f
e50fdf4
 
9a87223
e50fdf4
9a87223
e50fdf4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c7c3ab
0707373
afb9ec0
ab5ba21
 
 
 
 
0707373
bd877a9
 
ab5ba21
 
 
 
 
 
 
 
 
 
 
 
bd877a9
6c7c3ab
e50fdf4
9914a2b
e50fdf4
9914a2b
e50fdf4
 
 
 
 
 
 
 
 
 
 
 
0707373
e50fdf4
 
4a2f000
6c7c3ab
0707373
6c7c3ab
e50fdf4
bc40ada
 
0707373
e50fdf4
 
 
 
 
 
 
 
 
ebcf536
 
 
e50fdf4
 
bc40ada
41f95b2
 
 
 
 
 
6c7c3ab
0707373
 
e50fdf4
6c7c3ab
 
 
 
 
 
 
 
e50fdf4
6c7c3ab
 
 
 
 
e50fdf4
6c7c3ab
7ea79b0
 
 
 
6c7c3ab
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import gradio as gr
import requests
import os
from openai import OpenAI

# Initialize the NVIDIA LLM client
client = OpenAI(
    base_url="https://integrate.api.nvidia.com/v1",
    api_key=os.getenv("NVIDIA_API_KEY")  # Use your NVIDIA API key
)

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.company_url = None  # Add company URL for scraping

    # 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...")
        
        # Modify LLM reasoning prompt to ask for clear, structured instructions
        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])}
        - Company Information: {self.company_info}
        - Role Description: {self.role_description}
        
        Based on this data, decide if it is sufficient to generate the email. If some information is missing or insufficient, respond with:
        1. "scrape" to fetch more data from the company website.
        2. "generate_email" to proceed with the email generation.
        3. "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.
        """
        
        # Send the reasoning prompt to the LLM
        completion = client.chat.completions.create(
            model="nvidia/llama-3.1-nemotron-70b-instruct",
            messages=[{"role": "user", "content": reasoning_prompt}],
            temperature=0.5,
            top_p=1,
            max_tokens=1024,
            stream=True
        )

        reasoning_output = ""
        for chunk in completion:
            if chunk.choices[0].delta.content is not None:
                print(chunk.choices[0].delta.content, end="")
                reasoning_output += chunk.choices[0].delta.content

        return self.act_on_llm_instructions(reasoning_output)

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

        if "scrape" in instruction:
            self.fetch_company_url()
            if self.company_url:
                self.fetch_company_info_with_firecrawl(self.company_url)
            return self.autonomous_reasoning()

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

        elif "fallback" in instruction:
            print("Action: Using fallback values for missing data.")
            if not self.company_info:
                self.company_info = "A leading company in its field."
            if not self.role_description:
                self.role_description = f"The role of {self.role} involves leadership and team management."
            return self.generate_email()

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

    # Fetch company URL using SERP API
    def fetch_company_url(self):
        serp_api_key = os.getenv("SERP_API_KEY")  # Fetch the SERP API key from the environment
        print(f"Fetching company URL for {self.company_name} using SERP API...")
        
        serp_url = f"https://serpapi.com/search.json?q={self.company_name}&api_key={serp_api_key}&num=1"
        response = requests.get(serp_url)
        
        if response.status_code == 200:
            serp_data = response.json()
            if 'organic_results' in serp_data and len(serp_data['organic_results']) > 0:
                self.company_url = serp_data['organic_results'][0]['link']
                print(f"Found company URL: {self.company_url}")
            else:
                print("No URL found for the company via SERP API.")
                self.company_url = None
        else:
            print(f"Error fetching company URL: {response.status_code}")
            self.company_url = None

    # Fetch LinkedIn data via Proxycurl
    def fetch_linkedin_data(self):
        proxycurl_api_key = os.getenv("PROXYCURL_API_KEY")  # Fetch API key from environment
        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", [])
            else:
                print("Error: Unable to fetch LinkedIn profile. Using default bio.")
                self.bio = "A professional with diverse experience."
                self.skills = ["Adaptable", "Hardworking"]
                self.experiences = ["Worked across various industries"]

    # Fetch company information via Firecrawl API using company URL
    def fetch_company_info_with_firecrawl(self, company_url):
        firecrawl_api_key = os.getenv("FIRECRAWL_API_KEY")  # Fetch the Firecrawl API key from the environment
        print(f"Fetching company info for {company_url} using Firecrawl.")
        
        headers = {"Authorization": f"Bearer {firecrawl_api_key}"}
        firecrawl_url = "https://api.firecrawl.dev/v1/scrape"
        data = {
            "url": company_url,
            "patterns": ["description", "about", "careers", "company overview"]
        }
        
        response = requests.post(firecrawl_url, json=data, headers=headers)
        if response.status_code == 200:
            firecrawl_data = response.json()
            self.company_info = firecrawl_data.get("description", "No detailed company info available.")
            print(f"Company info fetched: {self.company_info}")
        else:
            print(f"Error: Unable to fetch company info via Firecrawl. Using default info.")
            self.company_info = "A leading company in its field."

    # Final Action: Generate the email using NVIDIA LLM with "Start with Why" framework
    def generate_email(self):
        print("Action: Generating the email using NVIDIA LLM with the gathered information.")

        linkedin_text = f"Please find my LinkedIn profile at {self.linkedin}" if self.linkedin else ""

        prompt = f"""
        Write a professional job application email applying for the {self.role} position at {self.company_name}.

        The email should follow the "Start with Why" approach:
        1. **Why**: Begin with the candidate’s **purpose** or **belief**—why they are passionate about this role and the company. What motivates them to apply for this role? Connect their personal mission to the company's values, mission, or goals.
        2. **How**: Explain how the candidate’s skills, experience, and approach align with both their "why" and the company’s mission. This should show how they are uniquely qualified to contribute to the company’s success.
        3. **What**: Provide concrete examples of the candidate’s past achievements that support their qualifications for this role. These examples should demonstrate the candidate’s ability to succeed based on their skills and experience.
        4. **Call to Action**: End with a polite request for a meeting or further discussion to explore how the candidate can contribute to the company's success.

        Use the following information to craft the email:
        - The candidate’s LinkedIn bio: {self.bio}.
        - The candidate’s most relevant skills: {', '.join(self.skills)}.
        - The candidate’s professional experience: {', '.join([exp['title'] for exp in self.experiences])}.
        - Company information: {self.company_info}.
        - Role description: {self.role_description}.

        End the email with this signature:
        Best regards,
        {self.user_name}
        Email: {self.email}
        Phone: {self.phone}
        LinkedIn: {self.linkedin}

        The email should not exceed {self.word_limit} words.
        """

        completion = client.chat.completions.create(
            model="nvidia/llama-3.1-nemotron-70b-instruct",
            messages=[{"role": "user", "content": prompt}],
            temperature=0.5,
            top_p=1,
            max_tokens=1024,
            stream=True
        )

        generated_email = ""
        for chunk in completion:
            if chunk.choices[0].delta.content is not None:
                print(chunk.choices[0].delta.content, end="")
                generated_email += chunk.choices[0].delta.content

        return generated_email

    # Main loop following ReAct pattern
    def run(self):
        self.fetch_linkedin_data()  # Fetch LinkedIn data
        return self.autonomous_reasoning()  # Let the LLM autonomously decide and act

# Define the Gradio interface and the main app logic
def gradio_ui():
    # Input fields
    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)
    
    # Output field
    email_output = gr.Textbox(label="Generated Email", placeholder="Your generated email will appear here", lines=10)

    # Function to create and run the email agent
    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()

    # Gradio interface
    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"
    )
    
    # Launch the Gradio app
    demo.launch()

# Start the Gradio app when running the script
if __name__ == "__main__":
    gradio_ui()