File size: 8,853 Bytes
400920d
 
 
75736bd
 
 
400920d
75736bd
400920d
75736bd
400920d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75736bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
400920d
 
 
 
 
 
 
75736bd
400920d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75736bd
400920d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from langchain_groq import ChatGroq
import json
import streamlit as st
import requests
from bs4 import BeautifulSoup
from utils import embedding_model, get_pinecone_index, save_application

# ---------- Groq LLM ----------
llm = ChatGroq(
    model="llama-3.3-70b-versatile",
    temperature=0.3,
    groq_api_key=st.secrets["GROQ_API_KEY"]
)

class ProfileParserAgent:
    def run(self, resume_text):
        prompt = f"""Extract structured candidate profile. Return JSON:
        {{
            "full_name": "...",
            "skills": ["skill1", "skill2"],
            "experience_years": number,
            "education": "degree",
            "certifications": [...]
        }}
        Resume: {resume_text}
        """
        resp = llm.invoke(prompt)
        try:
            return json.loads(resp.content)
        except:
            return {"full_name": "Candidate", "skills": ["Python", "AI"], "experience_years": 2, "education": "BSc CS", "certifications": []}

class JobSearchAgent:
    def run(self, job_titles, locations):
        """
        Real-time job search:
        1. Try SERP API if API key exists
        2. Fallback to free job APIs (Arbeitnow, RemoteOK)
        3. Final fallback to mock data
        """
        jobs = []
        serp_key = st.secrets.get("SERPAPI_API_KEY", None)
        
        # Option 1: Use SERP API
        if serp_key:
            try:
                for title in job_titles:
                    params = {
                        "api_key": serp_key,
                        "engine": "google_jobs",
                        "q": title,
                        "location": locations[0] if locations else "Remote"
                    }
                    response = requests.get("https://serpapi.com/search", params=params)
                    data = response.json()
                    if "jobs_results" in data:
                        for job in data["jobs_results"]:
                            jobs.append({
                                "title": job.get("title", title),
                                "company": job.get("company_name", "Unknown"),
                                "location": job.get("location", "Remote"),
                                "description": job.get("description", "No description"),
                                "url": job.get("link", "#")
                            })
            except Exception as e:
                st.warning(f"SERP API failed: {e}. Trying free APIs...")
        
        # Option 2: Free APIs (if no SERP or SERP failed)
        if not jobs:
            # Arbeitnow API
            try:
                resp = requests.get("https://arbeitnow.com/api/job-board-api", timeout=10)
                if resp.status_code == 200:
                    data = resp.json()
                    for job in data.get("data", []):
                        if any(t.lower() in job.get("title", "").lower() for t in job_titles):
                            jobs.append({
                                "title": job.get("title", ""),
                                "company": job.get("company", ""),
                                "location": job.get("location", "Remote"),
                                "description": job.get("description", ""),
                                "url": job.get("url", "#")
                            })
            except:
                pass
            # RemoteOK API (if needed)
            if len(jobs) < 3:
                try:
                    resp = requests.get("https://remoteok.com/api", timeout=10)
                    if resp.status_code == 200:
                        data = resp.json()
                        for job in data[:20]:
                            if any(t.lower() in job.get("position", "").lower() for t in job_titles):
                                jobs.append({
                                    "title": job.get("position", ""),
                                    "company": job.get("company", ""),
                                    "location": "Remote",
                                    "description": job.get("description", ""),
                                    "url": job.get("url", "#")
                                })
                except:
                    pass
        
        # Option 3: Mock data (final fallback)
        if not jobs:
            mock_jobs = [
                {"title": "AI Engineer", "company": "HuggingFace", "location": "Remote", "description": "Build AI agents using Transformers, LangChain, Groq. Requires Python, LLMs.", "url": "https://huggingface.co/jobs"},
                {"title": "Machine Learning Engineer", "company": "Google", "location": "Remote", "description": "LLM fine-tuning, deployment. Python, TensorFlow.", "url": "https://careers.google.com"},
                {"title": "Data Scientist", "company": "Amazon", "location": "Remote", "description": "NLP, transformers, AWS.", "url": "https://amazon.jobs"}
            ]
            jobs = mock_jobs
        
        return jobs[:10]   # limit to 10 jobs

