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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Deploys the LangGraph agent with a feature-rich Gradio UI on Hugging Face Spaces.
|
| 2 |
+
|
| 3 |
+
# 1. IMPORTS AND SETUP
|
| 4 |
+
import os
|
| 5 |
+
import uuid
|
| 6 |
+
import gradio as gr
|
| 7 |
+
from typing import TypedDict, List, Optional
|
| 8 |
+
from langchain_openai import ChatOpenAI
|
| 9 |
+
from langchain_core.prompts import ChatPromptTemplate
|
| 10 |
+
from langchain_core.tools import tool
|
| 11 |
+
from langchain_core.pydantic_v1 import BaseModel, Field
|
| 12 |
+
from langgraph.graph import StateGraph, END
|
| 13 |
+
import requests
|
| 14 |
+
from bs4 import BeautifulSoup
|
| 15 |
+
from PyPDF2 import PdfReader
|
| 16 |
+
from threading import Thread
|
| 17 |
+
|
| 18 |
+
# Import the stream_executor to allow the UI to update progressively
|
| 19 |
+
from langchain.callbacks.base import BaseCallbackHandler
|
| 20 |
+
from langchain_core.runnables import RunnableConfig
|
| 21 |
+
|
| 22 |
+
print("--- Libraries imported. ---")
|
| 23 |
+
|
| 24 |
+
# IMPORTANT: Set your API keys in the Hugging Face Space "Secrets"
|
| 25 |
+
# The names should be OPENAI_API_KEY, LANGCHAIN_API_KEY, and TAVILY_API_KEY
|
| 26 |
+
os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
|
| 27 |
+
os.environ["LANGCHAIN_API_KEY"] = os.getenv("LANGCHAIN_API_KEY")
|
| 28 |
+
os.environ["TAVILY_API_KEY"] = os.getenv("TAVILY_API_KEY")
|
| 29 |
+
os.environ["LANGCHAIN_TRACING_V2"] = "true"
|
| 30 |
+
os.environ["LANGCHAIN_PROJECT"] = "Deployed Career Navigator"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# 2. LANGGRAPH AGENT BACKEND (The "Brain" of the App)
|
| 34 |
+
|
| 35 |
+
# Pydantic Models for structured data
|
| 36 |
+
class SkillAnalysis(BaseModel):
|
| 37 |
+
technical_skills: List[str] = Field(description="List of top 5 technical skills.")
|
| 38 |
+
soft_skills: List[str] = Field(description="List of top 3 soft skills.")
|
| 39 |
+
|
| 40 |
+
class ResumeFeedback(BaseModel):
|
| 41 |
+
strengths: List[str] = Field(description="Resume strengths.")
|
| 42 |
+
gaps: List[str] = Field(description="Missing skills or experiences.")
|
| 43 |
+
suggestions: List[str] = Field(description="Suggestions for improvement.")
|
| 44 |
+
|
| 45 |
+
class CareerActionPlan(BaseModel):
|
| 46 |
+
career_overview: str = Field(description="Overview of the chosen career.")
|
| 47 |
+
skill_analysis: SkillAnalysis
|
| 48 |
+
resume_feedback: ResumeFeedback
|
| 49 |
+
learning_roadmap: str = Field(description="Markdown-formatted learning plan.")
|
| 50 |
+
portfolio_plan: str = Field(description="Markdown-formatted portfolio project plan.")
|
| 51 |
+
|
| 52 |
+
# Agent State
|
| 53 |
+
class TeamState(TypedDict):
|
| 54 |
+
student_interests: str
|
| 55 |
+
student_resume: str
|
| 56 |
+
career_options: List[str]
|
| 57 |
+
chosen_career: str
|
| 58 |
+
market_analysis: Optional[SkillAnalysis]
|
| 59 |
+
resume_analysis: Optional[ResumeFeedback]
|
| 60 |
+
final_plan: Optional[CareerActionPlan]
|
| 61 |
+
|
| 62 |
+
# Tools
|
| 63 |
+
@tool
|
| 64 |
+
def scrape_web_content(url: str) -> str:
|
| 65 |
+
"""Scrapes text content from a URL."""
|
| 66 |
+
try:
|
| 67 |
+
response = requests.get(url, timeout=10)
|
| 68 |
+
soup = BeautifulSoup(response.content, 'html.parser')
|
| 69 |
+
return soup.get_text(separator=' ', strip=True)[:10000]
|
| 70 |
+
except requests.RequestException:
|
| 71 |
+
return "Error: Could not scrape the URL."
|
| 72 |
+
|
| 73 |
+
# Specialist Agents
|
| 74 |
+
llm = ChatOpenAI(model="gpt-4o", temperature=0)
|
| 75 |
+
|
| 76 |
+
def job_market_analyst_agent(state: TeamState):
|
| 77 |
+
# This is a simplified version for faster UI response. A full version would be more robust.
|
| 78 |
+
print("--- 🕵️ Agent: Job Market Analyst ---")
|
| 79 |
+
structured_llm = llm.with_structured_output(SkillAnalysis)
|
| 80 |
+
prompt = ChatPromptTemplate.from_template(
|
| 81 |
+
"You are an expert job market analyst. Based on the career of '{career}', identify the top 5 technical skills and top 3 soft skills required."
|
| 82 |
+
)
|
| 83 |
+
chain = prompt | structured_llm
|
| 84 |
+
analysis = chain.invoke({"career": state['chosen_career']})
|
| 85 |
+
return {"market_analysis": analysis}
|
| 86 |
+
|
| 87 |
+
def resume_reviewer_agent(state: TeamState):
|
| 88 |
+
print("--- 📝 Agent: Resume Reviewer ---")
|
| 89 |
+
structured_llm = llm.with_structured_output(ResumeFeedback)
|
| 90 |
+
prompt = ChatPromptTemplate.from_messages([
|
| 91 |
+
("system", "You are an expert career coach. Compare the user's resume with the provided analysis of in-demand skills and provide feedback."),
|
| 92 |
+
("human", "User's Resume:\n{resume}\n\nRequired Skills Analysis:\n{skill_analysis}")
|
| 93 |
+
])
|
| 94 |
+
chain = prompt | structured_llm
|
| 95 |
+
feedback = chain.invoke({
|
| 96 |
+
"resume": state["student_resume"],
|
| 97 |
+
"skill_analysis": state["market_analysis"].dict()
|
| 98 |
+
})
|
| 99 |
+
return {"resume_analysis": feedback}
|
| 100 |
+
|
| 101 |
+
def lead_agent_node(state: TeamState):
|
| 102 |
+
print("--- 👑 Agent: Lead Agent (Synthesizing & Planning) ---")
|
| 103 |
+
structured_llm = llm.with_structured_output(CareerActionPlan)
|
| 104 |
+
prompt = ChatPromptTemplate.from_template(
|
| 105 |
+
"You are the lead career strategist. Synthesize all the provided information into a comprehensive Career Action Plan. "
|
| 106 |
+
"Create a detailed 8-week learning roadmap and suggest 3 portfolio projects.\n\n"
|
| 107 |
+
"Chosen Career: {career}\n"
|
| 108 |
+
"Required Skills: {skills}\n"
|
| 109 |
+
"Resume Feedback: {resume_feedback}"
|
| 110 |
+
)
|
| 111 |
+
chain = prompt | structured_llm
|
| 112 |
+
final_plan = chain.invoke({
|
| 113 |
+
"career": state["chosen_career"],
|
| 114 |
+
"skills": state["market_analysis"].dict(),
|
| 115 |
+
"resume_feedback": state["resume_analysis"].dict()
|
| 116 |
+
})
|
| 117 |
+
return {"final_plan": final_plan}
|
| 118 |
+
|
| 119 |
+
# Graph Definition
|
| 120 |
+
graph_builder = StateGraph(TeamState)
|
| 121 |
+
graph_builder.add_node("analyze_market", job_market_analyst_agent)
|
| 122 |
+
graph_builder.add_node("review_resume", resume_reviewer_agent)
|
| 123 |
+
graph_builder.add_node("create_final_plan", lead_agent_node)
|
| 124 |
+
graph_builder.set_entry_point("analyze_market")
|
| 125 |
+
graph_builder.add_edge("analyze_market", "review_resume")
|
| 126 |
+
graph_builder.add_edge("review_resume", "create_final_plan")
|
| 127 |
+
graph_builder.add_edge("create_final_plan", END)
|
| 128 |
+
navigator_agent = graph_builder.compile()
|
| 129 |
+
|
| 130 |
+
print("--- LangGraph Agent Backend is ready. ---")
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# 3. HELPER FUNCTIONS FOR GRADIO
|
| 134 |
+
def extract_text_from_pdf(pdf_file):
|
| 135 |
+
"""Extracts text from an uploaded PDF file."""
|
| 136 |
+
if not pdf_file:
|
| 137 |
+
return ""
|
| 138 |
+
reader = PdfReader(pdf_file.name)
|
| 139 |
+
text = ""
|
| 140 |
+
for page in reader.pages:
|
| 141 |
+
text += page.extract_text() or ""
|
| 142 |
+
return text
|
| 143 |
+
|
| 144 |
+
def run_agent_process(resume_text, chosen_career, progress=gr.Progress(track_tqdm=True)):
|
| 145 |
+
"""The main function to run the agent and yield updates for the UI."""
|
| 146 |
+
initial_state = {
|
| 147 |
+
"student_resume": resume_text,
|
| 148 |
+
"chosen_career": chosen_career,
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
# Use a thread to run the agent so the UI doesn't block
|
| 152 |
+
final_state = navigator_agent.invoke(initial_state)
|
| 153 |
+
plan = final_state['final_plan']
|
| 154 |
+
|
| 155 |
+
return {
|
| 156 |
+
# Update UI components with the final plan
|
| 157 |
+
output_plan_state: plan,
|
| 158 |
+
output_overview: gr.update(value=f"## 1. Career Overview: {plan.career_overview}", visible=True),
|
| 159 |
+
output_skills: gr.update(
|
| 160 |
+
value=f"## 2. Job Market Skill Analysis\n**Top Technical Skills:** {', '.join(plan.skill_analysis.technical_skills)}\n\n**Top Soft Skills:** {', '.join(plan.skill_analysis.soft_skills)}",
|
| 161 |
+
visible=True
|
| 162 |
+
),
|
| 163 |
+
output_resume_feedback: gr.update(
|
| 164 |
+
value=f"## 3. Your Resume Feedback\n**Strengths:** {' '.join(plan.resume_feedback.strengths)}\n\n**Gaps to Fill:** {', '.join(plan.resume_feedback.gaps)}\n\n**Suggestions:**\n" + "\n".join([f"- {s}" for s in plan.resume_feedback.suggestions]),
|
| 165 |
+
visible=True
|
| 166 |
+
),
|
| 167 |
+
output_learning_plan: gr.update(value=f"## 4. Your 8-Week Learning Roadmap\n{plan.learning_roadmap}", visible=True),
|
| 168 |
+
output_portfolio_plan: gr.update(value=f"## 5. Your Portfolio Project Plan\n{plan.portfolio_plan}", visible=True),
|
| 169 |
+
# Hide the input section and show the output/chat sections
|
| 170 |
+
input_row: gr.update(visible=False),
|
| 171 |
+
chat_row: gr.update(visible=True)
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
def chat_with_agent(message, history, plan_state):
|
| 175 |
+
"""Handles the follow-up conversation with the agent."""
|
| 176 |
+
if not plan_state:
|
| 177 |
+
return "Please generate a plan first."
|
| 178 |
+
|
| 179 |
+
prompt = ChatPromptTemplate.from_messages([
|
| 180 |
+
("system", "You are a helpful career coach. The user has just received the following career action plan. Answer their follow-up questions based on this plan.\n\n--- CAREER PLAN ---\n{plan_text}"),
|
| 181 |
+
("human", "{user_question}")
|
| 182 |
+
])
|
| 183 |
+
|
| 184 |
+
chat_chain = prompt | llm
|
| 185 |
+
|
| 186 |
+
# Convert Pydantic model to a string for the context
|
| 187 |
+
plan_text = f"Career: {plan_state.career_overview}\nSkills: {plan_state.skill_analysis.dict()}\nResume Feedback: {plan_state.resume_feedback.dict()}\nLearning Plan: {plan_state.learning_roadmap}\nPortfolio Plan: {plan_state.portfolio_plan}"
|
| 188 |
+
|
| 189 |
+
response = chat_chain.invoke({
|
| 190 |
+
"plan_text": plan_text,
|
| 191 |
+
"user_question": message
|
| 192 |
+
})
|
| 193 |
+
|
| 194 |
+
return response.content
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
# 4. GRADIO UI DEFINITION
|
| 198 |
+
with gr.Blocks(theme=gr.themes.Soft(), css=".gradio-container {background-color: #f0f4f9;}") as demo:
|
| 199 |
+
# State object to hold the final plan for the chat
|
| 200 |
+
output_plan_state = gr.State()
|
| 201 |
+
|
| 202 |
+
gr.Markdown("# 🚀 Your AI Career Navigator")
|
| 203 |
+
gr.Markdown("Upload your resume, select a target career, and get a personalized, data-driven action plan from a team of AI agents.")
|
| 204 |
+
|
| 205 |
+
# Page 1: Input Section
|
| 206 |
+
with gr.Row(visible=True) as input_row:
|
| 207 |
+
with gr.Column(scale=1):
|
| 208 |
+
input_pdf_resume = gr.File(label="Upload Your Resume (PDF)", file_types=[".pdf"])
|
| 209 |
+
input_career_choice = gr.Dropdown(
|
| 210 |
+
label="Select Your Target Career",
|
| 211 |
+
choices=["Data Analyst", "Software Engineer", "Product Manager", "UX Designer", "AI/ML Engineer"],
|
| 212 |
+
value="Data Analyst"
|
| 213 |
+
)
|
| 214 |
+
submit_button = gr.Button("Generate My Action Plan", variant="primary")
|
| 215 |
+
|
| 216 |
+
# Page 2: Output Section (initially hidden)
|
| 217 |
+
with gr.Column(visible=False) as output_col:
|
| 218 |
+
output_overview = gr.Markdown(visible=False)
|
| 219 |
+
output_skills = gr.Markdown(visible=False)
|
| 220 |
+
output_resume_feedback = gr.Markdown(visible=False)
|
| 221 |
+
output_learning_plan = gr.Markdown(visible=False)
|
| 222 |
+
output_portfolio_plan = gr.Markdown(visible=False)
|
| 223 |
+
|
| 224 |
+
# Page 2: Chat Section (initially hidden)
|
| 225 |
+
with gr.Row(visible=False) as chat_row:
|
| 226 |
+
chat_interface = gr.ChatInterface(
|
| 227 |
+
chat_with_agent,
|
| 228 |
+
chatbot=gr.Chatbot(height=400),
|
| 229 |
+
additional_inputs=[output_plan_state],
|
| 230 |
+
title="Ask Follow-up Questions",
|
| 231 |
+
description="Ask any questions about your generated plan."
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
# Event Handling
|
| 235 |
+
submit_button.click(
|
| 236 |
+
fn=extract_text_from_pdf,
|
| 237 |
+
inputs=[input_pdf_resume],
|
| 238 |
+
outputs=None # We will use the result in the next step
|
| 239 |
+
).then(
|
| 240 |
+
fn=run_agent_process,
|
| 241 |
+
inputs=[lambda *args: args[0], input_career_choice],
|
| 242 |
+
outputs=[
|
| 243 |
+
output_plan_state,
|
| 244 |
+
output_overview,
|
| 245 |
+
output_skills,
|
| 246 |
+
output_resume_feedback,
|
| 247 |
+
output_learning_plan,
|
| 248 |
+
output_portfolio_plan,
|
| 249 |
+
input_row,
|
| 250 |
+
chat_row
|
| 251 |
+
]
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
# Launch the app
|
| 255 |
+
if __name__ == "__main__":
|
| 256 |
+
demo.launch(debug=True)
|