diff --git "a/app.py" "b/app.py"
--- "a/app.py"
+++ "b/app.py"
@@ -1,4 +1,4 @@
-# filename: app_gemini_serper_v3.py
+# filename: app_openai_serper_v4.py
import gradio as gr
import pandas as pd
import numpy as np
@@ -16,9 +16,8 @@ from dotenv import load_dotenv
import uuid
import re
-# --- Google AI Integration ---
-import google.generativeai as genai
-from google.api_core import exceptions as google_exceptions
+# --- OpenAI Integration ---
+import openai
# --- Load environment variables ---
load_dotenv()
@@ -26,290 +25,272 @@ load_dotenv()
# --- Set up logging ---
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
-logger = logging.getLogger(__name__) # Use __name__ for logger
+logger = logging.getLogger(__name__)
# --- Configure API keys ---
-GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
+OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
SERPER_API_KEY = os.getenv("SERPER_API_KEY")
-if not GOOGLE_API_KEY:
- logger.warning("GOOGLE_API_KEY not found. AI features will not work.")
+if not OPENAI_API_KEY:
+ logger.warning("OPENAI_API_KEY not found. AI features will not work.")
+else:
+ logger.info("OpenAI API Key found.")
if not SERPER_API_KEY:
logger.warning("SERPER_API_KEY not found. Live web search features will not work.")
+else:
+ logger.info("Serper API Key found.")
-# --- Initialize the Google AI client ---
+
+# --- Initialize the OpenAI client ---
try:
- genai.configure(api_key=GOOGLE_API_KEY)
- logger.info("Google AI client configured successfully.")
+ # Ensure the API key is not None before initializing
+ if OPENAI_API_KEY:
+ client = openai.OpenAI(api_key=OPENAI_API_KEY)
+ logger.info("OpenAI client initialized successfully.")
+ else:
+ client = None
+ logger.error("Failed to initialize OpenAI client: API key is missing.")
except Exception as e:
- logger.error(f"Failed to configure Google AI client: {e}")
- genai = None # Prevent further calls if config fails
+ logger.error(f"Failed to initialize OpenAI client: {e}")
+ client = None
# --- Model configuration ---
-# Using gemini-1.5-flash-latest as the state-of-the-art, fast model
-MODEL_ID = "gemini-1.5-flash-latest"
-if genai:
- try:
- gemini_model = genai.GenerativeModel(
- MODEL_ID,
- # System instruction is now passed during generation, not model init
- # safety_settings adjusted for potentially sensitive career/emotion talk
- safety_settings=[
- {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
- {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
- {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_ONLY_HIGH"},
- {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
- ]
- )
- logger.info(f"Google AI Model '{MODEL_ID}' initialized.")
- except Exception as e:
- logger.error(f"Failed to initialize Google AI Model '{MODEL_ID}': {e}")
- gemini_model = None
-else:
- gemini_model = None
+MODEL_ID = "gpt-4o" # Using OpenAI's GPT-4o model
# --- Constants ---
-# Enhanced emotions and goals for richer profile
+# Using the same enhanced constants from v3
EMOTIONS = ["Unmotivated 😩", "Anxious 😥", "Confused 🤔", "Excited 🎉", "Overwhelmed 🤯", "Discouraged 😔", "Hopeful ✨", "Focused 😎", "Stuck 🧱"]
GOAL_TYPES = [
"Get a job (Big Company) 🏢", "Get a job (Startup) 🌱", "Find an Internship 🎓", "Freelance/Contract Work 💼",
"Change Careers 🚀", "Improve Specific Skills 💡", "Build Professional Network 🤝", "Leadership Development 📈", "Explore Options 🤔"
]
-USER_DB_PATH = "user_database_v3.json" # New DB file for new structure
-RESUME_FOLDER = "user_resumes_v3"
-PORTFOLIO_FOLDER = "user_portfolios_v3"
+USER_DB_PATH = "user_database_v4.json" # New DB file for this version
+RESUME_FOLDER = "user_resumes_v4"
+PORTFOLIO_FOLDER = "user_portfolios_v4"
os.makedirs(RESUME_FOLDER, exist_ok=True)
os.makedirs(PORTFOLIO_FOLDER, exist_ok=True)
-# --- Tool Definitions for Google AI (Gemini) ---
-# Note: Schema is slightly different from OpenAI's
-
-# 1. Document Template Generator
-generate_document_template_func = genai.protos.FunctionDeclaration(
- name="generate_document_template",
- description="Generate a document template (like a resume or cover letter) based on type, career field, and experience level.",
- parameters=genai.protos.Schema(
- type=genai.protos.Type.OBJECT,
- properties={
- "document_type": genai.protos.Schema(type=genai.protos.Type.STRING, description="e.g., Resume, Cover Letter, LinkedIn Summary"),
- "career_field": genai.protos.Schema(type=genai.protos.Type.STRING, description="Target industry or field"),
- "experience_level": genai.protos.Schema(type=genai.protos.Type.STRING, description="e.g., Entry, Mid, Senior, Student")
- },
- required=["document_type"]
- )
-)
-
-# 2. Personalized Routine Creator
-create_personalized_routine_func = genai.protos.FunctionDeclaration(
- name="create_personalized_routine",
- description="Create a personalized daily or weekly career development routine based on the user's current emotion, goals, and available time.",
- parameters=genai.protos.Schema(
- type=genai.protos.Type.OBJECT,
- properties={
- "emotion": genai.protos.Schema(type=genai.protos.Type.STRING, description="User's current primary emotion"),
- "goal": genai.protos.Schema(type=genai.protos.Type.STRING, description="User's primary career goal"),
- "available_time_minutes": genai.protos.Schema(type=genai.protos.Type.INTEGER, description="Average minutes per day user can dedicate"),
- "routine_length_days": genai.protos.Schema(type=genai.protos.Type.INTEGER, description="Desired length of the routine in days (e.g., 7 for weekly)")
- },
- required=["emotion", "goal"]
- )
-)
-
-# 3. Resume Analyzer
-analyze_resume_func = genai.protos.FunctionDeclaration(
- name="analyze_resume",
- description="Analyze the provided resume text and provide feedback, comparing it against the user's stated career goal. Provides strengths, weaknesses, and suggestions.",
- parameters=genai.protos.Schema(
- type=genai.protos.Type.OBJECT,
- properties={
- "resume_text": genai.protos.Schema(type=genai.protos.Type.STRING, description="The full text content of the user's resume"),
- "career_goal": genai.protos.Schema(type=genai.protos.Type.STRING, description="The specific career goal to analyze against")
- },
- required=["resume_text", "career_goal"]
- )
-)
-
-# 4. Portfolio Analyzer
-analyze_portfolio_func = genai.protos.FunctionDeclaration(
- name="analyze_portfolio",
- description="Analyze a user's portfolio based on a URL (if provided) and a description, offering feedback relative to their career goal.",
- parameters=genai.protos.Schema(
- type=genai.protos.Type.OBJECT,
- properties={
- "portfolio_url": genai.protos.Schema(type=genai.protos.Type.STRING, description="URL link to the online portfolio (optional)"),
- "portfolio_description": genai.protos.Schema(type=genai.protos.Type.STRING, description="User's description of the portfolio content and purpose"),
- "career_goal": genai.protos.Schema(type=genai.protos.Type.STRING, description="The specific career goal to analyze against")
- },
- required=["portfolio_description", "career_goal"]
- )
-)
-
-# 5. Skill Extractor & Rater (from Resume)
-extract_and_rate_skills_from_resume_func = genai.protos.FunctionDeclaration(
- name="extract_and_rate_skills_from_resume",
- description="Extracts key skills from resume text and rates them on a scale of 1-10 based on apparent proficiency shown in the resume. Useful for identifying strengths and gaps.",
- parameters=genai.protos.Schema(
- type=genai.protos.Type.OBJECT,
- properties={
- "resume_text": genai.protos.Schema(type=genai.protos.Type.STRING, description="The full text content of the user's resume"),
- "max_skills": genai.protos.Schema(type=genai.protos.Type.INTEGER, description="Maximum number of skills to extract (default 8)")
- },
- required=["resume_text"]
- )
-)
-
-# 6. NEW: Live Web Search for Opportunities (Serper API)
-search_web_serper_func = genai.protos.FunctionDeclaration(
- name="search_jobs_courses_skills",
- description="Search the web for relevant job openings, online courses, or skills development resources based on the user's goals, location, and potentially identified skill gaps.",
- parameters=genai.protos.Schema(
- type=genai.protos.Type.OBJECT,
- properties={
- "search_query": genai.protos.Schema(type=genai.protos.Type.STRING, description="The specific search query (e.g., 'remote data analyst jobs in California', 'online Python courses for beginners', 'project management certifications')"),
- "search_type": genai.protos.Schema(type=genai.protos.Type.STRING, description="Type of search: 'jobs', 'courses', 'skills', or 'general'"),
- "location": genai.protos.Schema(type=genai.protos.Type.STRING, description="Geographical location for the search (if applicable, e.g., 'London, UK')")
- },
- required=["search_query", "search_type"]
- )
-)
-
-
-# Combine all tool function declarations for the API call
-tools_list_gemini = [
- generate_document_template_func,
- create_personalized_routine_func,
- analyze_resume_func,
- analyze_portfolio_func,
- extract_and_rate_skills_from_resume_func,
- search_web_serper_func
+# --- Tool Definitions for OpenAI ---
+# Format matches the structure expected by the OpenAI API
+tools_list_openai = [
+ {
+ "type": "function",
+ "function": {
+ "name": "generate_document_template",
+ "description": "Generate a document template (like a resume or cover letter) based on type, career field, and experience level.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "document_type": {"type": "string", "description": "e.g., Resume, Cover Letter, LinkedIn Summary"},
+ "career_field": {"type": "string", "description": "Target industry or field"},
+ "experience_level": {"type": "string", "description": "e.g., Entry, Mid, Senior, Student"}
+ },
+ "required": ["document_type"]
+ },
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "create_personalized_routine",
+ "description": "Create a personalized daily or weekly career development routine based on the user's current emotion, goals, and available time.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "emotion": {"type": "string", "description": "User's current primary emotion"},
+ "goal": {"type": "string", "description": "User's primary career goal"},
+ "available_time_minutes": {"type": "integer", "description": "Average minutes per day user can dedicate"},
+ "routine_length_days": {"type": "integer", "description": "Desired length of the routine in days (e.g., 7 for weekly)"}
+ },
+ "required": ["emotion", "goal"]
+ },
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "analyze_resume",
+ "description": "Analyze the provided resume text and provide feedback, comparing it against the user's stated career goal. Provides strengths, weaknesses, and suggestions.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "resume_text": {"type": "string", "description": "The full text content of the user's resume"},
+ "career_goal": {"type": "string", "description": "The specific career goal to analyze against"}
+ },
+ "required": ["resume_text", "career_goal"]
+ },
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "analyze_portfolio",
+ "description": "Analyze a user's portfolio based on a URL (if provided) and a description, offering feedback relative to their career goal.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "portfolio_url": {"type": "string", "description": "URL link to the online portfolio (optional)"},
+ "portfolio_description": {"type": "string", "description": "User's description of the portfolio content and purpose"},
+ "career_goal": {"type": "string", "description": "The specific career goal to analyze against"}
+ },
+ "required": ["portfolio_description", "career_goal"]
+ },
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "extract_and_rate_skills_from_resume",
+ "description": "Extracts key skills from resume text and rates them on a scale of 1-10 based on apparent proficiency shown in the resume. Useful for identifying strengths and gaps.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "resume_text": {"type": "string", "description": "The full text content of the user's resume"},
+ "max_skills": {"type": "integer", "description": "Maximum number of skills to extract (default 8)"}
+ },
+ "required": ["resume_text"]
+ },
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "search_jobs_courses_skills",
+ "description": "Search the web using Serper API for relevant job openings, online courses, or skills development resources based on the user's goals, location, and potentially identified skill gaps.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "search_query": {"type": "string", "description": "The specific search query (e.g., 'remote data analyst jobs in California', 'online Python courses for beginners', 'project management certifications')"},
+ "search_type": {"type": "string", "description": "Type of search: 'jobs', 'courses', 'skills', or 'general'"},
+ "location": {"type": "string", "description": "Geographical location for the search (if applicable, e.g., 'London, UK')"}
+ },
+ "required": ["search_query", "search_type"]
+ },
+ }
+ }
]
-# --- User Database Functions (Enhanced Profile) ---
+# --- User Database Functions (Enhanced Profile - Adapted for OpenAI History) ---
def load_user_database():
try:
with open(USER_DB_PATH, 'r', encoding='utf-8') as file: db = json.load(file)
- # Basic validation and migration for chat history (similar to previous)
+ # Validation for chat history (OpenAI format: role='user'/'assistant'/'system'/'tool', content=str, tool_calls=list[dict])
for user_id in db.get('users', {}):
profile = db['users'][user_id]
- if 'chat_history' not in profile or not isinstance(profile['chat_history'], list): profile['chat_history'] = []
+ if 'chat_history' not in profile or not isinstance(profile['chat_history'], list):
+ profile['chat_history'] = []
else:
- # Gemini uses 'parts' not 'content', and roles 'user'/'model'
- fixed_history = []
- for msg in profile['chat_history']:
- if isinstance(msg, dict) and 'role' in msg and 'parts' in msg:
- # Basic check, can be more robust
- if msg['role'] in ['user', 'model'] and isinstance(msg['parts'], list):
- fixed_history.append(msg)
- elif isinstance(msg, dict) and 'role' == 'function': # Gemini uses role 'function' for tool responses
- # Ensure it has necessary fields (name, response)
- if 'name' in msg and 'response' in msg:
- fixed_history.append(msg)
- profile['chat_history'] = fixed_history
-
- # Ensure other lists exist
+ fixed_history = []
+ for msg in profile['chat_history']:
+ if isinstance(msg, dict) and 'role' in msg and 'content' in msg:
+ # Basic check for standard messages
+ if msg['role'] in ['user', 'assistant', 'system'] and isinstance(msg.get('content'), (str, type(None))):
+ # Allow None content for assistant messages that only have tool calls
+ if msg['role'] == 'assistant' or msg.get('content') is not None:
+ # Check for tool_calls structure if present
+ if 'tool_calls' in msg:
+ if isinstance(msg['tool_calls'], list) and all(isinstance(tc, dict) and 'id' in tc and 'type' in tc and 'function' in tc for tc in msg['tool_calls']):
+ fixed_history.append(msg)
+ else:
+ logger.warning(f"Skipping message with invalid tool_calls for user {user_id}: {msg}")
+ else:
+ fixed_history.append(msg) # Valid user/system/assistant message without tool calls
+ else:
+ logger.warning(f"Skipping message with invalid role/content type for user {user_id}: {msg}")
+ elif isinstance(msg, dict) and msg.get('role') == 'tool':
+ # Check for tool response structure
+ if 'tool_call_id' in msg and 'content' in msg and isinstance(msg.get('content'), str):
+ # Note: OpenAI API expects 'name' in the tool call, but the response message uses 'tool_call_id'. Content should be stringified JSON result.
+ fixed_history.append(msg)
+ else:
+ logger.warning(f"Skipping invalid tool message structure for user {user_id}: {msg}")
+ else:
+ logger.warning(f"Skipping unrecognized message structure for user {user_id}: {msg}")
+ profile['chat_history'] = fixed_history
+
+ # Ensure other lists/fields exist (same as v3)
for key in ['recommendations', 'daily_emotions', 'completed_tasks', 'routine_history', 'strengths', 'areas_for_development', 'values']:
if key not in profile or not isinstance(profile.get(key), list):
profile[key] = []
- # Ensure basic string fields exist
for key in ['name', 'location', 'current_emotion', 'career_goal', 'industry', 'preferred_work_style', 'long_term_aspirations', 'resume_path', 'portfolio_path']:
if key not in profile:
profile[key] = ""
if 'progress_points' not in profile: profile['progress_points'] = 0
- if 'experience_level' not in profile: profile['experience_level'] = "Not specified" # Add experience level
+ if 'experience_level' not in profile: profile['experience_level'] = "Not specified"
return db
except (FileNotFoundError, json.JSONDecodeError): logger.info(f"DB file '{USER_DB_PATH}' not found/invalid. Creating new."); db = {'users': {}}; save_user_database(db); return db
except Exception as e: logger.error(f"Error loading DB from {USER_DB_PATH}: {e}"); return {'users': {}}
def save_user_database(db):
+ # (Identical to v3)
try:
with open(USER_DB_PATH, 'w', encoding='utf-8') as file: json.dump(db, file, indent=4, ensure_ascii=False)
except Exception as e: logger.error(f"Error saving DB to {USER_DB_PATH}: {e}")
def get_user_profile(user_id):
+ # (Mostly identical to v3, ensures profile exists)
db = load_user_database()
if user_id not in db.get('users', {}):
db['users'] = db.get('users', {})
# Initialize enhanced profile structure
db['users'][user_id] = {
- "user_id": user_id,
- "name": "",
- "location": "",
- "industry": "", # NEW: Target industry
- "experience_level": "Not specified", # NEW: e.g., Entry, Mid, Senior
- "preferred_work_style": "Any", # NEW: Remote, Hybrid, On-site, Any
- "values": [], # NEW: List of values (e.g., "work-life balance", "impact", "learning")
- "strengths": [], # NEW: User-identified or AI-suggested strengths
- "areas_for_development": [], # NEW: User-identified or AI-suggested areas
- "long_term_aspirations": "", # NEW: Goals beyond the immediate one
-
- "current_emotion": "",
- "career_goal": "",
- "progress_points": 0,
- "completed_tasks": [],
- "upcoming_events": [], # Consider adding events scheduling later
- "routine_history": [],
- "daily_emotions": [],
- "resume_path": "",
- "portfolio_path": "",
- "recommendations": [],
- "chat_history": [], # Stores history in Gemini format {role: 'user'/'model', parts: [{'text': '...'}]} or {role: 'function', name:'...', response:{...}}
+ "user_id": user_id, "name": "", "location": "", "industry": "",
+ "experience_level": "Not specified", "preferred_work_style": "Any",
+ "values": [], "strengths": [], "areas_for_development": [],
+ "long_term_aspirations": "", "current_emotion": "", "career_goal": "",
+ "progress_points": 0, "completed_tasks": [], "upcoming_events": [],
+ "routine_history": [], "daily_emotions": [], "resume_path": "",
+ "portfolio_path": "", "recommendations": [],
+ "chat_history": [], # Stores history in OpenAI format {role: 'user'/'assistant'/'system'/'tool', content: str, tool_calls?: list, tool_call_id?: str}
"joined_date": datetime.now().isoformat()
}
save_user_database(db)
- # Ensure lists and basic fields exist on subsequent loads (handled mostly in load_user_database)
profile = db.get('users', {}).get(user_id, {})
- # Add simple check for chat history format upon retrieval
+ # Ensure critical lists exist after loading (handled mostly in load_user_database)
if 'chat_history' not in profile or not isinstance(profile.get('chat_history'), list):
profile['chat_history'] = []
- # Ensure other critical lists exist
for key in ['recommendations', 'daily_emotions', 'completed_tasks', 'routine_history', 'strengths', 'areas_for_development', 'values']:
if key not in profile: profile[key] = []
-
return profile
-# --- Database Update Functions (largely similar, adjust chat message structure) ---
+# --- Database Update Functions (Adjust chat message structure for OpenAI) ---
def update_user_profile(user_id, updates):
- # (Keep existing logic, ensure keys match new profile)
+ # (Identical to v3)
db = load_user_database()
if user_id in db.get('users', {}):
profile = db['users'][user_id]
- for key, value in updates.items():
- # Maybe add some validation here later if needed
- profile[key] = value
- save_user_database(db)
- return profile
- else:
- logger.warning(f"Attempted update non-existent profile: {user_id}")
- return None
+ for key, value in updates.items(): profile[key] = value
+ save_user_database(db); return profile
+ else: logger.warning(f"Attempted update non-existent profile: {user_id}"); return None
def add_task_to_user(user_id, task):
- # (Keep existing logic)
+ # (Identical to v3)
db = load_user_database(); profile = db.get('users', {}).get(user_id)
if profile:
if 'completed_tasks' not in profile or not isinstance(profile['completed_tasks'], list): profile['completed_tasks'] = []
- task_with_date = { "task": task, "date": datetime.now().isoformat() }
+ task_with_date = { "task": task, "date": datetime.now().isoformat(), "points": random.randint(10, 25) } # Add points here
profile['completed_tasks'].append(task_with_date)
- profile['progress_points'] = profile.get('progress_points', 0) + random.randint(10, 25) # Gamification element
+ profile['progress_points'] = profile.get('progress_points', 0) + task_with_date["points"] # Update total points
save_user_database(db); return profile
return None
def add_emotion_record(user_id, emotion):
- # (Keep existing logic)
+ # (Identical to v3)
cleaned_emotion = emotion.split(" ")[0] if " " in emotion else emotion
db = load_user_database(); profile = db.get('users', {}).get(user_id)
if profile:
if 'daily_emotions' not in profile or not isinstance(profile['daily_emotions'], list): profile['daily_emotions'] = []
emotion_record = { "emotion": cleaned_emotion, "date": datetime.now().isoformat() }
profile['daily_emotions'].append(emotion_record)
- profile['current_emotion'] = cleaned_emotion # Update current emotion too
+ profile['current_emotion'] = cleaned_emotion
save_user_database(db); return profile
return None
def add_routine_to_user(user_id, routine):
- # (Keep existing logic)
+ # (Identical to v3)
db = load_user_database(); profile = db.get('users', {}).get(user_id)
if profile:
if 'routine_history' not in profile or not isinstance(profile['routine_history'], list): profile['routine_history'] = []
@@ -317,13 +298,12 @@ def add_routine_to_user(user_id, routine):
except: days_delta = 7
end_date = (datetime.now() + timedelta(days=days_delta)).isoformat()
routine_with_date = { "routine": routine, "start_date": datetime.now().isoformat(), "end_date": end_date, "completion": 0 }
- profile['routine_history'].insert(0, routine_with_date) # Add to beginning
- profile['routine_history'] = profile['routine_history'][:10] # Keep last 10 routines
+ profile['routine_history'].insert(0, routine_with_date); profile['routine_history'] = profile['routine_history'][:10]
save_user_database(db); return profile
return None
def save_user_resume(user_id, resume_text):
- # (Keep existing logic)
+ # (Identical to v3)
if not resume_text: return None
filename, filepath = f"{user_id}_resume.txt", os.path.join(RESUME_FOLDER, f"{user_id}_resume.txt")
try:
@@ -333,7 +313,7 @@ def save_user_resume(user_id, resume_text):
except Exception as e: logger.error(f"Error saving resume {filepath}: {e}"); return None
def save_user_portfolio(user_id, portfolio_url, portfolio_description):
- # (Keep existing logic)
+ # (Identical to v3)
if not portfolio_description: return None
filename, filepath = f"{user_id}_portfolio.json", os.path.join(PORTFOLIO_FOLDER, f"{user_id}_portfolio.json")
portfolio_content = {"url": portfolio_url, "description": portfolio_description, "saved_date": datetime.now().isoformat()}
@@ -344,19 +324,17 @@ def save_user_portfolio(user_id, portfolio_url, portfolio_description):
except Exception as e: logger.error(f"Error saving portfolio {filepath}: {e}"); return None
def add_recommendation_to_user(user_id, recommendation):
- # (Keep existing logic - potentially refine recommendation structure later)
+ # (Identical to v3)
db = load_user_database(); profile = db.get('users', {}).get(user_id)
if profile:
if 'recommendations' not in profile or not isinstance(profile['recommendations'], list): profile['recommendations'] = []
- # Example structure: { 'title': 'Update LinkedIn', 'description': 'Focus on...', 'priority': 'High', 'action_type': 'Skill Building' }
recommendation_with_date = {"recommendation": recommendation, "date": datetime.now().isoformat(), "status": "pending"}
- profile['recommendations'].insert(0, recommendation_with_date) # Add to beginning
- profile['recommendations'] = profile['recommendations'][:20] # Limit size
+ profile['recommendations'].insert(0, recommendation_with_date); profile['recommendations'] = profile['recommendations'][:20]
save_user_database(db); return profile
return None
-def add_chat_message(user_id, role, parts_or_func_response):
- """Adds a message to the user's chat history using Gemini format."""
+def add_chat_message(user_id, role, message_content):
+ """Adds a message to the user's chat history using OpenAI format."""
db = load_user_database()
profile = db.get('users', {}).get(user_id)
if not profile:
@@ -366,61 +344,88 @@ def add_chat_message(user_id, role, parts_or_func_response):
if 'chat_history' not in profile or not isinstance(profile['chat_history'], list):
profile['chat_history'] = []
- if role not in ['user', 'model', 'function']: # Gemini roles: 'user', 'model' (for assistant), 'function' (for tool results)
- logger.warning(f"Invalid role '{role}' for Gemini chat history.")
+ if role not in ['user', 'assistant', 'system', 'tool']:
+ logger.warning(f"Invalid role '{role}' for OpenAI chat history.")
return profile
message = {"role": role}
- if role == 'user' or role == 'model':
- # Expecting parts_or_func_response to be a list of parts, e.g., [{'text': '...'}],
- # but handle simple string input for convenience
- if isinstance(parts_or_func_response, str):
- message['parts'] = [{'text': parts_or_func_response}]
- elif isinstance(parts_or_func_response, list):
- # Basic validation: Ensure it's a list of dicts with 'text'
- if all(isinstance(p, dict) and 'text' in p for p in parts_or_func_response):
- message['parts'] = parts_or_func_response
+
+ if role == 'user' or role == 'system':
+ if isinstance(message_content, str):
+ message['content'] = message_content
+ else:
+ logger.warning(f"Invalid content type for role {role}: {type(message_content)}. Expected string.")
+ return profile
+ elif role == 'assistant':
+ # Assistant message can have content (string/None) and/or tool_calls (list)
+ if isinstance(message_content, dict):
+ message['content'] = message_content.get('content') # Can be None if only tool calls
+ if 'tool_calls' in message_content:
+ # Basic validation of tool_calls structure
+ if isinstance(message_content['tool_calls'], list) and all(isinstance(tc, dict) and 'id' in tc and 'type' in tc and 'function' in tc for tc in message_content['tool_calls']):
+ message['tool_calls'] = message_content['tool_calls']
+ else:
+ logger.warning(f"Invalid tool_calls structure in assistant message: {message_content.get('tool_calls')}")
+ # Decide whether to store without tool_calls or skip
+ if message['content'] is None: return profile # Skip if no content and invalid tool_calls
+ # else store with content only
+ # Ensure content is string or None
+ if not isinstance(message['content'], (str, type(None))):
+ logger.warning(f"Invalid content type in assistant message dict: {type(message['content'])}")
+ message['content'] = str(message['content']) # Attempt conversion or handle error
+ elif isinstance(message_content, str):
+ message['content'] = message_content # Simple text response
+ else:
+ logger.warning(f"Invalid content type for role {role}: {type(message_content)}. Expected dict or string.")
+ return profile
+ elif role == 'tool':
+ # Tool message needs tool_call_id and content (stringified result)
+ if isinstance(message_content, dict) and 'tool_call_id' in message_content and 'content' in message_content:
+ message['tool_call_id'] = message_content['tool_call_id']
+ # Ensure content is stringified JSON or simple string
+ if isinstance(message_content['content'], str):
+ message['content'] = message_content['content']
else:
- logger.warning(f"Invalid parts format for role {role}: {parts_or_func_response}")
- return profile # Don't save invalid structure
+ try:
+ message['content'] = json.dumps(message_content['content'])
+ except Exception as e:
+ logger.error(f"Could not stringify tool content: {e}")
+ message['content'] = json.dumps({"error": "Failed to serialize tool result."})
else:
- logger.warning(f"Invalid content type for role {role}: {type(parts_or_func_response)}")
- return profile # Don't save invalid structure
+ logger.warning(f"Invalid content format for role {role}: {message_content}. Expected dict with 'tool_call_id' and 'content'.")
+ return profile
- elif role == 'function':
- # Expecting parts_or_func_response to be a dict like {'name': 'func_name', 'response': {'content': ...}}
- if isinstance(parts_or_func_response, dict) and 'name' in parts_or_func_response and 'response' in parts_or_func_response:
- message.update(parts_or_func_response) # Merge the dict
- else:
- logger.warning(f"Invalid function response format: {parts_or_func_response}")
- return profile # Don't save invalid structure
+ # Add timestamp for potential future use (optional)
+ # message['timestamp'] = datetime.now().isoformat()
profile['chat_history'].append(message)
- # Limit history size (keep system prompt implicit for now, or add explicitly if needed)
- max_history_turns = 25 # Keep last 25 pairs (user + model/function)
+ # Limit history size (keep system prompt implicit for now)
+ max_history_turns = 25 # Keep last 25 pairs (user + assistant/tool)
if len(profile['chat_history']) > max_history_turns * 2:
- profile['chat_history'] = profile['chat_history'][-(max_history_turns * 2):]
+ # Find first non-system message index if system message exists
+ first_non_system = 0
+ if profile['chat_history'] and profile['chat_history'][0]['role'] == 'system':
+ first_non_system = 1
+ # Keep system message + last N turns
+ profile['chat_history'] = profile['chat_history'][:first_non_system] + profile['chat_history'][-(max_history_turns * 2):]
+
save_user_database(db)
return profile
-# --- Basic Routine Fallback Function (keep as is, provides robustness) ---
+# --- Basic Routine Fallback Function (keep as is) ---
def generate_basic_routine(emotion, goal, available_time=60, days=7):
- # (Code identical to the provided version - a good fallback)
+ # (Code identical to the provided v3 version - a good fallback)
logger.info(f"Generating basic fallback routine for emotion={emotion}, goal={goal}")
- # ... (rest of the function code remains the same) ...
- routine_types = {
- "job_search": [ {"name": "Research Target Companies", "points": 15, "duration": 20, "description": "Identify 3 potential employers aligned with your goal."}, {"name": "Update LinkedIn Section", "points": 15, "duration": 25, "description": "Refine one section of your LinkedIn profile (e.g., summary, experience)."}, {"name": "Practice STAR Method", "points": 20, "duration": 15, "description": "Outline one experience using the STAR method for interviews."}, {"name": "Find Networking Event", "points": 10, "duration": 10, "description": "Look for one relevant online or local networking event."} ],
- "skill_building": [ {"name": "Online Tutorial (1 Module)", "points": 25, "duration": 45, "description": "Complete one module of a relevant online course/tutorial."}, {"name": "Read Industry Blog/Article", "points": 10, "duration": 15, "description": "Read and summarize one article about trends in your field."}, {"name": "Small Project Task", "points": 30, "duration": 60, "description": "Dedicate time to a specific task within a personal project."}, {"name": "Review Skill Documentation", "points": 15, "duration": 30, "description": "Read documentation or examples for a skill you're learning."} ],
- "motivation_wellbeing": [ {"name": "Mindful Reflection", "points": 10, "duration": 10, "description": "Spend 10 minutes reflecting on progress and challenges without judgment."}, {"name": "Set 1-3 Daily Intentions", "points": 10, "duration": 5, "description": "Define small, achievable goals for the day."}, {"name": "Short Break/Walk", "points": 15, "duration": 15, "description": "Take a brief break away from screens, preferably with light movement."}, {"name": "Connect with Support", "points": 20, "duration": 20, "description": "Briefly chat with a friend, mentor, or peer about your journey."} ] }
+ routine_types = { "job_search": [ {"name": "Research Target Companies", "points": 15, "duration": 20, "description": "Identify 3 potential employers aligned with your goal."}, {"name": "Update LinkedIn Section", "points": 15, "duration": 25, "description": "Refine one section of your LinkedIn profile (e.g., summary, experience)."}, {"name": "Practice STAR Method", "points": 20, "duration": 15, "description": "Outline one experience using the STAR method for interviews."}, {"name": "Find Networking Event", "points": 10, "duration": 10, "description": "Look for one relevant online or local networking event."} ], "skill_building": [ {"name": "Online Tutorial (1 Module)", "points": 25, "duration": 45, "description": "Complete one module of a relevant online course/tutorial."}, {"name": "Read Industry Blog/Article", "points": 10, "duration": 15, "description": "Read and summarize one article about trends in your field."}, {"name": "Small Project Task", "points": 30, "duration": 60, "description": "Dedicate time to a specific task within a personal project."}, {"name": "Review Skill Documentation", "points": 15, "duration": 30, "description": "Read documentation or examples for a skill you're learning."} ], "motivation_wellbeing": [ {"name": "Mindful Reflection", "points": 10, "duration": 10, "description": "Spend 10 minutes reflecting on progress and challenges without judgment."}, {"name": "Set 1-3 Daily Intentions", "points": 10, "duration": 5, "description": "Define small, achievable goals for the day."}, {"name": "Short Break/Walk", "points": 15, "duration": 15, "description": "Take a brief break away from screens, preferably with light movement."}, {"name": "Connect with Support", "points": 20, "duration": 20, "description": "Briefly chat with a friend, mentor, or peer about your journey."} ] }
cleaned_emotion = emotion.split(" ")[0].lower() if " " in emotion else emotion.lower()
- negative_emotions = ["unmotivated", "anxious", "confused", "overwhelmed", "discouraged", "stuck"] # Added 'stuck'
+ negative_emotions = ["unmotivated", "anxious", "confused", "overwhelmed", "discouraged", "stuck"]
if any(term in goal.lower() for term in ["job", "internship", "company", "freelance", "contract"]): base_type = "job_search"
elif any(term in goal.lower() for term in ["skill", "learn", "development"]): base_type = "skill_building"
- elif "network" in goal.lower(): base_type = "job_search" # Networking often related to job search
- else: base_type = "skill_building" # Default
+ elif "network" in goal.lower(): base_type = "job_search"
+ else: base_type = "skill_building"
include_wellbeing = cleaned_emotion in negative_emotions or "overwhelmed" in cleaned_emotion
daily_tasks_list = []
for day in range(1, days + 1):
@@ -429,296 +434,124 @@ def generate_basic_routine(emotion, goal, available_time=60, days=7):
if include_wellbeing: possible_tasks.extend(routine_types["motivation_wellbeing"])
random.shuffle(possible_tasks)
for task in possible_tasks:
- # Ensure task has duration and check remaining time
- if task.get("duration", 0) > 0 and task["duration"] <= remaining_time and tasks_added_count < 3: # Max 3 tasks/day
+ if task.get("duration", 0) > 0 and task["duration"] <= remaining_time and tasks_added_count < 3:
day_tasks.append(task); remaining_time -= task["duration"]; tasks_added_count += 1
- if remaining_time < 10 or tasks_added_count >= 3: break # Stop if little time left or max tasks reached
+ if remaining_time < 10 or tasks_added_count >= 3: break
daily_tasks_list.append({"day": day, "tasks": day_tasks})
- routine = {"name": f"{days}-Day Focus Plan", "description": f"A focused {days}-day plan to help you with '{goal}', especially while feeling {cleaned_emotion}. We'll do this step-by-step!", "days": days, "daily_tasks": daily_tasks_list}
+ routine = {"name": f"{days}-Day Focus Plan", "description": f"A focused {days}-day plan to help you with '{goal}', especially while feeling {cleaned_emotion}. We'll do this step-by-step!", "days": days, "daily_tasks": daily_tasks_list, "support_message": f"Hey, I know feeling {cleaned_emotion} while aiming for '{goal}' can be tough. We've got this routine to help break it down. One step at a time, okay? You're doing great just by planning!"}
return routine # Return dict directly
-# --- Tool Implementation Functions ---
-# Note: These functions now return Python dicts/strings directly.
-# The main AI interaction logic will handle packaging them for Gemini API.
+# --- Tool Implementation Functions (Return JSON strings or dicts for OpenAI) ---
+# These functions remain largely the same internally but ensure output is serializable.
-def generate_document_template(document_type: str, career_field: str = "", experience_level: str = "") -> Dict[str, str]:
- """Generates a basic markdown template for the specified document type."""
+def generate_document_template(document_type: str, career_field: str = "", experience_level: str = "") -> str:
+ """Generates a basic markdown template. Returns JSON string."""
logger.info(f"Executing tool: generate_document_template(type='{document_type}', field='{career_field}', exp='{experience_level}')")
template = f"## Basic Template: {document_type}\n\n"
template += f"**Target Field:** {career_field or 'Not specified'}\n"
template += f"**Experience Level:** {experience_level or 'Not specified'}\n\n---\n\n"
-
- # Using triple quotes correctly
- if "resume" in document_type.lower():
- template += """
-### Contact Information
-* Name:
-* Phone:
-* Email:
-* LinkedIn URL:
-* Portfolio URL (Optional):
-
-### Summary/Objective
-* _[ 2-3 sentences summarizing your key skills, experience, and career goals, tailored to the job/field. Make it impactful! ]_
-
-### Experience
-**Company Name | Location | Job Title | Start Date – End Date**
-* Accomplishment 1 (Use action verbs: Led, Managed, Developed, Increased X by Y%. Quantify results!)
-* Accomplishment 2
-* _[ Repeat for other relevant positions ]_
-
-### Education
-**University/Institution Name | Degree | Graduation Date (or Expected)**
-* Relevant coursework, honors, activities (Optional)
-
-### Skills
-* **Technical Skills:** [ e.g., Python, Java, SQL, MS Excel, Google Analytics, Figma, AWS ]
-* **Languages:** [ e.g., English (Native), Spanish (Fluent) ]
-* **Other:** [ Certifications, relevant tools, methodologies like Agile/Scrum ]
-"""
- elif "cover letter" in document_type.lower():
- template += """
-[Your Name]
-[Your Address]
-[Your Phone]
-[Your Email]
-
-[Date]
-
-[Hiring Manager Name (if known), or 'Hiring Team']
-[Hiring Manager Title (if known)]
-[Company Name]
-[Company Address]
-
-**Subject: Application for [Job Title] Position - [Your Name]**
-
-Dear [Mr./Ms./Mx. Last Name or Hiring Team],
-
-**Introduction:** State the position you're applying for and where you saw it. Express genuine enthusiasm for the role *and* the company. Briefly highlight 1-2 key qualifications that make you a perfect fit right from the start.
-* _[ Example: I am writing to express my strong interest in the [Job Title] position advertised on [Platform]. With my background in [Relevant Field] and proven ability to [Key Skill Relevant to Job], I am confident I can bring significant value to [Company Name]'s mission in [Specific Area Company Works In]. ]_
-
-**Body Paragraph(s):** This is where you connect your experience to the job description. Don't just list duties; show *impact*. Use examples (think STAR method: Situation, Task, Action, Result). Explain *why* you're drawn to *this specific company* – mention their values, projects, or recent news. Show you've done your homework!
-* _[ Example: In my previous role at [Previous Company], I spearheaded a project that [Quantifiable achievement relevant to new job], demonstrating my expertise in [Skill required by new job]. I admire [Company Name]'s innovative approach to [Specific Company Initiative], and I believe my skills in [Another Relevant Skill] align perfectly with the requirements of this role and your company culture. ]_
-
-**Conclusion:** Reiterate your strong interest and suitability. Briefly summarize your key selling points. State your call to action confidently (e.g., "I am eager to discuss how my skills can benefit [Company Name]..."). Thank the reader for their time and consideration.
-* _[ Example: Thank you for considering my application. My attached resume provides further detail on my qualifications. I am excited about the potential to contribute to your team and look forward to hearing from you soon regarding an interview. ]_
-
-Sincerely,
-
-[Your Typed Name]
-"""
- elif "linkedin summary" in document_type.lower():
- template += """
-### LinkedIn Summary / About Section Template
-
-**Headline:** [ Make this keyword-rich and concise! Who are you professionally? What's your focus? e.g., 'Software Engineer specializing in AI & Cloud | Python | Ex-Google | Building Innovative Solutions' OR 'Marketing Manager | Driving Growth for SaaS Startups | Content Strategy & Demand Generation' ]
-
-**About Section:**
-
-* **[ Paragraph 1: Hook & Overview ]** Start with a compelling statement about your passion, mission, or core expertise. Who are you, what do you do, and what drives you? Use keywords relevant to your target roles/industry. Think of this as your elevator pitch.
-* **[ Paragraph 2: Key Skills & Experience Highlights ]** Detail your core competencies, both technical and soft skills. Mention significant experiences, types of projects, or industries you've worked in. Quantify achievements whenever possible (e.g., 'Managed budgets up to $X', 'Increased user engagement by Y%'). Tailor this to attract your desired audience (recruiters, clients, collaborators).
-* **[ Paragraph 3: Career Goals & What You're Seeking (Optional but Recommended) ]** Briefly state your current career aspirations. What kind of opportunities, connections, or challenges are you looking for? Be specific if possible (e.g., 'Seeking opportunities in AI ethics', 'Open to collaborating on open-source projects').
-* **[ Paragraph 4: Call to Action / Personality (Optional) ]** You might invite relevant connections, mention personal interests related to your field, or add a touch of personality to make you more memorable. What makes you, you?
-* **[ Specialties/Keywords: ]** _[ List 5-15 key terms separated by commas or bullet points that recruiters might search for. e.g., Project Management, Data Analysis, Agile Methodologies, Content Strategy, Python, Java, Cloud Security, UX/UI Design, B2B Marketing ]_
-"""
- else:
- template += "[ Template structure for this document type will be provided here. Let me know what you need! ]"
-
- # Return as a dictionary for Gemini function response
- return {"template_markdown": template}
-
-def create_personalized_routine(emotion: str, goal: str, available_time_minutes: int = 60, routine_length_days: int = 7) -> Dict[str, Any]:
- """Creates a personalized routine, trying AI first, then falling back to basic."""
+ # (Keep the template content from v3/previous version)
+ if "resume" in document_type.lower(): template += """### Contact Information\n* Name:\n* Phone:\n* Email:\n* LinkedIn URL:\n* Portfolio URL (Optional):\n\n### Summary/Objective\n* _[ 2-3 sentences summarizing your key skills, experience, and career goals, tailored to the job/field. Make it impactful! ]_\n\n### Experience\n**Company Name | Location | Job Title | Start Date – End Date**\n* Accomplishment 1 (Use action verbs: Led, Managed, Developed, Increased X by Y%. Quantify results!)\n* Accomplishment 2\n* _[ Repeat for other relevant positions ]_\n\n### Education\n**University/Institution Name | Degree | Graduation Date (or Expected)**\n* Relevant coursework, honors, activities (Optional)\n\n### Skills\n* **Technical Skills:** [ e.g., Python, Java, SQL, MS Excel, Google Analytics, Figma, AWS ]\n* **Languages:** [ e.g., English (Native), Spanish (Fluent) ]\n* **Other:** [ Certifications, relevant tools, methodologies like Agile/Scrum ]\n"""
+ elif "cover letter" in document_type.lower(): template += """[Your Name]\n[Your Address]\n[Your Phone]\n[Your Email]\n\n[Date]\n\n[Hiring Manager Name (if known), or 'Hiring Team']\n[Hiring Manager Title (if known)]\n[Company Name]\n[Company Address]\n\n**Subject: Application for [Job Title] Position - [Your Name]**\n\nDear [Mr./Ms./Mx. Last Name or Hiring Team],\n\n**Introduction:** State the position you're applying for and where you saw it. Express genuine enthusiasm for the role *and* the company. Briefly highlight 1-2 key qualifications that make you a perfect fit right from the start.\n* _[ Example: I am writing to express my strong interest in the [Job Title] position advertised on [Platform]. With my background in [Relevant Field] and proven ability to [Key Skill Relevant to Job], I am confident I can bring significant value to [Company Name]'s mission in [Specific Area Company Works In]. ]_\n\n**Body Paragraph(s):** This is where you connect your experience to the job description. Don't just list duties; show *impact*. Use examples (think STAR method: Situation, Task, Action, Result). Explain *why* you're drawn to *this specific company* – mention their values, projects, or recent news. Show you've done your homework!\n* _[ Example: In my previous role at [Previous Company], I spearheaded a project that [Quantifiable achievement relevant to new job], demonstrating my expertise in [Skill required by new job]. I admire [Company Name]'s innovative approach to [Specific Company Initiative], and I believe my skills in [Another Relevant Skill] align perfectly with the requirements of this role and your company culture. ]_\n\n**Conclusion:** Reiterate your strong interest and suitability. Briefly summarize your key selling points. State your call to action confidently (e.g., "I am eager to discuss how my skills can benefit [Company Name]..."). Thank the reader for their time and consideration.\n* _[ Example: Thank you for considering my application. My attached resume provides further detail on my qualifications. I am excited about the potential to contribute to your team and look forward to hearing from you soon regarding an interview. ]_\n\nSincerely,\n\n[Your Typed Name]\n"""
+ elif "linkedin summary" in document_type.lower(): template += """### LinkedIn Summary / About Section Template\n\n**Headline:** [ Make this keyword-rich and concise! Who are you professionally? What's your focus? e.g., 'Software Engineer specializing in AI & Cloud | Python | Ex-Google | Building Innovative Solutions' OR 'Marketing Manager | Driving Growth for SaaS Startups | Content Strategy & Demand Generation' ]\n\n**About Section:**\n\n* **[ Paragraph 1: Hook & Overview ]** Start with a compelling statement about your passion, mission, or core expertise. Who are you, what do you do, and what drives you? Use keywords relevant to your target roles/industry. Think of this as your elevator pitch.\n* **[ Paragraph 2: Key Skills & Experience Highlights ]** Detail your core competencies, both technical and soft skills. Mention significant experiences, types of projects, or industries you've worked in. Quantify achievements whenever possible (e.g., 'Managed budgets up to $X', 'Increased user engagement by Y%'). Tailor this to attract your desired audience (recruiters, clients, collaborators).\n* **[ Paragraph 3: Career Goals & What You're Seeking (Optional but Recommended) ]** Briefly state your current career aspirations. What kind of opportunities, connections, or challenges are you looking for? Be specific if possible (e.g., 'Seeking opportunities in AI ethics', 'Open to collaborating on open-source projects').\n* **[ Paragraph 4: Call to Action / Personality (Optional) ]** You might invite relevant connections, mention personal interests related to your field, or add a touch of personality to make you more memorable. What makes you, you?\n* **[ Specialties/Keywords: ]** _[ List 5-15 key terms separated by commas or bullet points that recruiters might search for. e.g., Project Management, Data Analysis, Agile Methodologies, Content Strategy, Python, Java, Cloud Security, UX/UI Design, B2B Marketing ]_\n"""
+ else: template += "[ Template structure for this document type will be provided here. Let me know what you need! ]"
+ return json.dumps({"template_markdown": template}) # Return JSON string
+
+def create_personalized_routine(emotion: str, goal: str, available_time_minutes: int = 60, routine_length_days: int = 7) -> str:
+ """Creates a personalized routine using fallback. Returns JSON string."""
logger.info(f"Executing tool: create_personalized_routine(emo='{emotion}', goal='{goal}', time={available_time_minutes}, days={routine_length_days})")
- # In a real scenario, you might try a *brief* internal AI call here first
- # for a more nuanced routine before falling back. For now, use fallback directly.
logger.warning("Using basic fallback for create_personalized_routine for robustness.")
try:
- routine = generate_basic_routine(emotion, goal, available_time_minutes, routine_length_days)
- if not routine or not isinstance(routine, dict): # generate_basic_routine returns a dict
+ routine_dict = generate_basic_routine(emotion, goal, available_time_minutes, routine_length_days)
+ if not routine_dict or not isinstance(routine_dict, dict):
raise ValueError("Basic routine generation failed to return a valid dictionary.")
- # Add a supportive message within the routine data
- routine['support_message'] = f"Hey, I know feeling {emotion} while aiming for '{goal}' can be tough. We've got this routine to help break it down. One step at a time, okay? You're doing great just by planning!"
- return routine # Return the dict directly
+ return json.dumps(routine_dict) # Return JSON string
except Exception as e:
logger.error(f"Error in create_personalized_routine fallback: {e}")
- # Return an error structure
- return {"error": f"Couldn't create a routine right now due to an error: {e}. Maybe try simplifying the goal or adjusting the time?"}
+ return json.dumps({"error": f"Couldn't create a routine right now due to an error: {e}. Maybe try simplifying the goal or adjusting the time?"})
-def analyze_resume(resume_text: str, career_goal: str) -> Dict[str, Any]:
- """Provides analysis of the resume (Simulated - AI analysis would replace this)."""
+def analyze_resume(resume_text: str, career_goal: str) -> str:
+ """Provides analysis of the resume (Simulated). Returns JSON string."""
logger.info(f"Executing tool: analyze_resume(goal='{career_goal}', len={len(resume_text)})")
- # !! Placeholder Analysis !! Replace with actual AI call in production if desired,
- # but the main AI handles this via system prompt now. This function is for the TOOL call.
logger.warning("Using placeholder analysis for analyze_resume tool.")
- analysis = {
- "strengths": [
- "Clear contact information.",
- "Uses some action verbs.",
- f"Mentions skills relevant to '{career_goal}' (needs verification)."
- ],
- "areas_for_improvement": [
- "Quantify achievements more (e.g., 'Increased X by Y%').",
- f"Ensure skills section is tailored specifically for '{career_goal}' roles.",
- "Check for consistent formatting and tense.",
- "Add a compelling summary/objective statement at the top."
- ],
- "format_feedback": "Overall format seems clean, but check for consistency.",
- "content_feedback": f"Content shows potential relevance to '{career_goal}', but needs more specific examples and quantified results.",
- "keyword_suggestions": ["Review job descriptions for "+ career_goal +" and incorporate relevant keywords like 'Keyword1', 'Keyword2', 'Keyword3'."],
- "next_steps": [
- "Revise bullet points under 'Experience' to include measurable results.",
- "Tailor the Summary/Objective and Skills sections for each application.",
- "Proofread carefully for any typos or grammatical errors."
- ]
- }
- return {"analysis": analysis} # Return dict
+ analysis = { "strengths": ["Clear contact information.", "Uses some action verbs.", f"Mentions skills potentially relevant to '{career_goal}'."], "areas_for_improvement": ["Quantify achievements more (e.g., 'Increased X by Y%').", f"Tailor skills section specifically for '{career_goal}' roles.", "Check for consistent formatting and tense.", "Add a compelling summary/objective statement."], "format_feedback": "Overall format seems clean, check consistency.", "content_feedback": f"Content shows potential relevance to '{career_goal}', but needs more specific examples and quantified results.", "keyword_suggestions": ["Review job descriptions for "+ career_goal +" and incorporate relevant keywords like 'Keyword1', 'Keyword2', 'Keyword3'."], "next_steps": ["Revise 'Experience' bullet points with measurable results.", "Tailor Summary/Objective and Skills sections per application.", "Proofread carefully."] }
+ return json.dumps({"analysis": analysis}) # Return JSON string
-def analyze_portfolio(portfolio_description: str, career_goal: str, portfolio_url: str = "") -> Dict[str, Any]:
- """Provides analysis of the portfolio (Simulated - AI analysis would replace this)."""
+def analyze_portfolio(portfolio_description: str, career_goal: str, portfolio_url: str = "") -> str:
+ """Provides analysis of the portfolio (Simulated). Returns JSON string."""
logger.info(f"Executing tool: analyze_portfolio(goal='{career_goal}', url='{portfolio_url}', desc_len={len(portfolio_description)})")
- # !! Placeholder Analysis !!
logger.warning("Using placeholder analysis for analyze_portfolio tool.")
- analysis = {
- "alignment_with_goal": f"Based on the description, seems moderately aligned with '{career_goal}'. Review specific projects.",
- "strengths": [
- "Includes a variety of projects (based on description).",
- "Clear description provided helps understand context."
- ] + (["Portfolio URL provided for direct review."] if portfolio_url else []),
- "areas_for_improvement": [
- f"Ensure project descriptions clearly link skills used to '{career_goal}' requirements.",
- "Consider adding 1-2 detailed case studies for key projects.",
- "Make sure navigation is intuitive (if URL provided)."
- ],
- "presentation_feedback": "Description is helpful. " + (f"Review URL ({portfolio_url}) for visual appeal and clarity." if portfolio_url else "Consider creating an online portfolio if you don't have one."),
- "next_steps": [
- "Highlight 2-3 projects most relevant to '{career_goal}' prominently.",
- "Get feedback from peers or mentors in your target field.",
- "Ensure contact information is easily accessible."
- ]
- }
- return {"analysis": analysis} # Return dict
+ analysis = { "alignment_with_goal": f"Based on description, seems moderately aligned with '{career_goal}'. Review specific projects.", "strengths": ["Includes a variety of projects (based on description).", "Clear description provided helps context."] + (["URL provided."] if portfolio_url else []), "areas_for_improvement": [f"Ensure project descriptions clearly link skills used to '{career_goal}' requirements.", "Consider adding 1-2 detailed case studies.", "Check navigation is intuitive (if URL provided)."], "presentation_feedback": "Description helpful. " + (f"Review URL ({portfolio_url}) for visual appeal/clarity." if portfolio_url else "Consider creating an online portfolio."), "next_steps": ["Highlight 2-3 projects most relevant to '{career_goal}' prominently.", "Get feedback from peers/mentors.", "Ensure contact info is easily accessible."] }
+ return json.dumps({"analysis": analysis}) # Return JSON string
-def extract_and_rate_skills_from_resume(resume_text: str, max_skills: int = 8) -> Dict[str, Any]:
- """Extracts and rates skills from resume text (Simulated - AI could do this better)."""
+def extract_and_rate_skills_from_resume(resume_text: str, max_skills: int = 8) -> str:
+ """Extracts and rates skills from resume text (Simulated). Returns JSON string."""
logger.info(f"Executing tool: extract_skills(len={len(resume_text)}, max={max_skills})")
- # !! Placeholder Extraction !!
logger.warning("Using placeholder skill extraction for extract_and_rate_skills_from_resume tool.")
possible = ["Python", "Java", "JavaScript", "Project Management", "Communication", "Data Analysis", "Teamwork", "Leadership", "SQL", "React", "Customer Service", "Problem Solving", "Cloud Computing", "AWS", "Azure", "GCP", "Agile Methodologies", "Machine Learning", "Marketing", "SEO", "Content Creation"]
found = []
resume_lower = resume_text.lower()
- # Basic keyword spotting
for skill in possible:
- # Use word boundaries to avoid matching substrings (e.g., 'java' in 'javascript')
if re.search(r'\b' + re.escape(skill.lower()) + r'\b', resume_lower):
- # Simulate rating based on frequency or context (very basic here)
score = random.randint(4, 9)
- if "lead" in resume_lower or "manage" in resume_lower or "develop" in resume_lower:
- score = min(10, score + random.randint(0, 1)) # Slightly boost if leadership words present
+ if "lead" in resume_lower or "manage" in resume_lower or "develop" in resume_lower: score = min(10, score + random.randint(0, 1))
found.append({"name": skill, "score": score})
if len(found) >= max_skills: break
-
- # Fallback if nothing found but resume is substantial
- if not found and len(resume_text) > 100:
- found = [
- {"name": "Communication", "score": random.randint(5,8)},
- {"name": "Teamwork", "score": random.randint(5,8)},
- {"name": "Problem Solving", "score": random.randint(5,8)},
- ]
+ if not found and len(resume_text) > 100: found = [ {"name": "Communication", "score": random.randint(5,8)}, {"name": "Teamwork", "score": random.randint(5,8)}, {"name": "Problem Solving", "score": random.randint(5,8)}, ]
logger.info(f"Extracted skills (placeholder): {[s['name'] for s in found]}")
- return {"skills": found[:max_skills]} # Return dict
+ return json.dumps({"skills": found[:max_skills]}) # Return JSON string
-# --- NEW: Serper Web Search Implementation ---
-def search_web_serper(search_query: str, search_type: str = 'general', location: str = None) -> Dict[str, Any]:
- """Performs a web search using the Serper API."""
+# --- Serper Web Search Implementation (Returns JSON string) ---
+def search_web_serper(search_query: str, search_type: str = 'general', location: str = None) -> str:
+ """Performs a web search using Serper API. Returns JSON string."""
logger.info(f"Executing tool: search_web_serper(query='{search_query}', type='{search_type}', loc='{location}')")
if not SERPER_API_KEY:
logger.error("SERPER_API_KEY not configured.")
- return {"error": "Web search functionality is not configured."}
+ return json.dumps({"error": "Web search functionality is not configured."})
api_url = "https://google.serper.dev/search"
- payload = json.dumps({
- "q": search_query,
- "location": location if location else None, # Add location if provided
- # Add other params like 'num' for number of results if needed
- })
- headers = {
- 'X-API-KEY': SERPER_API_KEY,
- 'Content-Type': 'application/json'
- }
+ payload = json.dumps({"q": search_query,"location": location if location else None})
+ headers = {'X-API-KEY': SERPER_API_KEY,'Content-Type': 'application/json'}
try:
- response = requests.post(api_url, headers=headers, data=payload, timeout=10) # Added timeout
- response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
+ response = requests.post(api_url, headers=headers, data=payload, timeout=10)
+ response.raise_for_status()
results = response.json()
-
- # Extract relevant information based on search type (simplified)
extracted_results = []
+ # (Keep the extraction logic from v3)
if search_type == 'jobs':
- # Look for job postings, titles, companies
- if 'jobs' in results: # Serper might have a dedicated jobs structure
- for job in results['jobs'][:5]: # Limit to top 5
- extracted_results.append({
- "title": job.get('title'),
- "company": job.get('company_name'),
- "location": job.get('location'),
- "link": job.get('link') # Assuming Serper provides a direct link
- })
- elif 'organic' in results: # Fallback to organic results
+ if 'jobs' in results:
+ for job in results['jobs'][:5]: extracted_results.append({"title": job.get('title'),"company": job.get('company_name'),"location": job.get('location'),"link": job.get('link')})
+ elif 'organic' in results:
for item in results['organic'][:5]:
- # Basic check if title sounds like a job
- if any(kw in item.get('title', '').lower() for kw in ['hiring', 'job', 'career', 'vacancy']):
- extracted_results.append({
- "title": item.get('title'),
- "snippet": item.get('snippet'),
- "link": item.get('link')
- })
+ if any(kw in item.get('title', '').lower() for kw in ['hiring', 'job', 'career', 'vacancy']): extracted_results.append({"title": item.get('title'),"snippet": item.get('snippet'),"link": item.get('link')})
elif search_type in ['courses', 'skills']:
- # Extract organic results (titles, links, snippets)
if 'organic' in results:
- for item in results['organic'][:5]:
- extracted_results.append({
- "title": item.get('title'),
- "snippet": item.get('snippet'),
- "link": item.get('link')
- })
+ for item in results['organic'][:5]: extracted_results.append({"title": item.get('title'),"snippet": item.get('snippet'),"link": item.get('link')})
else: # General search
if 'organic' in results:
- for item in results['organic'][:3]: # Limit general results
- extracted_results.append({
- "title": item.get('title'),
- "snippet": item.get('snippet'),
- "link": item.get('link')
- })
- # Maybe include answer box if relevant?
- if 'answerBox' in results:
- extracted_results.insert(0, { # Put answer box first
- "type": "Answer Box",
- "title": results['answerBox'].get('title'),
- "snippet": results['answerBox'].get('snippet') or results['answerBox'].get('answer'),
- "link": results['answerBox'].get('link')
- })
-
+ for item in results['organic'][:3]: extracted_results.append({"title": item.get('title'),"snippet": item.get('snippet'),"link": item.get('link')})
+ if 'answerBox' in results: extracted_results.insert(0, {"type": "Answer Box","title": results['answerBox'].get('title'),"snippet": results['answerBox'].get('snippet') or results['answerBox'].get('answer'),"link": results['answerBox'].get('link')})
logger.info(f"Serper search successful for '{search_query}'. Found {len(extracted_results)} relevant items.")
- return {"search_results": extracted_results} # Return dict
+ return json.dumps({"search_results": extracted_results}) # Return JSON string
except requests.exceptions.RequestException as e:
logger.error(f"Serper API request failed: {e}")
- return {"error": f"Web search failed: {e}"}
+ return json.dumps({"error": f"Web search failed: {e}"})
except Exception as e:
logger.error(f"Error processing Serper response: {e}")
- return {"error": "Failed to process web search results."}
+ return json.dumps({"error": "Failed to process web search results."})
-# --- AI Interaction Logic (Using Google Gemini) ---
+# --- AI Interaction Logic (Using OpenAI GPT-4o) ---
def get_ai_response(user_id: str, user_input: str) -> str:
- """Gets response from Google Gemini, handling context, system prompt, and function calls."""
- logger.info(f"Getting AI response for user {user_id}. Input: '{user_input[:100]}...'")
+ """Gets response from OpenAI GPT-4o, handling context, system prompt, and tool calls."""
+ logger.info(f"Getting OpenAI response for user {user_id}. Input: '{user_input[:100]}...'")
- if not gemini_model:
- logger.error("Gemini model not initialized.")
+ if not client:
+ logger.error("OpenAI client not initialized.")
return "I'm sorry, my AI core isn't available right now. Please check the configuration."
try:
@@ -727,8 +560,7 @@ def get_ai_response(user_id: str, user_input: str) -> str:
logger.error(f"Failed profile retrieval for {user_id}.")
return "Uh oh, I couldn't access your profile details right now. Let's try again in a moment?"
- # **INVESTOR NOTE:** The system prompt defines Aishura's unique empathetic persona and strategic approach.
- # This blend of emotional intelligence and career coaching is our key differentiator.
+ # **INVESTOR NOTE:** The system prompt defines Aishura's unique empathetic persona and strategic approach, now adapted for OpenAI.
current_emotion_display = user_profile.get('current_emotion', 'how you feel')
user_name = user_profile.get('name', 'there')
career_goal = user_profile.get('career_goal', 'your goals')
@@ -737,7 +569,7 @@ def get_ai_response(user_id: str, user_input: str) -> str:
exp_level = user_profile.get('experience_level', 'your experience level')
system_prompt = f"""
- You are Aishura, an advanced AI career assistant built on Google's Gemini model. Your core mission is to provide **empathetic, supportive, and highly personalized career guidance**. You are talking to {user_name}.
+ You are Aishura, an advanced AI career assistant powered by OpenAI's GPT-4o. Your core mission is to provide **empathetic, supportive, and highly personalized career guidance**. You are talking to {user_name}.
**Your Persona & Communication Style:**
* **Empathetic & Validating:** ALWAYS acknowledge the user's feelings ({current_emotion_display}). Use phrases like "I hear you," "It sounds like things are tough/exciting," "That makes total sense," "I get it." Validate their experience.
@@ -753,781 +585,498 @@ def get_ai_response(user_id: str, user_input: str) -> str:
* **Proactive Suggestions:** If they mention needing a resume, cover letter, or LinkedIn help, suggest using `generate_document_template`. If they feel stuck or need structure, suggest `create_personalized_routine`. If they mention their resume or portfolio, offer to analyze it (`analyze_resume`, `analyze_portfolio`). If they want to understand their skills better from their resume, suggest `extract_and_rate_skills_from_resume`.
* **Web Search (`search_jobs_courses_skills`):**
* **Use ONLY when the user explicitly asks for job openings, courses, skill resources, or specific company information.**
- * Construct a specific `search_query` based on their request, `career_goal`, `location`, `industry`, and potentially `areas_for_development`.
+ * Construct a specific `search_query` based on their request, `career_goal`, `location`, `industry`, etc.
* Specify `search_type` ('jobs', 'courses', 'skills', 'general').
- * Include `location` if relevant and available.
- * **Crucially:** Present the search results clearly. Mention they are *live* results but listings change quickly. Don't just dump links; summarize findings. E.g., "Okay, I found a few promising [type] results for you based on our search:"
- * **Do NOT Use Tools If:** The user is just chatting, venting, or asking for general advice that doesn't map directly to a tool's function. Handle these conversationally.
- 4. **Synthesize Tool Results:** When a tool (especially search) provides results, don't just output the raw data. Explain *why* these results are relevant to the user and their goals. Integrate the findings into your conversational response.
- 5. **Maintain Context:** Remember the conversation flow and user profile details.
- 6. **Handle Errors Gracefully:** If a tool fails or returns an error, apologize and explain simply (e.g., "Hmm, I couldn't fetch the [tool purpose] just now. Maybe we can try searching differently, or focus on [alternative action]?"). Do not show technical error messages to the user.
-
- **Example Snippets:**
- * "I got you. Feeling {emotion} is tough, but we'll break down this {goal} together."
- * "Okay, based on your goal of {goal} and feeling {emotion}, how about we create a manageable routine? I can use the `create_personalized_routine` tool if you'd like."
- * "Finding jobs can be draining. Want me to run a quick search for '{goal}' roles in {location} using the `search_jobs_courses_skills` tool?"
+ * Include `location` if relevant.
+ * **Crucially:** Present the search results clearly. Summarize findings, don't just dump links. E.g., "Okay, I ran a search using Serper and found a few promising [type] results for you:"
+ * **Do NOT Use Tools If:** The user is just chatting, venting, or asking for general advice not mapping to a tool. Handle these conversationally.
+ 4. **Synthesize Tool Results:** Explain *why* tool results are relevant. Integrate findings into your response.
+ 5. **Maintain Context:** Remember the conversation flow and profile.
+ 6. **Handle Errors Gracefully:** Apologize and explain simply if a tool fails (e.g., "Hmm, I couldn't fetch the [tool purpose] just now. Maybe we can try searching differently, or focus on [alternative action]?"). No technical errors to user.
"""
- # Prepare message history for Gemini API
- # Convert stored format {role: 'user'/'model'/'function', parts/response} to API format
- gemini_history = []
- for msg in user_profile.get('chat_history', []):
- if msg['role'] == 'function':
- # Convert tool/function response format
- gemini_history.append(genai.protos.Content(
- parts=[genai.protos.Part(
- function_response=genai.protos.FunctionResponse(name=msg['name'], response=msg['response'])
- )]
- ))
- elif 'parts' in msg: # Should be 'user' or 'model'
- # Ensure parts format is correct (list of Part objects)
- # Assuming stored parts are like [{'text': '...'}]
- try:
- api_parts = [genai.protos.Part(text=p['text']) for p in msg.get('parts', []) if 'text' in p]
- if api_parts: # Only add if there are valid parts
- gemini_history.append(genai.protos.Content(role=msg['role'], parts=api_parts))
- except Exception as e:
- logger.warning(f"Skipping invalid message structure in history: {msg} - Error: {e}")
-
+ # Prepare message history for OpenAI API
+ # Convert stored format to API format {role: '...', content: '...'}
+ messages = [{"role": "system", "content": system_prompt}]
+ chat_history = user_profile.get('chat_history', [])
+ for msg in chat_history:
+ # Basic validation before appending
+ if isinstance(msg, dict) and 'role' in msg:
+ api_msg = {"role": msg["role"]}
+ if msg["role"] in ["user", "assistant", "system"]:
+ # Handle messages with content and potentially tool_calls (for assistant)
+ if 'content' in msg and isinstance(msg.get('content'), (str, type(None))):
+ api_msg['content'] = msg.get('content') # Can be None for assistant msg with only tool_calls
+ else:
+ # If content is missing or wrong type for user/system, skip or log error
+ if msg["role"] != 'assistant':
+ logger.warning(f"Skipping message with missing/invalid content for role {msg['role']}: {msg}")
+ continue
+ else: # Assistant role, content can be None if tool_calls exist
+ api_msg['content'] = None
+
+ if msg["role"] == 'assistant' and 'tool_calls' in msg and isinstance(msg['tool_calls'], list):
+ # Validate tool_calls structure before adding
+ valid_tool_calls = all(isinstance(tc, dict) and 'id' in tc and 'type' in tc and 'function' in tc for tc in msg['tool_calls'])
+ if valid_tool_calls:
+ api_msg['tool_calls'] = msg['tool_calls']
+ else:
+ logger.warning(f"Invalid tool_calls structure found in history: {msg['tool_calls']}")
+ # Decide: skip message, or add without tool_calls if content exists?
+ if api_msg['content'] is None: continue # Skip if no content either
+
+ # Only append if content is not None OR tool_calls are present
+ if api_msg.get('content') is not None or api_msg.get('tool_calls'):
+ messages.append(api_msg)
+
+ elif msg["role"] == "tool":
+ # Handle tool responses
+ if 'tool_call_id' in msg and 'content' in msg and isinstance(msg.get('content'), str):
+ api_msg['tool_call_id'] = msg['tool_call_id']
+ api_msg['content'] = msg['content'] # Content is the stringified result
+ messages.append(api_msg)
+ else:
+ logger.warning(f"Skipping invalid tool message structure in history: {msg}")
+ continue
+ else:
+ logger.warning(f"Skipping message with unknown role: {msg['role']}")
+ continue
+ else:
+ logger.warning(f"Skipping invalid message format in history: {msg}")
+ continue
- # --- Main AI Interaction Loop (Handles Function Calling) ---
- current_input_parts = [genai.protos.Part(text=user_input)]
- prompt_content = genai.protos.Content(role='user', parts=current_input_parts)
- full_prompt_history = gemini_history + [prompt_content]
- logger.info(f"Sending {len(full_prompt_history)} history entries to Gemini model {MODEL_ID}.")
+ # Add current user input
+ messages.append({"role": "user", "content": user_input})
- # **INVESTOR NOTE:** The use of Gemini 1.5 Flash ensures rapid responses, crucial for user engagement.
- # The integrated function calling allows seamless access to specialized tools and live data (Serper).
+ # --- Make the initial API Call ---
+ logger.info(f"Sending {len(messages)} messages to OpenAI model {MODEL_ID}.")
try:
- response = gemini_model.generate_content(
- full_prompt_history,
- generation_config=genai.types.GenerationConfig(temperature=0.7, max_output_tokens=1500),
- tools=tools_list_gemini, # Pass the list of function declarations
- tool_config=genai.types.ToolConfig(function_calling_config="AUTO"), # Let model decide when to call functions
- system_instruction=genai.protos.Content(parts=[genai.protos.Part(text=system_prompt)]) # System prompt passed here
+ response = client.chat.completions.create(
+ model=MODEL_ID,
+ messages=messages,
+ tools=tools_list_openai,
+ tool_choice="auto", # Let model decide when to call functions
+ temperature=0.7,
+ max_tokens=1500
)
+ response_message = response.choices[0].message
+ finish_reason = response.choices[0].finish_reason
- response_message = response.candidates[0].content
- finish_reason = response.candidates[0].finish_reason
+ except openai.APIError as e: logger.error(f"OpenAI API Error: {e.status_code} - {e.response}"); return f"AI service error (Code: {e.status_code}). Try again."
+ except openai.APITimeoutError: logger.error("OpenAI timed out."); return "AI service request timed out. Try again."
+ except openai.APIConnectionError as e: logger.error(f"OpenAI Connection Error: {e}"); return "Cannot connect to AI service."
+ except openai.RateLimitError: logger.error("OpenAI Rate Limit Exceeded."); return "AI service busy. Try again shortly."
+ except openai.AuthenticationError: logger.error("OpenAI Authentication Error. Check API Key."); return "AI Authentication failed. Please check configuration."
+ except Exception as e: logger.exception(f"Unexpected error during OpenAI API call: {e}"); return "Oh dear, something unexpected happened on my end. Let's pause and retry?"
- except google_exceptions.ResourceExhausted as e:
- logger.error(f"Google API Quota Error: {e}")
- return "I'm experiencing high demand right now. Let's try that again in a moment?"
- except google_exceptions.GoogleAPIError as e:
- logger.error(f"Google API Error: {e}")
- return f"Sorry, there was an issue connecting to my AI brain ({e.message}). Could you try again?"
- except Exception as e:
- logger.exception(f"Unexpected error during Gemini API call: {e}")
- return "Oh dear, something unexpected happened on my end. Let's pause and retry?"
+ # --- Process the response ---
+ tool_calls = response_message.tool_calls
+ # Store user message (already added to 'messages' list for API call)
+ add_chat_message(user_id, "user", user_input)
- # Check if the model decided to call a function
- if response_message.parts[0].function_call.name:
- function_call = response_message.parts[0].function_call
- func_name = function_call.name
- func_args = dict(function_call.args) # Arguments are provided as a dict
+ # Store the initial assistant message (might contain text and/or tool calls)
+ assistant_message_for_db = {"content": response_message.content}
+ if tool_calls:
+ # Convert ToolCall objects to dictionaries for JSON serialization
+ assistant_message_for_db['tool_calls'] = [tc.model_dump() for tc in tool_calls]
+ add_chat_message(user_id, "assistant", assistant_message_for_db)
- logger.info(f"Gemini requested tool call: '{func_name}' with args: {func_args}")
- # Add the user message and the assistant's function call request to history
- add_chat_message(user_id, "user", user_input) # Store user input as text
- add_chat_message(user_id, "model", [{'text': f"Thinking... (using tool {func_name})"}]) # Placeholder text, real call stored below
+ # --- Handle Tool Calls if any ---
+ if tool_calls:
+ logger.info(f"OpenAI requested tool call(s): {[tc.function.name for tc in tool_calls]}")
+ messages.append(response_message) # Add assistant's msg with tool_calls to local list for next API call
- # --- Call the appropriate Python function ---
available_functions = {
"generate_document_template": generate_document_template,
"create_personalized_routine": create_personalized_routine,
"analyze_resume": analyze_resume,
"analyze_portfolio": analyze_portfolio,
"extract_and_rate_skills_from_resume": extract_and_rate_skills_from_resume,
- "search_jobs_courses_skills": search_web_serper, # Add Serper function
+ "search_jobs_courses_skills": search_web_serper,
}
- function_to_call = available_functions.get(func_name)
- function_response_content = None
+ # Execute functions and gather results
+ for tool_call in tool_calls:
+ function_name = tool_call.function.name
+ function_to_call = available_functions.get(function_name)
+ tool_call_id = tool_call.id
+ function_response_content = None # Initialize
- if function_to_call:
try:
- # Special handling for functions needing profile context or saving files
- if func_name == "analyze_resume":
- if 'career_goal' not in func_args: func_args['career_goal'] = career_goal
- save_user_resume(user_id, func_args.get('resume_text', '')) # Save resume if text provided
- elif func_name == "analyze_portfolio":
- if 'career_goal' not in func_args: func_args['career_goal'] = career_goal
- save_user_portfolio(user_id, func_args.get('portfolio_url', ''), func_args.get('portfolio_description', ''))
- elif func_name == "search_jobs_courses_skills":
- # Ensure location from profile is used if not specified in args
- if 'location' not in func_args or not func_args['location']:
- func_args['location'] = location if location != 'your area' else None # Pass None if default
-
- # Call the function with unpacked arguments
- logger.info(f"Calling function '{func_name}' with args: {func_args}")
- function_response_content = function_to_call(**func_args) # Expecting a dict or string
- logger.info(f"Function '{func_name}' returned type: {type(function_response_content)}")
-
- # Prepare response structure for Gemini
- tool_response_for_api = genai.protos.Part(
- function_response=genai.protos.FunctionResponse(
- name=func_name,
- response={'content': function_response_content} # Gemini expects response in a 'content' key
- )
- )
- # Store tool call result in DB
- add_chat_message(user_id, 'function', {'name': func_name, 'response': {'content': function_response_content}})
-
-
+ function_args = json.loads(tool_call.function.arguments)
+
+ if function_to_call:
+ # Special handling before calling
+ if function_name == "analyze_resume":
+ if 'career_goal' not in function_args: function_args['career_goal'] = career_goal
+ save_user_resume(user_id, function_args.get('resume_text', ''))
+ elif function_name == "analyze_portfolio":
+ if 'career_goal' not in function_args: function_args['career_goal'] = career_goal
+ save_user_portfolio(user_id, function_args.get('portfolio_url', ''), function_args.get('portfolio_description', ''))
+ elif function_name == "search_jobs_courses_skills":
+ if 'location' not in function_args or not function_args['location']:
+ function_args['location'] = location if location != 'your area' else None
+
+ logger.info(f"Calling function '{function_name}' with args: {function_args}")
+ # Functions return JSON strings
+ function_response_content = function_to_call(**function_args)
+ logger.info(f"Function '{function_name}' returned: {function_response_content[:200]}...")
+ else:
+ logger.warning(f"Function {function_name} not implemented.")
+ function_response_content = json.dumps({"error": f"Tool '{function_name}' not available."})
+
+ except json.JSONDecodeError as e:
+ logger.error(f"Error decoding args for {function_name}: {tool_call.function.arguments} - {e}")
+ function_response_content = json.dumps({"error": f"Invalid arguments received for tool '{function_name}'."})
except TypeError as e:
- logger.error(f"Argument mismatch for function {func_name}. Args: {func_args}, Error: {e}")
- error_response = {"error": f"Internal error: Tool '{func_name}' called with incorrect arguments."}
- tool_response_for_api = genai.protos.Part(function_response=genai.protos.FunctionResponse(name=func_name, response={'content': error_response}))
- add_chat_message(user_id, 'function', {'name': func_name, 'response': {'content': error_response}})
+ logger.error(f"Argument mismatch for function {function_name}. Args: {function_args}, Error: {e}")
+ function_response_content = json.dumps({"error": f"Internal error: Tool '{function_name}' called with incorrect arguments."})
except Exception as e:
- logger.exception(f"Error executing function {func_name}: {e}")
- error_response = {"error": f"Sorry, I encountered an error while trying to use the '{func_name}' tool. Please try again or ask differently."}
- # Prepare error response for Gemini
- tool_response_for_api = genai.protos.Part(
- function_response=genai.protos.FunctionResponse(
- name=func_name,
- response={'content': error_response} # Send error back to model
- )
- )
- # Store error result in DB
- add_chat_message(user_id, 'function', {'name': func_name, 'response': {'content': error_response}})
+ logger.exception(f"Error executing function {function_name}: {e}")
+ function_response_content = json.dumps({"error": f"Sorry, I encountered an error while trying to use the '{function_name}' tool."})
- else:
- logger.warning(f"Function {func_name} not implemented.")
- error_response = {"error": f"Tool '{func_name}' is not available."}
- tool_response_for_api = genai.protos.Part(
- function_response=genai.protos.FunctionResponse(
- name=func_name,
- response={'content': error_response}
- )
- )
- add_chat_message(user_id, 'function', {'name': func_name, 'response': {'content': error_response}})
+ # Append tool response to messages list for API
+ messages.append({
+ "tool_call_id": tool_call_id,
+ "role": "tool",
+ "content": function_response_content, # Content is the JSON string result
+ })
+ # Store tool response in DB
+ add_chat_message(user_id, "tool", {"tool_call_id": tool_call_id, "content": function_response_content})
- # --- Send function response back to the model ---
- logger.info(f"Sending function response for '{func_name}' back to Gemini.")
+ # --- Make the second API Call with tool results ---
+ logger.info(f"Sending {len(messages)} messages to OpenAI (incl. tool results).")
try:
- second_response = gemini_model.generate_content(
- # History includes original user prompt, model's func call, and the func response part
- gemini_history + [prompt_content, response_message, genai.protos.Content(parts=[tool_response_for_api])],
- generation_config=genai.types.GenerationConfig(temperature=0.7, max_output_tokens=1500),
- system_instruction=genai.protos.Content(parts=[genai.protos.Part(text=system_prompt)]) # Re-send system prompt
+ second_response = client.chat.completions.create(
+ model=MODEL_ID,
+ messages=messages, # Send history including system, user, assistant tool_call, and tool responses
+ temperature=0.7,
+ max_tokens=1500
)
- final_response_text = second_response.candidates[0].content.parts[0].text
- logger.info("Received final response after tool call.")
-
- except google_exceptions.GoogleAPIError as e:
- logger.error(f"Google API Error on second call: {e}")
- final_response_text = f"Sorry, there was an issue processing the results from the tool ({e.message}). Let's try again?"
- except Exception as e:
- logger.exception(f"Unexpected error during second Gemini call: {e}")
- final_response_text = "Oh dear, something went wrong while processing the tool's results. Could we try that step again?"
-
- # Store final assistant response
- add_chat_message(user_id, "model", final_response_text)
- return final_response_text
-
- else: # No function call, just a text response
- logger.info("No tool call requested by Gemini.")
- final_response_text = response_message.parts[0].text
- # Store user input and assistant response
- add_chat_message(user_id, "user", user_input)
- add_chat_message(user_id, "model", final_response_text)
+ final_response_text = second_response.choices[0].message.content
+ logger.info("Received final response after tool calls.")
+
+ # Store final assistant text response
+ add_chat_message(user_id, "assistant", {"content": final_response_text})
+ return final_response_text
+
+ except openai.APIError as e: logger.error(f"OpenAI API Error on second call: {e.status_code} - {e.response}"); return f"AI service error processing tool results (Code: {e.status_code})."
+ except openai.RateLimitError: logger.error("OpenAI Rate Limit Exceeded on second call."); return "AI service busy processing results. Try again shortly."
+ except Exception as e: logger.exception(f"Unexpected error during second OpenAI call: {e}"); return "Oh dear, something went wrong while processing the tool's results. Could we try that step again?"
+
+ else: # No tool calls were made
+ logger.info("No tool calls requested by OpenAI.")
+ final_response_text = response_message.content
+ # Assistant message already stored above
+ if not final_response_text:
+ final_response_text = "Okay, consider it done. How else can I assist you?" # Fallback if content is empty
return final_response_text
except Exception as e:
- logger.exception(f"Unexpected error in get_ai_response: {e}")
- return "An unexpected error occurred. Please try again later."
+ logger.exception(f"Critical error in get_ai_response: {e}")
+ return "A critical error occurred. Please try again later."
-# --- Recommendation Generation (Placeholder - Keep disabled or implement simple keyword based) ---
+# --- Recommendation Generation (Simple version - unchanged) ---
def gen_recommendations_simple(user_id):
- """Generate simple recommendations based on profile keywords (Placeholder)."""
+ # (Identical to v3)
logger.info(f"Generating simple recommendations for user {user_id}")
- profile = get_user_profile(user_id)
- recs = []
- goal = profile.get('career_goal', '').lower()
- emotion = profile.get('current_emotion', '').lower()
-
- # Simple keyword triggers
- if 'job' in goal or 'internship' in goal:
- recs.append({"title": "Refine Resume", "description": f"Tailor your resume for '{goal}' roles. Use keywords from job descriptions.", "priority": "High", "action_type": "Job Application"})
- recs.append({"title": "Practice Interviewing", "description": "Use the STAR method to prepare answers for common behavioral questions.", "priority": "Medium", "action_type": "Skill Building"})
- recs.append({"title": "Network Actively", "description": f"Connect with people in '{profile.get('industry', 'your')}' industry on LinkedIn or attend virtual events.", "priority": "Medium", "action_type": "Networking"})
-
- if 'skill' in goal:
- recs.append({"title": "Identify Learning Resources", "description": f"Find online courses (Coursera, Udemy, edX) or tutorials for the skills needed for '{goal}'.", "priority": "High", "action_type": "Skill Building"})
- recs.append({"title": "Start a Small Project", "description": f"Apply newly learned skills in a personal project to build portfolio evidence.", "priority": "Medium", "action_type": "Skill Building"})
-
- if emotion in ["anxious", "overwhelmed", "stuck", "unmotivated", "discouraged"]:
- recs.append({"title": "Focus on Small Wins", "description": "Break down larger tasks into very small, achievable steps. Celebrate completing them!", "priority": "High", "action_type": "Wellbeing"})
- recs.append({"title": "Schedule Breaks", "description": "Ensure you take regular short breaks to avoid burnout. Step away from the screen.", "priority": "Medium", "action_type": "Wellbeing"})
-
- # Add recommendations to user profile (limited number)
+ profile = get_user_profile(user_id); recs = []
+ goal = profile.get('career_goal', '').lower(); emotion = profile.get('current_emotion', '').lower()
+ if 'job' in goal or 'internship' in goal: recs.append({"title": "Refine Resume", "description": f"Tailor your resume for '{goal}' roles. Use keywords from job descriptions.", "priority": "High", "action_type": "Job Application"}); recs.append({"title": "Practice Interviewing", "description": "Use the STAR method to prepare answers for common behavioral questions.", "priority": "Medium", "action_type": "Skill Building"}); recs.append({"title": "Network Actively", "description": f"Connect with people in '{profile.get('industry', 'your')}' industry on LinkedIn or attend virtual events.", "priority": "Medium", "action_type": "Networking"})
+ if 'skill' in goal: recs.append({"title": "Identify Learning Resources", "description": f"Find online courses (Coursera, Udemy, edX) or tutorials for the skills needed for '{goal}'.", "priority": "High", "action_type": "Skill Building"}); recs.append({"title": "Start a Small Project", "description": f"Apply newly learned skills in a personal project to build portfolio evidence.", "priority": "Medium", "action_type": "Skill Building"})
+ if emotion in ["anxious", "overwhelmed", "stuck", "unmotivated", "discouraged"]: recs.append({"title": "Focus on Small Wins", "description": "Break down larger tasks into very small, achievable steps. Celebrate completing them!", "priority": "High", "action_type": "Wellbeing"}); recs.append({"title": "Schedule Breaks", "description": "Ensure you take regular short breaks to avoid burnout. Step away from the screen.", "priority": "Medium", "action_type": "Wellbeing"})
if recs:
- # Only add if substantially different from latest pending ones
- current_recs = profile.get('recommendations', [])
- pending_titles = {r['recommendation'].get('title') for r in current_recs if r.get('status') == 'pending'}
- new_recs_to_add = [r for r in recs if r.get('title') not in pending_titles]
-
- for rec in new_recs_to_add[:3]: # Add max 3 new ones
- add_recommendation_to_user(user_id, rec)
+ current_recs = profile.get('recommendations', []); pending_titles = {r['recommendation'].get('title') for r in current_recs if r.get('status') == 'pending'}; new_recs_to_add = [r for r in recs if r.get('title') not in pending_titles]
+ for rec in new_recs_to_add[:3]: add_recommendation_to_user(user_id, rec)
+ return
- return # Returns None, updates DB directly
-
-
-# --- Chart and Visualization Functions (Keep as is) ---
-# (create_emotion_chart, create_progress_chart, create_routine_completion_gauge, create_skill_radar_chart remain unchanged)
-# ... (Previous chart functions code - no changes needed here) ...
+# --- Chart and Visualization Functions (Identical to v3) ---
+# (create_emotion_chart, create_progress_chart, create_routine_completion_gauge, create_skill_radar_chart functions are identical to v3)
def create_emotion_chart(user_id):
user_profile = get_user_profile(user_id); records = user_profile.get('daily_emotions', [])
if not records: fig = go.Figure(); fig.add_annotation(text="No emotion data yet. How are you feeling today?", showarrow=False); fig.update_layout(title="Your Emotional Journey"); return fig
- # Added more emotions to map
vals = {"Unmotivated": 1, "Discouraged": 1.5, "Stuck": 2, "Anxious": 2.5, "Confused": 3, "Overwhelmed": 3.5, "Hopeful": 4.5, "Focused": 5, "Excited": 6}
dates = [datetime.fromisoformat(r['date']) for r in records]; scores = [vals.get(r['emotion'], 3) for r in records]; names = [r['emotion'] for r in records]
df = pd.DataFrame({'Date': dates, 'Score': scores, 'Emotion': names}).sort_values('Date')
fig = px.line(df, x='Date', y='Score', markers=True, labels={"Score": "State"}, title="Your Emotional Journey")
- fig.update_traces(hovertemplate='%{x|%Y-%m-%d %H:%M}
Feeling: %{text}', text=df['Emotion']); fig.update_yaxes(tickvals=list(vals.values()), ticktext=list(vals.keys())); return fig
+ fig.update_traces(hovertemplate='%{x|%Y-%m-%d %H:%M}
Feeling: %{text}', text=df['Emotion']); fig.update_yaxes(tickvals=list(vals.values()), ticktext=list(vals.keys())); return fig
def create_progress_chart(user_id):
user_profile = get_user_profile(user_id); tasks = user_profile.get('completed_tasks', [])
if not tasks: fig = go.Figure(); fig.add_annotation(text="No tasks completed yet. Let's add one!", showarrow=False); fig.update_layout(title="Progress Points"); return fig
tasks.sort(key=lambda x: datetime.fromisoformat(x['date']))
- dates, points, labels, cum_pts = [], [], [], 0; pts_task = user_profile.get('progress_points', 0) # Start from current total
- task_dates = {} # Track points per day
+ task_dates = {}
for task in tasks:
task_date_str = datetime.fromisoformat(task['date']).strftime('%Y-%m-%d')
- pts = task.get('points', random.randint(10, 25)) # Use stored points if available
+ pts = task.get('points', random.randint(10, 25))
if task_date_str not in task_dates: task_dates[task_date_str] = {'date': datetime.fromisoformat(task['date']).date(), 'points': 0, 'tasks': []}
task_dates[task_date_str]['points'] += pts
task_dates[task_date_str]['tasks'].append(task['task'])
-
- # Aggregate points daily for chart
- sorted_dates = sorted(task_dates.keys())
- cumulative_points = 0
- chart_dates, chart_points, chart_tasks = [], [], []
+ sorted_dates = sorted(task_dates.keys()); cumulative_points = 0; chart_dates, chart_points, chart_tasks = [], [], []
for date_str in sorted_dates:
- day_data = task_dates[date_str]
- cumulative_points += day_data['points']
- chart_dates.append(day_data['date'])
- chart_points.append(cumulative_points)
- chart_tasks.append("
".join(day_data['tasks'])) # Combine tasks for hover
-
- if not chart_dates: # Handle case if somehow no dates processed
- fig = go.Figure(); fig.add_annotation(text="Error processing task data.", showarrow=False); fig.update_layout(title="Progress Points"); return fig
-
-
+ day_data = task_dates[date_str]; cumulative_points += day_data['points']; chart_dates.append(day_data['date']); chart_points.append(cumulative_points); chart_tasks.append("
".join(day_data['tasks']))
+ if not chart_dates: fig = go.Figure(); fig.add_annotation(text="Error processing task data.", showarrow=False); fig.update_layout(title="Progress Points"); return fig
df = pd.DataFrame({'Date': chart_dates, 'Points': chart_points, 'Tasks': chart_tasks})
- fig = px.line(df, x='Date', y='Points', markers=True, title="Progress Journey"); fig.update_traces(hovertemplate='%{x|%Y-%m-%d}
Points: %{y}
Tasks:
%{text}', text=df['Tasks']); return fig
-
+ fig = px.line(df, x='Date', y='Points', markers=True, title="Progress Journey"); fig.update_traces(hovertemplate='%{x|%Y-%m-%d}
Points: %{y}
Tasks:
%{text}', text=df['Tasks']); return fig
def create_routine_completion_gauge(user_id):
user_profile = get_user_profile(user_id); routines = user_profile.get('routine_history', [])
if not routines: fig = go.Figure(go.Indicator(mode="gauge", value=0, title={'text': "Active Routine"})); fig.add_annotation(text="No routine active. Create one?", showarrow=False); return fig
latest = routines[0]; completion = latest.get('completion', 0); name = latest.get('routine', {}).get('name', 'Routine')
- fig = go.Figure(go.Indicator(mode="gauge+number", value=completion, domain={'x': [0, 1], 'y': [0, 1]}, title={'text': f"{name} (%)"},
- gauge={'axis': {'range': [0, 100]}, 'bar': {'color': "cornflowerblue"}, 'bgcolor': "white", 'steps': [{'range': [0, 50], 'color': 'whitesmoke'}, {'range': [50, 80], 'color': 'lightgray'}], 'threshold': {'line': {'color': "green", 'width': 4}, 'thickness': 0.75, 'value': 90}})); return fig
+ fig = go.Figure(go.Indicator(mode="gauge+number", value=completion, domain={'x': [0, 1], 'y': [0, 1]}, title={'text': f"{name} (%)"}, gauge={'axis': {'range': [0, 100]}, 'bar': {'color': "cornflowerblue"}, 'bgcolor': "white", 'steps': [{'range': [0, 50], 'color': 'whitesmoke'}, {'range': [50, 80], 'color': 'lightgray'}], 'threshold': {'line': {'color': "green", 'width': 4}, 'thickness': 0.75, 'value': 90}})); return fig
def create_skill_radar_chart(user_id):
logger.info(f"Creating skill chart for {user_id}"); user_profile = get_user_profile(user_id); path = user_profile.get('resume_path')
if not path or not os.path.exists(path): logger.warning("No resume found for skill chart."); fig = go.Figure(); fig.add_annotation(text="Upload or Analyze Resume for Skill Chart", showarrow=False); fig.update_layout(title="Identified Skills"); return fig
try:
with open(path, 'r', encoding='utf-8') as f: text = f.read()
- # Use the tool function to get skills (even if simulated)
- skills_data = extract_and_rate_skills_from_resume(resume_text=text) # Returns a dict
+ skills_json_str = extract_and_rate_skills_from_resume(resume_text=text) # Returns JSON string
+ skills_data = json.loads(skills_json_str) # Parse JSON string
if 'skills' in skills_data and skills_data['skills']:
- skills = skills_data['skills'][:8] # Limit to 8 for readability
- cats = [s['name'] for s in skills]; vals = [s['score'] for s in skills]
- if len(cats) < 3: # Radar needs >= 3 points
- fig = go.Figure(); fig.add_annotation(text="Need at least 3 skills identified for radar chart.", showarrow=False); fig.update_layout(title="Identified Skills"); return fig
-
- # Ensure the plot loops back
- if len(cats) > 2:
- cats.append(cats[0])
- vals.append(vals[0])
-
- fig = go.Figure();
- fig.add_trace(go.Scatterpolar(
- r=vals,
- theta=cats,
- fill='toself',
- name='Skills',
- hovertemplate='Skill: %{theta}
Score: %{r}' # Custom hover
- ))
- fig.update_layout(
- polar=dict(radialaxis=dict(visible=True, range=[0, 10], showline=False, ticksuffix=' pts')), # Added units
- showlegend=False,
- title="Skill Assessment (from Resume)"
- )
+ skills = skills_data['skills'][:8]; cats = [s['name'] for s in skills]; vals = [s['score'] for s in skills]
+ if len(cats) < 3: fig = go.Figure(); fig.add_annotation(text="Need at least 3 skills identified for radar chart.", showarrow=False); fig.update_layout(title="Identified Skills"); return fig
+ if len(cats) > 2: cats.append(cats[0]); vals.append(vals[0])
+ fig = go.Figure(); fig.add_trace(go.Scatterpolar(r=vals, theta=cats, fill='toself', name='Skills', hovertemplate='Skill: %{theta}
Score: %{r}'))
+ fig.update_layout(polar=dict(radialaxis=dict(visible=True, range=[0, 10], showline=False, ticksuffix=' pts')), showlegend=False, title="Skill Assessment (from Resume)")
logger.info(f"Created radar chart with {len(skills)} skills."); return fig
else: logger.warning("No skills extracted for chart."); fig = go.Figure(); fig.add_annotation(text="No skills extracted from resume yet.", showarrow=False); fig.update_layout(title="Identified Skills"); return fig
except Exception as e: logger.exception(f"Error creating skill chart: {e}"); fig = go.Figure(); fig.add_annotation(text="Error analyzing skills.", showarrow=False); fig.update_layout(title="Identified Skills"); return fig
-# --- Gradio Interface Components ---
-# **INVESTOR NOTE:** The Gradio interface provides an accessible and interactive front-end.
-# We prioritize a clean UX, focusing on the chat interaction while making powerful tools easily accessible.
+# --- Gradio Interface Components (Mostly identical to v3, ensure compatibility) ---
def create_interface():
- """Create the Gradio interface for Aishura v3"""
- # Use a persistent session ID or implement user login for production
- session_user_id = str(uuid.uuid4()) # Simple session ID for demo purposes
- logger.info(f"Initializing Gradio interface for session user ID: {session_user_id}")
- get_user_profile(session_user_id) # Initialize profile if it doesn't exist
+ """Create the Gradio interface for Aishura v4 (OpenAI)"""
+ session_user_id = str(uuid.uuid4())
+ logger.info(f"Initializing Gradio interface v4 for session user ID: {session_user_id}")
+ get_user_profile(session_user_id) # Initialize profile
- # --- Event Handlers ---
+ # --- Event Handlers (Adapted slightly if needed) ---
def welcome(name, location, emotion, goal, industry, exp_level, work_style):
- logger.info(f"Welcome: name='{name}', loc='{location}', emo='{emotion}', goal='{goal}', industry='{industry}', exp='{exp_level}', work='{work_style}'")
- if not all([name, location, emotion, goal]):
- # Basic validation
- return ("Please fill in your Name, Location, Emotion, and Goal to get started!", gr.update(visible=True), gr.update(visible=False), gr.update(), gr.update(), gr.update(), gr.update(), gr.update())
-
- # Clean goal text (remove emoji if present)
+ # (Logic identical to v3 welcome handler)
+ logger.info(f"Welcome v4: name='{name}', loc='{location}', emo='{emotion}', goal='{goal}', industry='{industry}', exp='{exp_level}', work='{work_style}'")
+ if not all([name, location, emotion, goal]): return ("Please fill in your Name, Location, Emotion, and Goal to get started!", gr.update(visible=True), gr.update(visible=False), gr.update(), gr.update(), gr.update(), gr.update(), gr.update())
cleaned_goal = goal.rsplit(" ", 1)[0] if goal[-1].isnumeric() == False and goal[-2] == " " else goal
-
- # Update profile with initial info
- profile_updates = {
- "name": name,
- "location": location,
- "career_goal": cleaned_goal,
- "industry": industry,
- "experience_level": exp_level,
- "preferred_work_style": work_style
- }
+ profile_updates = {"name": name, "location": location, "career_goal": cleaned_goal, "industry": industry, "experience_level": exp_level, "preferred_work_style": work_style}
update_user_profile(session_user_id, profile_updates)
- add_emotion_record(session_user_id, emotion) # Add initial emotion
-
- # **INVESTOR NOTE:** The initial interaction immediately personalizes the experience and sets an empathetic tone.
+ add_emotion_record(session_user_id, emotion)
initial_input = f"Hi Aishura! I'm {name} from {location}. I'm focusing on '{cleaned_goal}' in the {industry} industry ({exp_level}, preferring {work_style} work). Right now, I'm feeling {emotion}. Can you help me get started?"
-
- # Get the first AI response
- ai_response = get_ai_response(session_user_id, initial_input)
-
- # Prepare chat history display for Gradio
- # Gemini uses {role: 'user'/'model', parts: [{'text': '...'}]}
- # Gradio chatbot expects [[user_msg, assistant_msg], ...]
+ ai_response = get_ai_response(session_user_id, initial_input) # Calls the OpenAI version
+ # Convert DB history (OpenAI format) to Gradio format [[user, assistant], ...]
+ # For initial display, it's just the first exchange
initial_chat_display = [[initial_input, ai_response]]
-
- # Update charts
e_fig, p_fig, r_fig, s_fig = create_emotion_chart(session_user_id), create_progress_chart(session_user_id), create_routine_completion_gauge(session_user_id), create_skill_radar_chart(session_user_id)
- recs_md = display_recommendations(session_user_id) # Display initial recommendations
-
- return (
- gr.update(value=initial_chat_display), # Update chatbot
- gr.update(visible=False), # Hide welcome group
- gr.update(visible=True), # Show main interface
- gr.update(value=e_fig), gr.update(value=p_fig), gr.update(value=r_fig), gr.update(value=s_fig), # Update plots
- gr.update(value=recs_md) # Update recommendations markdown
- )
+ gen_recommendations_simple(session_user_id) # Generate initial recommendations
+ recs_md = display_recommendations(session_user_id)
+ return (gr.update(value=initial_chat_display), gr.update(visible=False), gr.update(visible=True), gr.update(value=e_fig), gr.update(value=p_fig), gr.update(value=r_fig), gr.update(value=s_fig), gr.update(value=recs_md))
def chat_submit(message_text, history_list_list):
- """Handles chatbot submission, gets AI response, updates history and recommendations."""
- logger.info(f"Chat submit for {session_user_id}: '{message_text[:50]}...'")
- if not message_text:
- return history_list_list, "" # Return current history and clear textbox
-
- # Append user message to Gradio display history immediately
- history_list_list.append([message_text, None]) # Add placeholder for assistant response
- yield history_list_list, "" # Update UI immediately, clear textbox
+ # (Logic identical to v3 chat_submit handler)
+ logger.info(f"Chat submit v4 for {session_user_id}: '{message_text[:50]}...'")
+ if not message_text: yield history_list_list, gr.update() # No change if empty message
+ else:
+ history_list_list.append([message_text, None])
+ yield history_list_list, gr.update() # Update UI with user message, clear textbox handled by .then()
- # Get AI response (which also updates the internal DB history)
- ai_response_text = get_ai_response(session_user_id, message_text)
+ ai_response_text = get_ai_response(session_user_id, message_text) # Calls OpenAI version
+ history_list_list[-1][1] = ai_response_text # Update assistant response
- # Update the placeholder in Gradio display history with the actual response
- history_list_list[-1][1] = ai_response_text
+ gen_recommendations_simple(session_user_id) # Generate recommendations
+ recs_md = display_recommendations(session_user_id)
- # Generate and display recommendations
- gen_recommendations_simple(session_user_id) # Generate based on latest interaction (simple version)
- recs_md = display_recommendations(session_user_id)
+ yield history_list_list, gr.update(value=recs_md) # Update UI with assistant response and recommendations
- # Update UI again with the final response and recommendations
- yield history_list_list, gr.update(value=recs_md)
-
- # --- Tool Interface Handlers (Manual Trigger from UI) ---
- # These call the *implementation* functions directly, bypassing AI unless needed internally
+ # --- Tool Interface Handlers (Call implementations directly) ---
def generate_template_interface_handler(doc_type, career_field, experience):
- logger.info(f"Manual Template UI: type='{doc_type}'")
- # Call implementation directly
- result_dict = generate_document_template(doc_type, career_field, experience)
- return result_dict.get('template_markdown', "Error generating template.")
+ logger.info(f"Manual Template UI v4: type='{doc_type}'")
+ json_str = generate_document_template(doc_type, career_field, experience)
+ try: return json.loads(json_str).get('template_markdown', "Error.")
+ except: return "Error displaying template."
def create_routine_interface_handler(emotion, goal, time_available, days):
- logger.info(f"Manual Routine UI: emo='{emotion}', goal='{goal}'")
+ logger.info(f"Manual Routine UI v4: emo='{emotion}', goal='{goal}'")
cleaned_emotion = emotion.split(" ")[0] if " " in emotion else emotion
- # Call implementation directly (uses fallback basic generator)
- result_dict = create_personalized_routine(cleaned_emotion, goal, int(time_available), int(days))
-
- if "error" in result_dict:
- return f"Error: {result_dict['error']}", gr.update()
-
- # Save routine to user profile
- add_routine_to_user(session_user_id, result_dict)
-
- # Format for display
- md = f"# {result_dict.get('name', 'Your Routine')}\n\n"
- md += f"_{result_dict.get('support_message', result_dict.get('description', ''))}_\n\n---\n\n" # Use support message
- for day in result_dict.get('daily_tasks', []):
- md += f"## Day {day.get('day', '?')}\n"
- tasks = day.get('tasks', [])
- if not tasks:
- md += "- Rest day or catch-up.\n"
- else:
- for task in tasks:
- md += f"- **{task.get('name', 'Task')}** ({task.get('duration', '?')} min)\n"
- md += f" - _{task.get('description', '...')}_\n"
- md += "\n"
-
- gauge = create_routine_completion_gauge(session_user_id)
- return md, gr.update(value=gauge) # Update markdown and gauge plot
+ json_str = create_personalized_routine(cleaned_emotion, goal, int(time_available), int(days))
+ try:
+ data = json.loads(json_str)
+ if "error" in data: return f"Error: {data['error']}", gr.update()
+ add_routine_to_user(session_user_id, data) # Save the dict structure
+ md = f"# {data.get('name', 'Your Routine')}\n\n"
+ md += f"_{data.get('support_message', data.get('description', ''))}_\n\n---\n\n"
+ for day in data.get('daily_tasks', []):
+ md += f"## Day {day.get('day', '?')}\n"; tasks = day.get('tasks', [])
+ if not tasks: md += "- Rest day or catch-up.\n"
+ else:
+ for task in tasks: md += f"- **{task.get('name', 'Task')}** ({task.get('duration', '?')} min)\n - _{task.get('description', '...')}_\n"
+ md += "\n"
+ gauge = create_routine_completion_gauge(session_user_id)
+ return md, gr.update(value=gauge)
+ except Exception as e: logger.exception("Error displaying routine"); return f"Error displaying routine: {e}", gr.update()
def analyze_resume_interface_handler(resume_file):
- logger.info(f"Manual Resume Analysis UI: file={resume_file}")
- if resume_file is None:
- return "Please upload a resume file.", gr.update(value=None), gr.update(value=None)
-
+ # (Logic identical to v3, calls the updated tool function)
+ logger.info(f"Manual Resume Analysis UI v4: file={resume_file}")
+ if resume_file is None: return "Please upload a resume file.", gr.update(value=None), gr.update(value=None)
try:
- # Read text content from uploaded file object
- with open(resume_file.name, 'r', encoding='utf-8') as f:
- resume_text = f.read()
+ with open(resume_file.name, 'r', encoding='utf-8') as f: resume_text = f.read()
logger.info(f"Read {len(resume_text)} characters from uploaded resume.")
- except Exception as e:
- logger.error(f"Error reading uploaded resume file: {e}")
- return f"Error reading file: {e}", gr.update(value=None), gr.update(value=None)
-
-
- if not resume_text:
- return "Resume file seems empty.", gr.update(value=None), gr.update(value=None)
-
- profile = get_user_profile(session_user_id)
- goal = profile.get('career_goal', 'Not specified')
-
- # Save resume text to user profile (associates it)
+ except Exception as e: logger.error(f"Error reading uploaded resume file: {e}"); return f"Error reading file: {e}", gr.update(value=None), gr.update(value=None)
+ if not resume_text: return "Resume file seems empty.", gr.update(value=None), gr.update(value=None)
+ profile = get_user_profile(session_user_id); goal = profile.get('career_goal', 'Not specified')
resume_path = save_user_resume(session_user_id, resume_text)
- if not resume_path:
- return "Could not save resume file for analysis.", gr.update(value=None), gr.update(value=None)
-
-
- # Call analysis tool implementation function
- analysis_result = analyze_resume(resume_text, goal) # Returns dict
-
+ if not resume_path: return "Could not save resume file.", gr.update(value=None), gr.update(value=None)
+ analysis_json_str = analyze_resume(resume_text, goal) # Returns JSON string
try:
- analysis = analysis_result.get('analysis', {})
- md = f"## Resume Analysis (Simulated)\n\n**Analyzing for Goal:** '{goal}'\n\n"
- md += "**Strengths Identified:**\n" + "\n".join([f"* {s}" for s in analysis.get('strengths', ["None identified."])]) + "\n\n"
- md += "**Areas for Improvement:**\n" + "\n".join([f"* {s}" for s in analysis.get('areas_for_improvement', ["None identified."])]) + "\n\n"
- md += f"**Format Feedback:** {analysis.get('format_feedback', 'N/A')}\n"
- md += f"**Content Alignment:** {analysis.get('content_feedback', 'N/A')}\n"
- md += f"**Suggested Keywords:** {', '.join(analysis.get('keyword_suggestions', ['N/A']))}\n\n"
- md += "**Recommended Next Steps:**\n" + "\n".join([f"* {s}" for s in analysis.get('next_steps', ["Review suggestions."])])
-
- # Update skill chart based on the new resume analysis
+ analysis_result = json.loads(analysis_json_str); analysis = analysis_result.get('analysis', {})
+ md = f"## Resume Analysis (Simulated)\n\n**Analyzing for Goal:** '{goal}'\n\n"; md += "**Strengths Identified:**\n" + "\n".join([f"* {s}" for s in analysis.get('strengths', ["None identified."])]) + "\n\n"; md += "**Areas for Improvement:**\n" + "\n".join([f"* {s}" for s in analysis.get('areas_for_improvement', ["None identified."])]) + "\n\n"; md += f"**Format Feedback:** {analysis.get('format_feedback', 'N/A')}\n"; md += f"**Content Alignment:** {analysis.get('content_feedback', 'N/A')}\n"; md += f"**Suggested Keywords:** {', '.join(analysis.get('keyword_suggestions', ['N/A']))}\n\n"; md += "**Recommended Next Steps:**\n" + "\n".join([f"* {s}" for s in analysis.get('next_steps', ["Review suggestions."])])
skill_fig = create_skill_radar_chart(session_user_id)
+ return md, gr.update(value=skill_fig), gr.update(value=resume_path)
+ except Exception as e: logger.exception("Error formatting resume analysis results."); return "Error displaying analysis results.", gr.update(value=None), gr.update(value=None)
- return md, gr.update(value=skill_fig), gr.update(value=resume_path) # Return analysis text, skill chart, and path
-
- except Exception as e:
- logger.exception("Error formatting resume analysis results.")
- return "Error displaying analysis results.", gr.update(value=None), gr.update(value=None)
def analyze_portfolio_interface_handler(portfolio_url, portfolio_description):
- logger.info(f"Manual Portfolio Analysis UI: url='{portfolio_url}'")
- if not portfolio_description:
- return "Please provide a description of your portfolio."
-
- profile = get_user_profile(session_user_id)
- goal = profile.get('career_goal', 'Not specified')
-
- # Save portfolio info
+ # (Logic identical to v3, calls the updated tool function)
+ logger.info(f"Manual Portfolio Analysis UI v4: url='{portfolio_url}'")
+ if not portfolio_description: return "Please provide a description of your portfolio."
+ profile = get_user_profile(session_user_id); goal = profile.get('career_goal', 'Not specified')
portfolio_path = save_user_portfolio(session_user_id, portfolio_url, portfolio_description)
- if not portfolio_path:
- return "Could not save portfolio details."
-
-
- # Call analysis tool implementation function
- analysis_result = analyze_portfolio(portfolio_description, goal, portfolio_url) # Returns dict
-
+ if not portfolio_path: return "Could not save portfolio details."
+ analysis_json_str = analyze_portfolio(portfolio_description, goal, portfolio_url) # Returns JSON string
try:
- analysis = analysis_result.get('analysis', {})
- md = f"## Portfolio Analysis (Simulated)\n\n**Analyzing for Goal:** '{goal}'\n"
- if portfolio_url: md += f"**URL:** {portfolio_url}\n\n"
- else: md += "\n"
-
- md += f"**Alignment with Goal:** {analysis.get('alignment_with_goal', 'N/A')}\n\n"
- md += "**Strengths Based on Description:**\n" + "\n".join([f"* {s}" for s in analysis.get('strengths', ["N/A"])]) + "\n\n"
- md += "**Areas for Improvement:**\n" + "\n".join([f"* {s}" for s in analysis.get('areas_for_improvement', ["N/A"])]) + "\n\n"
- md += f"**Presentation Feedback:** {analysis.get('presentation_feedback', 'N/A')}\n\n"
- md += "**Recommended Next Steps:**\n" + "\n".join([f"* {s}" for s in analysis.get('next_steps', ["Review suggestions."])])
-
+ analysis_result = json.loads(analysis_json_str); analysis = analysis_result.get('analysis', {})
+ md = f"## Portfolio Analysis (Simulated)\n\n**Analyzing for Goal:** '{goal}'\n"; md += f"**URL:** {portfolio_url}\n\n" if portfolio_url else "\n"; md += f"**Alignment with Goal:** {analysis.get('alignment_with_goal', 'N/A')}\n\n"; md += "**Strengths Based on Description:**\n" + "\n".join([f"* {s}" for s in analysis.get('strengths', ["N/A"])]) + "\n\n"; md += "**Areas for Improvement:**\n" + "\n".join([f"* {s}" for s in analysis.get('areas_for_improvement', ["N/A"])]) + "\n\n"; md += f"**Presentation Feedback:** {analysis.get('presentation_feedback', 'N/A')}\n\n"; md += "**Recommended Next Steps:**\n" + "\n".join([f"* {s}" for s in analysis.get('next_steps', ["Review suggestions."])])
return md
+ except Exception as e: logger.exception("Error formatting portfolio analysis results."); return "Error displaying analysis results."
- except Exception as e:
- logger.exception("Error formatting portfolio analysis results.")
- return "Error displaying analysis results."
-
- # --- Progress Tracking Handlers ---
+ # --- Progress Tracking Handlers (Identical to v3) ---
def complete_task_handler(task_name):
- logger.info(f"Complete Task UI for {session_user_id}: task='{task_name}'")
- if not task_name:
- return ("Please enter the task you completed.", "", gr.update(), gr.update(), gr.update())
-
+ logger.info(f"Complete Task UI v4 for {session_user_id}: task='{task_name}'")
+ if not task_name: return ("Please enter the task you completed.", "", gr.update(), gr.update(), gr.update())
updated_profile = add_task_to_user(session_user_id, task_name)
-
- # Update routine completion if a routine is active
if updated_profile and updated_profile.get('routine_history'):
- db = load_user_database() # Reload DB after add_task potentially saved it
- profile = db.get('users', {}).get(session_user_id)
- if profile and profile.get('routine_history'): # Check again after reload
- latest_routine = profile['routine_history'][0]
- # Simple completion increment - could be smarter based on task type/routine content
- increment = random.randint(5, 15)
- latest_routine['completion'] = min(100, latest_routine.get('completion', 0) + increment)
- save_user_database(db) # Save updated routine completion
-
- # Update charts
+ db = load_user_database(); profile = db.get('users', {}).get(session_user_id)
+ if profile and profile.get('routine_history'):
+ latest_routine = profile['routine_history'][0]; increment = random.randint(5, 15)
+ latest_routine['completion'] = min(100, latest_routine.get('completion', 0) + increment); save_user_database(db)
e_fig, p_fig, g_fig = create_emotion_chart(session_user_id), create_progress_chart(session_user_id), create_routine_completion_gauge(session_user_id)
-
return (f"Awesome job completing '{task_name}'! Keep up the great work!", "", gr.update(value=e_fig), gr.update(value=p_fig), gr.update(value=g_fig))
def update_emotion_handler(emotion):
- logger.info(f"Update Emotion UI for {session_user_id}: emotion='{emotion}'")
- if not emotion:
- return "Please select how you're feeling.", gr.update()
-
+ logger.info(f"Update Emotion UI v4 for {session_user_id}: emotion='{emotion}'")
+ if not emotion: return "Please select how you're feeling.", gr.update()
add_emotion_record(session_user_id, emotion)
e_fig = create_emotion_chart(session_user_id)
cleaned_display = emotion.split(" ")[0] if " " in emotion else emotion
-
return f"Got it. Acknowledging how you feel ({cleaned_display}) is a great step.", gr.update(value=e_fig)
def display_recommendations(current_user_id):
- """Formats latest recommendations into Markdown for display."""
- logger.info(f"Displaying recommendations for {current_user_id}")
- profile = get_user_profile(current_user_id)
- recs = profile.get('recommendations', [])
-
- if not recs:
- return "Chat with me about your goals and challenges, and I can suggest some next steps! 😊"
-
- # Show only pending recommendations, most recent first
- pending_recs = [r for r in recs if r.get('status') == 'pending'][:5] # Get latest 5 pending
-
- if not pending_recs:
- return "No pending recommendations right now. Great job, or let's chat to find new ones!"
-
+ # (Identical to v3)
+ logger.info(f"Displaying recommendations v4 for {current_user_id}")
+ profile = get_user_profile(current_user_id); recs = profile.get('recommendations', [])
+ if not recs: return "Chat with me about your goals and challenges, and I can suggest some next steps! 😊"
+ pending_recs = [r for r in recs if r.get('status') == 'pending'][:5]
+ if not pending_recs: return "No pending recommendations right now. Great job, or let's chat to find new ones!"
md = "### ✨ Here are a few things we could focus on:\n\n"
for i, entry in enumerate(pending_recs, 1):
rec = entry.get('recommendation', {})
- md += f"**{i}. {rec.get('title', 'Recommendation')}**\n"
- md += f" - {rec.get('description', 'No description.')}\n"
- md += f" - *Priority: {rec.get('priority', 'Medium')} | Type: {rec.get('action_type', 'General')}*\n---\n"
+ md += f"**{i}. {rec.get('title', 'Recommendation')}**\n"; md += f" - {rec.get('description', 'No description.')}\n"; md += f" - *Priority: {rec.get('priority', 'Medium')} | Type: {rec.get('action_type', 'General')}*\n---\n"
return md
- # --- Build Gradio Interface ---
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="sky", secondary_hue="blue", font=[gr.themes.GoogleFont("Poppins"), "Arial", "sans-serif"]), title="Aishura v3") as app:
+ # --- Build Gradio Interface (Structure identical to v3) ---
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="sky", secondary_hue="blue", font=[gr.themes.GoogleFont("Poppins"), "Arial", "sans-serif"]), title="Aishura v4 (OpenAI)") as app:
gr.Markdown("# Aishura - Your Empathetic AI Career Copilot 🚀")
- gr.Markdown("_Leveraging Google Gemini & Real-Time Data_")
-
- # Session state to store user ID (alternative to global variable)
- # user_id_state = gr.State(session_user_id) # Can use state if needed
+ gr.Markdown("_Powered by OpenAI GPT-4o & Real-Time Data_") # Updated subtitle
- # Welcome Screen
+ # Welcome Screen (Identical structure)
with gr.Group(visible=True) as welcome_group:
gr.Markdown("## Welcome! Let's personalize your journey.")
gr.Markdown("Tell me a bit about yourself so I can help you better.")
with gr.Row():
- with gr.Column():
- name_input = gr.Textbox(label="What's your first name?")
- location_input = gr.Textbox(label="Where are you located (City, Country)?", placeholder="e.g., London, UK")
- industry_input = gr.Textbox(label="What's your primary industry or field?", placeholder="e.g., Technology, Healthcare, Finance")
- with gr.Column():
- emotion_dropdown = gr.Dropdown(choices=EMOTIONS, label="How are you feeling right now?")
- goal_dropdown = gr.Dropdown(choices=GOAL_TYPES, label="What's your main career goal currently?") # Label updated
- exp_level_dropdown = gr.Dropdown(choices=["Student", "Entry-Level (0-2 yrs)", "Mid-Level (3-7 yrs)", "Senior-Level (8+ yrs)", "Executive"], label="What's your experience level?")
- work_style_dropdown = gr.Dropdown(choices=["On-site", "Hybrid", "Remote", "Any"], label="Preferred work style?", value="Any")
-
- welcome_button = gr.Button("✨ Start My Journey with Aishura ✨", variant="primary")
- welcome_output = gr.Markdown()
-
- # Main Interface (Hidden initially)
+ with gr.Column(): name_input = gr.Textbox(label="What's your first name?"); location_input = gr.Textbox(label="Where are you located (City, Country)?", placeholder="e.g., London, UK"); industry_input = gr.Textbox(label="What's your primary industry or field?", placeholder="e.g., Technology, Healthcare, Finance")
+ with gr.Column(): emotion_dropdown = gr.Dropdown(choices=EMOTIONS, label="How are you feeling right now?"); goal_dropdown = gr.Dropdown(choices=GOAL_TYPES, label="What's your main career goal currently?"); exp_level_dropdown = gr.Dropdown(choices=["Student", "Entry-Level (0-2 yrs)", "Mid-Level (3-7 yrs)", "Senior-Level (8+ yrs)", "Executive"], label="What's your experience level?"); work_style_dropdown = gr.Dropdown(choices=["On-site", "Hybrid", "Remote", "Any"], label="Preferred work style?", value="Any")
+ welcome_button = gr.Button("✨ Start My Journey with Aishura ✨", variant="primary"); welcome_output = gr.Markdown()
+
+ # Main Interface (Identical structure)
with gr.Group(visible=False) as main_interface:
with gr.Tabs():
- # --- Chat Tab ---
+ # Chat Tab
with gr.TabItem("💬 Chat with Aishura"):
with gr.Row():
with gr.Column(scale=3):
- # Using Gradio's ChatInterface structure for simplicity
- chatbot_display = gr.Chatbot(
- label="Aishura",
- height=600,
- show_copy_button=True,
- bubble_full_width=False, # Modern look
- avatar_images=(None, "https://img.icons8.com/external-those-icons-lineal-color-those-icons/96/external-AI-artificial-intelligence-those-icons-lineal-color-those-icons-9.png") # Example AI avatar
- )
- msg_textbox = gr.Textbox(
- show_label=False,
- placeholder="Type your message here... ask for help, share progress, or just vent!",
- container=False,
- scale=1 # Take full width below chatbot
- )
- # Submit button (optional, hitting Enter also works)
- # submit_btn = gr.Button("Send", variant="secondary", size="sm")
-
+ chatbot_display = gr.Chatbot(label="Aishura", height=600, show_copy_button=True, bubble_full_width=False, avatar_images=(None, "https://img.icons8.com/external-those-icons-lineal-color-those-icons/96/external-AI-artificial-intelligence-those-icons-lineal-color-those-icons-9.png"))
+ msg_textbox = gr.Textbox(show_label=False, placeholder="Type your message here...", container=False, scale=1)
with gr.Column(scale=1):
- gr.Markdown("### Recommendations")
- recommendation_output = gr.Markdown("Loading recommendations...")
- refresh_recs_button = gr.Button("🔄 Refresh Recs")
- gr.Markdown("---")
- gr.Markdown("### Quick Actions")
- # Add quick action buttons later? e.g., "Summarize my progress"
-
- # --- Analysis & Tools Tab ---
+ gr.Markdown("### Recommendations"); recommendation_output = gr.Markdown("Loading recommendations...")
+ refresh_recs_button = gr.Button("🔄 Refresh Recs"); gr.Markdown("---"); gr.Markdown("### Quick Actions")
+
+ # Analysis & Tools Tab
with gr.TabItem("🛠️ Analyze & Tools"):
with gr.Tabs():
with gr.TabItem("📄 Resume Hub"):
- gr.Markdown("### Analyze Your Resume")
- gr.Markdown("Upload your resume (TXT or PDF - text readable) for analysis and skill identification.")
- # Use File upload component
+ gr.Markdown("### Analyze Your Resume"); gr.Markdown("Upload your resume (TXT or PDF - text readable) for analysis and skill identification.")
resume_file_input = gr.File(label="Upload Resume (.txt, .pdf)", file_types=['.txt', '.pdf'])
- # Display path of saved resume
resume_path_display = gr.Textbox(label="Current Resume File", interactive=False)
analyze_resume_button = gr.Button("Analyze Uploaded Resume", variant="primary")
resume_analysis_output = gr.Markdown("Analysis will appear here...")
- gr.Markdown("---")
- gr.Markdown("### Generate Document Templates")
- doc_type_dropdown = gr.Dropdown(choices=["Resume", "Cover Letter", "LinkedIn Summary", "Networking Email"], label="Document Type")
- doc_field_input = gr.Textbox(label="Target Career Field (Optional)", placeholder="e.g., Software Engineering")
- doc_exp_dropdown = gr.Dropdown(choices=["Student", "Entry-Level", "Mid-Level", "Senior-Level"], label="Experience Level")
- generate_template_button = gr.Button("Generate Template")
- template_output_md = gr.Markdown("Template will appear here...")
-
-
+ gr.Markdown("---"); gr.Markdown("### Generate Document Templates")
+ doc_type_dropdown = gr.Dropdown(choices=["Resume", "Cover Letter", "LinkedIn Summary", "Networking Email"], label="Document Type"); doc_field_input = gr.Textbox(label="Target Career Field (Optional)", placeholder="e.g., Software Engineering"); doc_exp_dropdown = gr.Dropdown(choices=["Student", "Entry-Level", "Mid-Level", "Senior-Level"], label="Experience Level")
+ generate_template_button = gr.Button("Generate Template"); template_output_md = gr.Markdown("Template will appear here...")
with gr.TabItem("🎨 Portfolio Hub"):
gr.Markdown("### Analyze Your Portfolio")
- portfolio_url_input = gr.Textbox(label="Portfolio URL (Optional)", placeholder="https://yourportfolio.com")
- portfolio_desc_input = gr.Textbox(label="Describe your portfolio's content and purpose", lines=5, placeholder="e.g., Collection of web development projects using React and Node.js...")
- analyze_portfolio_button = gr.Button("Analyze Portfolio Info", variant="primary")
- portfolio_analysis_output = gr.Markdown("Analysis will appear here...")
-
+ portfolio_url_input = gr.Textbox(label="Portfolio URL (Optional)", placeholder="https://yourportfolio.com"); portfolio_desc_input = gr.Textbox(label="Describe your portfolio's content and purpose", lines=5, placeholder="e.g., Collection of web development projects...")
+ analyze_portfolio_button = gr.Button("Analyze Portfolio Info", variant="primary"); portfolio_analysis_output = gr.Markdown("Analysis will appear here...")
with gr.TabItem("📅 Routine Builder"):
- gr.Markdown("### Create a Personalized Routine")
- gr.Markdown("Feeling stuck? Let's build a manageable routine based on how you feel and your goals.")
- routine_emotion_dropdown = gr.Dropdown(choices=EMOTIONS, label="How are you feeling?")
- profile = get_user_profile(session_user_id) # Get goal from profile for default
- routine_goal_input = gr.Textbox(label="Main Goal for this Routine", value=profile.get('career_goal', ''))
- routine_time_slider = gr.Slider(15, 120, 45, step=15, label="Minutes you can dedicate per day")
- routine_days_slider = gr.Slider(3, 21, 7, step=1, label="Length of routine (days)")
- create_routine_button = gr.Button("Create My Routine", variant="primary")
- routine_output_md = gr.Markdown("Your personalized routine will appear here...")
-
-
- # --- Progress Tab ---
+ gr.Markdown("### Create a Personalized Routine"); gr.Markdown("Feeling stuck? Let's build a manageable routine.")
+ routine_emotion_dropdown = gr.Dropdown(choices=EMOTIONS, label="How are you feeling?"); profile = get_user_profile(session_user_id); routine_goal_input = gr.Textbox(label="Main Goal for this Routine", value=profile.get('career_goal', ''))
+ routine_time_slider = gr.Slider(15, 120, 45, step=15, label="Minutes you can dedicate per day"); routine_days_slider = gr.Slider(3, 21, 7, step=1, label="Length of routine (days)")
+ create_routine_button = gr.Button("Create My Routine", variant="primary"); routine_output_md = gr.Markdown("Your personalized routine will appear here...")
+
+ # Progress Tab
with gr.TabItem("📈 Track Your Journey"):
gr.Markdown("## Your Progress Dashboard")
with gr.Row():
with gr.Column(scale=1):
- gr.Markdown("### ✅ Log Completed Task")
- task_input = gr.Textbox(label="What did you accomplish?", placeholder="e.g., Updated resume, Applied for job X, Completed course module")
- complete_button = gr.Button("Log Task", variant="primary")
- task_output = gr.Markdown()
- gr.Markdown("---")
- gr.Markdown("### 😊 How are you feeling now?")
- new_emotion_dropdown = gr.Dropdown(choices=EMOTIONS, label="Select current emotion")
- emotion_button = gr.Button("Update Emotion")
- emotion_output = gr.Markdown()
+ gr.Markdown("### ✅ Log Completed Task"); task_input = gr.Textbox(label="What did you accomplish?", placeholder="e.g., Updated resume, Applied for job X...")
+ complete_button = gr.Button("Log Task", variant="primary"); task_output = gr.Markdown()
+ gr.Markdown("---"); gr.Markdown("### 😊 How are you feeling now?")
+ new_emotion_dropdown = gr.Dropdown(choices=EMOTIONS, label="Select current emotion"); emotion_button = gr.Button("Update Emotion"); emotion_output = gr.Markdown()
with gr.Column(scale=2):
- gr.Markdown("### Emotional Journey")
- emotion_chart_output = gr.Plot(label="Emotion Trend") # Init Plot
- gr.Markdown("### Active Routine Progress")
- routine_gauge_output = gr.Plot(label="Routine Completion") # Init Plot
-
+ gr.Markdown("### Emotional Journey"); emotion_chart_output = gr.Plot(label="Emotion Trend")
+ gr.Markdown("### Active Routine Progress"); routine_gauge_output = gr.Plot(label="Routine Completion")
with gr.Row():
- with gr.Column(scale=1):
- gr.Markdown("### Progress Points")
- progress_chart_output = gr.Plot(label="Progress Points Over Time") # Init Plot
- with gr.Column(scale=1):
- gr.Markdown("### Skills Assessment (from Resume)")
- skill_radar_chart_output = gr.Plot(label="Skills Radar") # Init Plot
-
-
- # --- Event Wiring ---
- welcome_button.click(
- fn=welcome,
- inputs=[name_input, location_input, emotion_dropdown, goal_dropdown, industry_input, exp_level_dropdown, work_style_dropdown],
- outputs=[chatbot_display, welcome_group, main_interface, emotion_chart_output, progress_chart_output, routine_gauge_output, skill_radar_chart_output, recommendation_output] # Added rec output
- )
-
- # Chat submission
- msg_textbox.submit(
- fn=chat_submit,
- inputs=[msg_textbox, chatbot_display],
- outputs=[chatbot_display, recommendation_output] # Chatbot updated progressively, recs at end
- ).then(lambda: gr.update(value=""), outputs=[msg_textbox]) # Clear textbox after submit
-
-
- refresh_recs_button.click(
- fn=lambda: display_recommendations(session_user_id),
- outputs=[recommendation_output]
- )
-
- # Tool Handlers
- analyze_resume_button.click(
- fn=analyze_resume_interface_handler,
- inputs=[resume_file_input], # Changed to file input
- outputs=[resume_analysis_output, skill_radar_chart_output, resume_path_display] # Added path display
- )
- analyze_portfolio_button.click(
- fn=analyze_portfolio_interface_handler,
- inputs=[portfolio_url_input, portfolio_desc_input],
- outputs=[portfolio_analysis_output]
- )
- generate_template_button.click(
- fn=generate_template_interface_handler,
- inputs=[doc_type_dropdown, doc_field_input, doc_exp_dropdown],
- outputs=[template_output_md]
- )
- create_routine_button.click(
- fn=create_routine_interface_handler,
- inputs=[routine_emotion_dropdown, routine_goal_input, routine_time_slider, routine_days_slider],
- outputs=[routine_output_md, routine_gauge_output] # Updates routine text and gauge
- )
-
- # Progress Handlers
- complete_button.click(
- fn=complete_task_handler,
- inputs=[task_input],
- outputs=[task_output, task_input, emotion_chart_output, progress_chart_output, routine_gauge_output] # Clear input, update charts
- )
- emotion_button.click(
- fn=update_emotion_handler,
- inputs=[new_emotion_dropdown],
- outputs=[emotion_output, emotion_chart_output] # Update status text and emotion chart
- )
+ with gr.Column(scale=1): gr.Markdown("### Progress Points"); progress_chart_output = gr.Plot(label="Progress Points Over Time")
+ with gr.Column(scale=1): gr.Markdown("### Skills Assessment (from Resume)"); skill_radar_chart_output = gr.Plot(label="Skills Radar")
+
+ # --- Event Wiring (Identical logic, calls updated functions) ---
+ welcome_button.click(fn=welcome, inputs=[name_input, location_input, emotion_dropdown, goal_dropdown, industry_input, exp_level_dropdown, work_style_dropdown], outputs=[chatbot_display, welcome_group, main_interface, emotion_chart_output, progress_chart_output, routine_gauge_output, skill_radar_chart_output, recommendation_output])
+ msg_textbox.submit(fn=chat_submit, inputs=[msg_textbox, chatbot_display], outputs=[chatbot_display, recommendation_output]).then(lambda: gr.update(value=""), outputs=[msg_textbox])
+ refresh_recs_button.click(fn=lambda: display_recommendations(session_user_id), outputs=[recommendation_output])
+ analyze_resume_button.click(fn=analyze_resume_interface_handler, inputs=[resume_file_input], outputs=[resume_analysis_output, skill_radar_chart_output, resume_path_display])
+ analyze_portfolio_button.click(fn=analyze_portfolio_interface_handler, inputs=[portfolio_url_input, portfolio_desc_input], outputs=[portfolio_analysis_output])
+ generate_template_button.click(fn=generate_template_interface_handler, inputs=[doc_type_dropdown, doc_field_input, doc_exp_dropdown], outputs=[template_output_md])
+ create_routine_button.click(fn=create_routine_interface_handler, inputs=[routine_emotion_dropdown, routine_goal_input, routine_time_slider, routine_days_slider], outputs=[routine_output_md, routine_gauge_output])
+ complete_button.click(fn=complete_task_handler, inputs=[task_input], outputs=[task_output, task_input, emotion_chart_output, progress_chart_output, routine_gauge_output])
+ emotion_button.click(fn=update_emotion_handler, inputs=[new_emotion_dropdown], outputs=[emotion_output, emotion_chart_output])
return app
# --- Main Execution ---
if __name__ == "__main__":
- print("\n--- Aishura v3 Configuration Check ---")
- if not GOOGLE_API_KEY:
- print("⚠️ WARNING: GOOGLE_API_KEY not found in environment variables. AI features DISABLED.")
- else:
- print("✅ GOOGLE_API_KEY found.")
- if not SERPER_API_KEY:
- print("⚠️ WARNING: SERPER_API_KEY not found. Live web search DISABLED.")
- else:
- print("✅ SERPER_API_KEY found.")
- if not gemini_model:
- print("❌ ERROR: Google Gemini model failed to initialize. AI features DISABLED.")
- else:
- print(f"✅ Google Gemini model '{MODEL_ID}' initialized.")
- print("-------------------------------------\n")
-
- logger.info("Starting Aishura v3 Gradio application...")
+ print("\n--- Aishura v4 (OpenAI) Configuration Check ---")
+ if not OPENAI_API_KEY: print("⚠️ WARNING: OPENAI_API_KEY not found. AI features DISABLED.")
+ else: print("✅ OPENAI_API_KEY found.")
+ if not SERPER_API_KEY: print("⚠️ WARNING: SERPER_API_KEY not found. Live web search DISABLED.")
+ else: print("✅ SERPER_API_KEY found.")
+ if not client: print("❌ ERROR: OpenAI client failed to initialize. AI features DISABLED.")
+ else: print(f"✅ OpenAI client initialized for model '{MODEL_ID}'.")
+ print("-------------------------------------------\n")
+
+ logger.info("Starting Aishura v4 (OpenAI) Gradio application...")
aishura_app = create_interface()
- # Share=True generates a public link (useful for demos)
- # Set debug=True for more verbose Gradio logs if needed
aishura_app.launch(share=False, debug=False)
- logger.info("Aishura Gradio application stopped.")
\ No newline at end of file
+ logger.info("Aishura Gradio application stopped.")