class EmbeddingGenerator:
    def generate(self, text):
        return embedding_model.encode(text).tolist()

class VectorDBStorage:
    def __init__(self):
        self.index = get_pinecone_index()
    def store_jobs(self, jobs):
        vectors = []
        for i, job in enumerate(jobs):
            job_text = f"{job['title']} {job['company']} {job['description']}"
            vec = embedding_model.encode(job_text).tolist()
            vectors.append((f"job_{i}", vec, {"title": job['title'], "company": job['company'], "description": job['description'], "url": job['url']}))
        self.index.upsert(vectors=vectors)
    def search(self, query_vec, top_k=5):
        results = self.index.query(vector=query_vec, top_k=top_k, include_metadata=True)
        return results['matches']

class MatchingRankingAgent:
    def run(self, candidate_profile, jobs_with_metadata):
        profile_text = f"Skills: {', '.join(candidate_profile.get('skills',[]))}. Experience: {candidate_profile.get('experience_years',0)} years."
        profile_vec = embedding_model.encode(profile_text).tolist()
        vdb = VectorDBStorage()
        vdb.store_jobs(jobs_with_metadata)
        matches = vdb.search(profile_vec, top_k=len(jobs_with_metadata))
        ranked = []
        for m in matches:
            ranked.append({
                "job": m['metadata'],
                "score": m['score'] * 100,
                "match_percent": round(m['score']*100, 1)
            })
        ranked.sort(key=lambda x: x['score'], reverse=True)
        return ranked

class CompanyResearchAgent:
    def run(self, company_name):
        prompt = f"Provide a concise summary of company '{company_name}': culture, tech stack, mission. Keep 80 words."
        resp = llm.invoke(prompt)
        return resp.content

class ResumeTailoringAgent:
    def run(self, original_resume_text, job_description, job_title):
        prompt = f"""Tailor the following resume to the job: {job_title}.
        Job description: {job_description}
        Original resume: {original_resume_text}
        Output a revised resume (text format) highlighting relevant skills and achievements."""
        resp = llm.invoke(prompt)
        return resp.content

class CoverLetterAgent:
    def run(self, candidate_name, job_title, company_name, job_description, skills):
        prompt = f"""Write a professional cover letter for {candidate_name} applying to {job_title} at {company_name}.
        Skills: {', '.join(skills)}.
        Job description: {job_description}
        Letter should be 150 words."""
        resp = llm.invoke(prompt)
        return resp.content

class ApplicationAgent:
    def run(self, job_url, tailored_resume, cover_letter):
        # Simulated submission – in production, use browser automation
        return {"status": "simulated_submitted", "submission_id": "hf_demo"}

class InterviewPrepAgent:
    def run(self, job_title, job_description, company_name):
        prompt = f"""Generate 5 likely interview questions and suggested answers for a {job_title} role at {company_name}.
        Job description: {job_description}
        Format: Q1: ... A1: ..."""
        resp = llm.invoke(prompt)
        return resp.content

class NotificationAgent:
    def run(self, message, channel="ui"):
        st.info(f"📢 {message}")
        return f"Sent: {message}"

class AnalyticsAgent:
    def run(self):
        from utils import get_metrics
        df = get_metrics()
        if df.empty:
            return {"total_applications": 0, "avg_match_score": 0, "submitted_count": 0}
        total = len(df)
        avg_score = df['match_score'].mean()
        submitted = len(df[df['status']=='simulated_submitted'])
        return {"total_applications": total, "avg_match_score": avg_score, "submitted_count": submitted}