Download agents.py from Ahmad140/Agent: direct link, hf CLI and curl.
- Browser
- Download file 8.85 kB
-
https://huggingface.co/spaces/Ahmad140/Agent/resolve/main/agents.py
- Command line
-
hf download hf://spaces/Ahmad140/Agent/agents.py
-
curl -L -o agents.py https://huggingface.co/spaces/Ahmad140/Agent/resolve/main/agents.py
8.85 kB
| 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} |