BigGoals / app.py
KatGaw's picture
adding files
7917295
import streamlit as st
from langchain_openai import ChatOpenAI
from tools import sentiment_analysis_util
import pandas as pd
from dotenv import load_dotenv
import os
from datetime import datetime
import json
from tavily import TavilyClient
from operator import itemgetter
import tiktoken
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain.schema.runnable import RunnablePassthrough
from langchain_openai.embeddings import OpenAIEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_core.prompts import ChatPromptTemplate
st.set_page_config(page_title="Personalized Success Recipe Generator", layout="wide")
st.image('el_pic.png')
load_dotenv()
OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
TAVILY_API_KEY = os.environ["TAVILY_API_KEY"]
# RAG Setup for Big Goals Book
@st.cache_resource
def setup_rag_system():
"""Setup RAG system for Big Goals book"""
# Define models
openai_chat_model = ChatOpenAI(model="gpt-4o", api_key=OPENAI_API_KEY)
embedding_model = OpenAIEmbeddings(model="text-embedding-3-small", api_key=OPENAI_API_KEY)
# RAG prompt template
RAG_PROMPT = """
CONTEXT:
{context}
QUERY:
{question}
Use the provided context from the Big Goals book to answer the user's question about goal setting, success strategies, and personal development.
Provide specific, actionable advice based on the book's principles. If the context doesn't contain relevant information, respond with "I don't have specific information about that in the Big Goals book, but I can help you with general goal-setting strategies."
"""
rag_prompt = ChatPromptTemplate.from_template(RAG_PROMPT)
# Check if vectorstore exists
if os.path.exists("./data/big_goals_vectorstore"):
vectorstore = FAISS.load_local(
"./data/big_goals_vectorstore",
embedding_model,
allow_dangerous_deserialization=True
)
retriever = vectorstore.as_retriever()
else:
# Create vectorstore from Big Goals book
with open('big_goals_step_by_step.md', 'r', encoding='utf-8') as f:
big_goals_content = f.read()
# Create document
from langchain_core.documents import Document
docs = [Document(page_content=big_goals_content, metadata={"source": "big_goals_book"})]
# Text splitter
def tiktoken_len(text):
tokens = tiktoken.encoding_for_model("gpt-4o").encode(text)
return len(tokens)
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=500,
chunk_overlap=50,
length_function=tiktoken_len,
)
split_chunks = text_splitter.split_documents(docs)
# Create vectorstore
os.makedirs("./data", exist_ok=True)
vectorstore = FAISS.from_documents(split_chunks, embedding_model)
vectorstore.save_local("./data/big_goals_vectorstore")
retriever = vectorstore.as_retriever()
# Create RAG chain with fewer retrieved documents for speed
retriever = vectorstore.as_retriever(search_kwargs={"k": 3}) # Only retrieve top 3 most relevant chunks
lcel_rag_chain = (
{"context": itemgetter("question") | retriever, "question": itemgetter("question")}
| RunnablePassthrough.assign(context=itemgetter("context"))
| {"response": rag_prompt | openai_chat_model, "context": itemgetter("context")}
)
return lcel_rag_chain, retriever, openai_chat_model
# Initialize RAG system
rag_chain, retriever, openai_chat_model = setup_rag_system()
# Initialize session state
if "user_profile" not in st.session_state:
st.session_state["user_profile"] = {}
if "company_info" not in st.session_state:
st.session_state["company_info"] = {}
if "success_recipe" not in st.session_state:
st.session_state["success_recipe"] = ""
if "messages" not in st.session_state:
st.session_state["messages"] = [{"role": "system", "content": "I'm here to help you with your personalized success strategy! Ask me anything about your goals, career, or the success recipe I've created for you."}]
# Left Sidebar - User Inputs
with st.sidebar:
st.title("📝 Your Profile")
name = st.text_input("Full Name", placeholder="Enter your full name")
gender = st.selectbox("Gender", ["Male", "Female", "Non-binary", "Prefer not to say"])
career_stage = st.selectbox("Career Stage", ["Young Adult (18-25)", "Mid-Career (26-45)", "Older/Retiree (45+)"])
job_position = st.text_input("Job Position", placeholder="e.g., Software Engineer, Marketing Manager")
country_origin = st.text_input("Country of Origin", placeholder="e.g., United States, Japan, Germany")
company = st.text_input("Company Name", placeholder="e.g., Google, Microsoft, Startup Inc.")
# Generate button
generate_button = st.button("🚀 Generate Success Recipe", type="primary", disabled=not (name and company and job_position and country_origin))
if generate_button:
# Store user profile when generate button is pressed
st.session_state["user_profile"] = {
"name": name,
"gender": gender,
"career_stage": career_stage,
"job_position": job_position,
"country_origin": country_origin,
"company": company
}
# Reset success recipe to trigger regeneration
st.session_state["success_recipe"] = ""
st.session_state["company_info"] = {}
st.rerun()
# Main Window
st.title("🎯 Personalized Success Recipe Generator")
# Auto-search company information when user profile exists and company info is needed
if st.session_state.get("user_profile") and not st.session_state.get("company_info"):
company = st.session_state["user_profile"]["company"]
with st.spinner(f"Searching for information about {company}..."):
try:
# Initialize Tavily client
tavily_client = TavilyClient(api_key=TAVILY_API_KEY)
# Search for company information
search_query = f"Latest news and information about {company} company"
response = tavily_client.search(query=search_query, search_depth="advanced", max_results=10)
# Extract and process company information
company_articles = []
for result in response.get('results', []):
article = {
'title': result.get('title', ''),
'content': result.get('content', ''),
'url': result.get('url', ''),
'published_date': result.get('published_date', ''),
'score': result.get('score', 0)
}
company_articles.append(article)
# Store company information
st.session_state["company_info"] = {
"company_name": company,
"articles": company_articles,
"search_date": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}
st.success(f"Found {len(company_articles)} articles about {company}!")
# Analyze company culture and success
with st.spinner("Analyzing company culture and success metrics..."):
try:
# Prepare company analysis prompt
company_analysis_prompt = f"""
Analyze the following company information and provide insights about:
1. **Company Success Level**: Is this company successful, struggling, or growing? What indicators show this?
2. **Company Culture Type**: Is this an entrepreneurial/startup culture, mission-driven organization, or bureaucratic/corporate environment?
3. **Leadership Structure**: What type of leadership and decision-making structure does this company have?
4. **Position Analysis**: For someone in the role of {st.session_state["user_profile"]["job_position"]}, what level of autonomy and influence would they typically have?
5. **Growth Opportunities**: What opportunities exist for career advancement and skill development?
6. **Challenges**: What challenges might someone face in this company and role?
Company Articles:
{json.dumps(company_articles, indent=2)}
Provide a comprehensive analysis that will help create a personalized success strategy.
"""
# Initialize ChatOpenAI for company analysis
analysis_client = ChatOpenAI(
model="gpt-4o",
temperature=0.3,
api_key=OPENAI_API_KEY
)
# Generate company analysis
analysis_messages = [
{"role": "system", "content": "You are a business analyst and organizational culture expert who analyzes companies to provide insights about their success, culture, and career opportunities."},
{"role": "user", "content": company_analysis_prompt}
]
analysis_response = analysis_client.invoke(analysis_messages)
company_analysis = analysis_response.content
# Store company analysis
st.session_state["company_info"]["analysis"] = company_analysis
st.info("Company analysis completed!")
except Exception as e:
st.error(f"Error analyzing company information: {str(e)}")
st.session_state["company_info"]["analysis"] = "Company analysis unavailable due to error."
except Exception as e:
st.error(f"Error searching for company information: {str(e)}")
# Auto-generate and save profile summary
if st.session_state.get("user_profile") and st.session_state.get("company_info"):
profile = st.session_state["user_profile"]
company_info = st.session_state["company_info"]
# Generate markdown content
markdown_content = f"""# Personal Success Profile
## Personal Information
- **Name:** {profile['name']}
- **Gender:** {profile['gender']}
- **Career Stage:** {profile['career_stage']}
- **Job Position:** {profile['job_position']}
- **Country of Origin:** {profile['country_origin']}
## Company Information
- **Company:** {company_info['company_name']}
- **Research Date:** {company_info['search_date']}
### Company Analysis
{company_info.get('analysis', 'Company analysis not available')}
### Recent Company News and Insights
"""
for i, article in enumerate(company_info['articles'][:10], 1):
markdown_content += f"""
#### Article {i}: {article['title']}
- **Content:** {article['content'][:300]}...
- **URL:** {article['url']}
- **Published:** {article['published_date']}
- **Relevance Score:** {article['score']:.2f}
---
"""
# Auto-save profile summary
profile_filename = f"profile_{profile['name'].replace(' ', '_')}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"
with open(profile_filename, 'w', encoding='utf-8') as f:
f.write(markdown_content)
st.info(f"Profile summary automatically saved as {profile_filename}")
# Download button for profile summary
st.download_button(
label="📥 Download Profile Summary",
data=markdown_content,
file_name=profile_filename,
mime="text/markdown"
)
# Auto-generate success recipe
if st.session_state.get("user_profile") and st.session_state.get("company_info") and not st.session_state.get("success_recipe"):
with st.spinner("Generating your personalized success recipe..."):
try:
# Prepare context for RAG
profile = st.session_state["user_profile"]
company_info = st.session_state["company_info"]
# Read the entire Big Goals book content
with open('big_goals_step_by_step.md', 'r', encoding='utf-8') as f:
big_goals_content = f.read()
# Initialize ChatOpenAI for final recipe generation
client = ChatOpenAI(
model="gpt-4o",
temperature=0.7,
api_key=OPENAI_API_KEY
)
# Create prompt for success recipe generation
prompt = f"""
Based on the user profile, company information, company analysis, and the Big Goals book content provided, create a detailed, actionable success recipe for {profile['name']}.
User Profile:
- Name: {profile['name']}
- Gender: {profile['gender']}
- Career Stage: {profile['career_stage']}
- Job Position: {profile['job_position']}
- Country of Origin: {profile['country_origin']}
- Company: {profile['company']}
Company Analysis:
{company_info.get('analysis', 'Company analysis not available')}
Big Goals Book Content:
{big_goals_content}
The recipe should be highly specific and practical, focusing on HOW to succeed, not just what to do. Include:
1. **Cultural Integration**: How to leverage their {profile['country_origin']} heritage as a professional advantage
2. **Career Stage Strategy**: Specific tactics for their {profile['career_stage']} phase
3. **Job-Specific Actions**: Concrete steps for their role as {profile['job_position']}
4. **Company Alignment**: How to succeed within their specific company culture (use the company analysis insights)
5. **Position Autonomy**: Leverage their level of autonomy and influence in their role
6. **Big Goals Framework**: Direct application of the book's principles with specific examples
Format as a comprehensive success recipe with:
- **Cultural Reflection**: How their background shapes their approach to work
- **Vision Statement**: A clear, inspiring vision that incorporates their values
- **Action Steps**: Specific, measurable actions they can take immediately
- **Big Goals References**: Direct quotes and chapter references from the book
- **Cultural Considerations**: How to navigate workplace dynamics with their background
- **Company-Specific Strategies**: Tactics tailored to their organization's culture and success level
- **Position-Specific Tactics**: Actions based on their role's autonomy and influence level
- **Timeline**: When to implement each step
- **Success Metrics**: How to measure progress
Make it deeply personal, culturally aware, and immediately actionable. Focus on the "how" and "why" behind each recommendation. Use the company analysis to inform your recommendations about the work environment and opportunities.
"""
# Generate the success recipe
messages = [
{"role": "system", "content": "You are an expert career coach and success strategist who creates highly detailed, actionable success recipes. Focus on specific HOW-TO steps, cultural integration strategies, and practical implementation guidance. Always include concrete examples, timelines, and measurable outcomes. Reference specific chapters and quotes from the Big Goals book to support recommendations."},
{"role": "user", "content": prompt}
]
response = client.invoke(messages)
success_recipe = response.content
# Store the success recipe
st.session_state["success_recipe"] = success_recipe
# Auto-save the success recipe
recipe_filename = f"success_recipe_{profile['name'].replace(' ', '_')}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"
with open(recipe_filename, 'w', encoding='utf-8') as f:
f.write(f"# Success Recipe for {profile['name']}\n\n{success_recipe}")
st.success(f"Success recipe automatically saved as {recipe_filename}!")
except Exception as e:
st.error(f"Error generating success recipe: {str(e)}")
# Display success recipe in main window
if st.session_state.get("success_recipe"):
st.subheader("🎯 Your Personalized Success Recipe")
st.markdown(st.session_state["success_recipe"])
# Download button for success recipe
st.download_button(
label="📥 Download Success Recipe",
data=st.session_state["success_recipe"],
file_name=f"success_recipe_{st.session_state['user_profile']['name'].replace(' ', '_')}.md",
mime="text/markdown"
)
# Chat functionality in main window
st.subheader("💬 Chat with Your Success Coach")
# Display chat messages
for msg in st.session_state.messages:
st.chat_message(msg["role"]).write(msg["content"])
# Chat input
if prompt := st.chat_input("Ask me anything about your success strategy..."):
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message in chat message container
with st.chat_message("user"):
st.markdown(prompt)
# Generate response using RAG
with st.chat_message("assistant"):
with st.spinner("Thinking..."):
# Create context for the chat
context = ""
if st.session_state.get("user_profile"):
profile = st.session_state["user_profile"]
context += f"User Profile: {profile['name']}, {profile['career_stage']}, {profile['job_position']} at {profile['company']}, from {profile['country_origin']}. "
if st.session_state.get("success_recipe"):
context += f"Success Recipe: {st.session_state['success_recipe'][:1000]}... "
# Read the entire Big Goals book content
with open('big_goals_step_by_step.md', 'r', encoding='utf-8') as f:
big_goals_content = f.read()
# Create enhanced prompt with full book content
enhanced_prompt = f"""
User Question: {prompt}
User Context: {context}
Please provide a helpful response that combines the user's specific situation with relevant advice from the Big Goals book. Use the book content below to inform your response.
Big Goals Book Content:
{big_goals_content}
"""
# Generate response using ChatOpenAI (faster without RAG)
client = ChatOpenAI(
model="gpt-4o-mini", # Faster model
temperature=0.7,
api_key=OPENAI_API_KEY,
max_tokens=500 # Limit response length for speed
)
chat_messages = [
{"role": "system", "content": "You are a helpful success coach who provides personalized advice based on the Big Goals book principles and the user's specific situation. Keep responses concise and actionable. Use the provided Big Goals book content to inform your advice."},
{"role": "user", "content": enhanced_prompt}
]
response = client.invoke(chat_messages)
response_content = response.content
st.write(response_content)
st.session_state.messages.append({"role": "assistant", "content": response_content})