File size: 17,380 Bytes
0335d8f 32b2f60 0335d8f 32b2f60 0335d8f 32b2f60 0335d8f 32b2f60 0335d8f 9e02252 0335d8f 02acac5 |
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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 |
import os
import sys
import json
import time
import gradio as gr
import google.generativeai as genai
from intent_detector import detect_intent
from rag_utils import retrieve_profiles, retrieve_jobs
# 1. Configure Gemini
API_KEY = os.getenv("GOOGLE_API_KEY")
if not API_KEY:
raise ValueError("Error: Set GOOGLE_API_KEY environment variable before running.")
genai.configure(api_key=API_KEY)
# 2. System prompt with conversational onboarding flow
SYSTEM_PROMPT = """
You are a helpful AI assistant that can perform three main tasks:
1. ONBOARD – Help professionals create their profile by asking questions ONE AT A TIME in a natural conversation flow
2. SEARCH – Help find job opportunities based on user requirements
3. POST – Help clients create structured job postings
ONBOARDING CONVERSATION FLOW:
When onboarding a user, ask questions in this specific order, ONE QUESTION AT A TIME:
1. First, ask for their full name
2. Then ask what their current role/job title is
3. Then ask about their key skills (programming languages, technologies, etc.)
4. Then ask about their years of experience
5. Then ask about their preferred location or if they want remote work
6. Finally, summarize their profile and confirm if everything looks correct
IMPORTANT ONBOARDING RULES:
- Ask ONLY ONE question at a time
- Wait for the user's response before asking the next question
- Be conversational and friendly
- If they provide multiple pieces of information at once, acknowledge what they shared and ask for what's still missing
- Keep questions simple and clear
- After collecting all information, show a summary and ask for confirmation
SEARCH BEHAVIOR:
For job searches, retrieve relevant listings and present them clearly with title, company, and key details.
POST BEHAVIOR:
For job postings, help create structured JSON format job listings.
Always be helpful, conversational, and ask follow-up questions when needed.
"""
class ChatbotState:
"""Manages the conversation state for onboarding flow."""
def __init__(self):
self.reset()
def reset(self):
"""Reset the conversation state."""
self.mode = None # "onboarding", "search", "post", or None
self.onboarding_step = 0
self.user_data = {}
self.onboarding_complete = False
def is_onboarding(self):
"""Check if currently in onboarding mode."""
return self.mode == "onboarding" and not self.onboarding_complete
def get_next_onboarding_question(self):
"""Get the next question in the onboarding flow."""
questions = [
"What's your full name?",
"What's your current role or job title?",
"What are your key skills? (For example: Python, React, project management, etc.)",
"How many years of experience do you have in your field?",
"What's your preferred work location? (Or would you prefer remote work?)"
]
if self.onboarding_step < len(questions):
return questions[self.onboarding_step]
return None
def save_onboarding_data(self, field, value):
"""Save user response to onboarding data."""
fields = ["name", "role", "skills", "experience", "location"]
if self.onboarding_step < len(fields):
self.user_data[fields[self.onboarding_step]] = value
def get_onboarding_summary(self):
"""Generate a summary of collected onboarding data."""
summary = "Here's your profile summary:\n"
summary += f"• Name: {self.user_data.get('name', 'Not provided')}\n"
summary += f"• Role: {self.user_data.get('role', 'Not provided')}\n"
summary += f"• Skills: {self.user_data.get('skills', 'Not provided')}\n"
summary += f"• Experience: {self.user_data.get('experience', 'Not provided')}\n"
summary += f"• Location: {self.user_data.get('location', 'Not provided')}\n"
summary += "\nDoes this look correct? (yes/no)"
return summary
def save_user_profile(user_data, filename="data/user_profiles.jsonl"):
"""Save user profile to file."""
os.makedirs(os.path.dirname(filename), exist_ok=True)
# Create a unique ID for the user
user_id = f"user_{int(time.time())}"
profile_entry = {
"id": user_id,
"name": user_data.get("name", ""),
"role": user_data.get("role", ""),
"skills": user_data.get("skills", "").split(", ") if user_data.get("skills") else [],
"experience": user_data.get("experience", ""),
"location": user_data.get("location", ""),
"timestamp": time.time()
}
try:
with open(filename, "a", encoding="utf-8") as f:
f.write(json.dumps(profile_entry) + "\n")
return True
except Exception as e:
print(f"Error saving profile: {e}")
return False
# Global state for the chatbot
chatbot_state = ChatbotState()
model = None
def initialize_model(model_name="gemini-1.5-flash"):
"""Initialize the Gemini model."""
global model
model = genai.GenerativeModel(model_name)
return model
def process_message(message, history, model_name):
"""Process user message and return bot response."""
global chatbot_state, model
if model is None:
initialize_model(model_name)
try:
# Handle onboarding flow
if chatbot_state.is_onboarding():
# Handle onboarding responses
if chatbot_state.onboarding_step < 5: # Still collecting basic info
# Save the user's response
chatbot_state.save_onboarding_data(None, message)
chatbot_state.onboarding_step += 1
# Check if we need to ask another question
if chatbot_state.onboarding_step < 5:
next_question = chatbot_state.get_next_onboarding_question()
return f"Great! {next_question}"
else:
# All info collected, show summary
summary = chatbot_state.get_onboarding_summary()
return summary
elif chatbot_state.onboarding_step == 5: # Waiting for confirmation
if message.lower() in ["yes", "y", "correct", "looks good"]:
# Save profile
if save_user_profile(chatbot_state.user_data):
response = "Perfect! Your profile has been saved successfully. You're now onboarded and ready to search for jobs! 🎉"
else:
response = "Your profile information has been recorded. You're now onboarded! 🎉"
chatbot_state.onboarding_complete = True
chatbot_state.mode = None
return response
elif message.lower() in ["no", "n", "incorrect", "wrong"]:
chatbot_state.reset()
chatbot_state.mode = "onboarding"
chatbot_state.onboarding_step = 0
return "No problem! Let's start over. What's your full name?"
else:
return "Please answer 'yes' if the information is correct, or 'no' if you'd like to start over."
# Regular intent detection for non-onboarding messages
intent = detect_intent(message, model=model_name)
print(f"[Debug] Detected intent: {intent}")
# Handle different intents
if intent == "ONBOARD":
# Start onboarding flow
chatbot_state.reset()
chatbot_state.mode = "onboarding"
# Check if user already provided some info in their first message
first_question = chatbot_state.get_next_onboarding_question()
return f"I'd be happy to help you create your professional profile! Let's start with some basic information.\n\n{first_question}"
elif intent == "SEARCH":
# Handle job search
context_block = None
job_results = retrieve_jobs(message, top_k=3)
if job_results:
lines = []
for idx, job in enumerate(job_results, start=1):
lines.append(f"{idx}) {job['text']}")
block_text = "\n".join(lines)
context_block = f"Relevant job listings:\n{block_text}"
print(f"[Debug] Found {len(job_results)} relevant jobs")
else:
print("[Debug] No relevant jobs found")
# Prepare prompt for job search
search_prompt = f"""
{SYSTEM_PROMPT}
{"Context Information: " + context_block if context_block else "No relevant jobs found in the database."}
User is looking for jobs: {message}
Please provide a helpful response about job opportunities. If jobs were found, present them clearly. If no jobs were found, provide helpful guidance on how they might refine their search.
"""
response = model.generate_content(search_prompt)
return response.text
elif intent == "POST":
# Handle job posting creation
post_prompt = f"""
{SYSTEM_PROMPT}
User wants to create a job posting: {message}
Help them create a structured job posting. Ask for any missing information needed to create a complete job post (title, description, required skills, budget, timeline, etc.).
"""
response = model.generate_content(post_prompt)
return response.text
else:
# General conversation
general_prompt = f"""
{SYSTEM_PROMPT}
User message: {message}
Respond helpfully. If they seem to want to get started with onboarding, job searching, or job posting, guide them appropriately.
"""
response = model.generate_content(general_prompt)
return response.text
except Exception as e:
return f"Sorry, I encountered an error: {str(e)}. Please try again!"
def reset_conversation():
"""Reset the conversation state."""
global chatbot_state
chatbot_state.reset()
return [], ""
def get_welcome_message():
"""Get the initial welcome message."""
return """👋 **Welcome to AI Job Assistant!**
I can help you with:
• 🎯 **Creating your professional profile** - Let me guide you through a quick onboarding
• 🔍 **Finding job opportunities** - Search for jobs that match your skills
• 📝 **Creating job postings** - Help employers post structured job listings
What would you like to do today?"""
# Custom CSS for a modern look
custom_css = """
.gradio-container {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.chat-message {
padding: 1rem;
margin: 0.5rem 0;
border-radius: 1rem;
max-width: 80%;
}
.user-message {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
margin-left: auto;
}
.bot-message {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
color: white;
}
/* Dark mode support */
.dark .chat-message {
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
}
.gradio-chatbot {
height: 500px;
}
/* Custom button styles */
.primary-button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
color: white;
padding: 0.5rem 1rem;
border-radius: 0.5rem;
font-weight: 500;
transition: all 0.3s ease;
}
.primary-button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
"""
def create_interface():
"""Create the Gradio interface."""
with gr.Blocks(
css=custom_css,
theme=gr.themes.Soft(
primary_hue="blue",
secondary_hue="purple",
neutral_hue="slate",
),
title="AI Job Assistant"
) as interface:
gr.HTML("""
<div style="text-align: center; padding: 2rem; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 1rem; margin-bottom: 2rem;">
<h1 style="margin: 0; font-size: 2.5rem; font-weight: bold;">🤖 AI Job Assistant</h1>
<p style="margin: 0.5rem 0 0 0; font-size: 1.2rem; opacity: 0.9;">Your intelligent career companion</p>
</div>
""")
with gr.Row():
with gr.Column(scale=4):
chatbot = gr.Chatbot(
value=[{"role": "assistant", "content": get_welcome_message()}],
height=500,
show_label=False,
container=True,
avatar_images=("👤", "🤖"),
type="messages"
)
with gr.Row():
msg = gr.Textbox(
placeholder="Type your message here...",
show_label=False,
scale=4,
container=False
)
send_btn = gr.Button(
"Send",
variant="primary",
scale=1,
elem_classes=["primary-button"]
)
with gr.Column(scale=1, min_width=250):
gr.HTML("""
<div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; padding: 1.5rem; border-radius: 1rem; margin-bottom: 1rem;">
<h3 style="margin: 0 0 1rem 0;">🚀 Quick Actions</h3>
<div style="font-size: 0.9rem; line-height: 1.6;">
<div style="margin-bottom: 0.8rem;">
<strong>💼 Get Started:</strong><br>
"I want to create my profile"
</div>
<div style="margin-bottom: 0.8rem;">
<strong>🔍 Find Jobs:</strong><br>
"Show me Python developer jobs"
</div>
<div>
<strong>📝 Post Job:</strong><br>
"I want to post a job opening"
</div>
</div>
</div>
""")
model_selector = gr.Dropdown(
choices=["gemini-1.5-flash", "gemini-1.5-pro"],
value="gemini-1.5-flash",
label="🧠 AI Model",
info="Choose your preferred AI model"
)
clear_btn = gr.Button(
"🗑️ Clear Chat",
variant="secondary",
size="sm"
)
gr.HTML("""
<div style="background: rgba(102, 126, 234, 0.1); padding: 1rem; border-radius: 0.5rem; margin-top: 1rem;">
<h4 style="margin: 0 0 0.5rem 0; color: #667eea;">ℹ️ Tips</h4>
<ul style="margin: 0; padding-left: 1.2rem; font-size: 0.85rem; color: #666;">
<li>Be specific about your skills and preferences</li>
<li>Use natural language - I understand context!</li>
<li>Ask follow-up questions anytime</li>
</ul>
</div>
""")
# Event handlers
def respond(message, chat_history, model_name):
if not message.strip():
return chat_history, ""
bot_message = process_message(message, chat_history, model_name)
chat_history.append({"role": "user", "content": message})
chat_history.append({"role": "assistant", "content": bot_message})
return chat_history, ""
def clear_chat():
reset_conversation()
return [{"role": "assistant", "content": get_welcome_message()}], ""
# Wire up the events
msg.submit(respond, [msg, chatbot, model_selector], [chatbot, msg])
send_btn.click(respond, [msg, chatbot, model_selector], [chatbot, msg])
clear_btn.click(clear_chat, None, [chatbot, msg])
# Auto-focus on textbox
interface.load(lambda: gr.update(focus=True), None, msg)
return interface
def main():
"""Main function to launch the Gradio interface."""
# Initialize the model
chosen_model = sys.argv[1] if len(sys.argv) > 1 else "gemini-1.5-flash"
initialize_model(chosen_model)
# Create and launch the interface
interface = create_interface()
print("🚀 Launching AI Job Assistant...")
print("🌐 Opening in your default browser...")
interface.launch(
server_name="0.0.0.0", # Allow external access
server_port=7860, # Default Gradio port
share=False, # Set to True to create public link
show_error=True
)
if __name__ == "__main__":
main() |