Mentor_BoT / src /streamlit_app.py
saikumar27's picture
Update src/streamlit_app.py
00476ff verified
Raw History Blame Contribute Delete
9.74 kB
import os
import io
import streamlit as st
from langchain.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate
from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
from dotenv import load_dotenv
# Load environment variables with error handling
try:
load_dotenv()
HF_TOKEN = (
os.getenv("HF_TOKEN") or
os.getenv("HUGGINGFACEHUB_API_TOKEN") or
st.secrets.get("HF_TOKEN", None)
)
if not HF_TOKEN:
raise ValueError("HuggingFace token not found")
os.environ['HUGGINGFACEHUB_API_TOKEN'] = HF_TOKEN
os.environ['HF_TOKEN'] = HF_TOKEN
except Exception as e:
st.error(f"""
❌ Failed to load HuggingFace token:
{str(e)}
Please ensure you have:
1. A .env file with HF_TOKEN=your_token_here
2. Or set it as environment variable
3. Or configured Streamlit secrets if deployed
""")
st.stop()
# App configuration
st.set_page_config(
page_title="πŸ‘¨β€πŸ« Multi-Mentor Chat",
page_icon="🧠",
layout="centered",
initial_sidebar_state="expanded"
)
# Custom CSS
st.markdown("""
<style>
.stRadio > div {flex-direction: row;}
.stRadio label {margin-right: 15px;}
.mentor-card {border-radius: 10px; padding: 15px; margin-bottom: 10px;}
.python-card {background-color: #3572A5; color: white;}
.data-card {background-color: #6C8EBF;}
.stats-card {background-color: #6A1B9A; color: white;}
.ml-card {background-color: #DD6B20; color: white;}
.dl-card {background-color: #4B8BBE; color: white;}
.sql-card {background-color: #F68212; color: white;}
.response-box {border-left: 4px solid #6A1B9A; padding: 10px; background-color: #f8f9fa;}
.chat-message {padding: 10px; border-radius: 5px; margin-bottom: 10px;}
.user-message {background-color: #e3f2fd;}
.assistant-message {background-color: #f5f5f5;}
</style>
""", unsafe_allow_html=True)
# Header
st.markdown("<h1 style='text-align: center; color: #4B8BBE;'>🧠 Multi-Topic Mentor</h1>", unsafe_allow_html=True)
st.markdown("<p style='text-align: center;'>Get expert guidance tailored to your learning topic and experience level.</p>", unsafe_allow_html=True)
# Sidebar with info
with st.sidebar:
st.markdown("## ℹ️ About")
st.markdown("""
This app connects you with AI mentors specialized in different technical fields.
Select your topic and experience level to get tailored guidance.
""")
st.markdown("## βš™οΈ Settings")
temperature = st.slider("Response Creativity", 0.1, 1.0, 0.5, 0.1)
max_tokens = st.slider("Response Length", 50, 300, 150, 50)
# Display token status (for debugging)
if st.checkbox("Show API status"):
st.write(f"Token loaded: {'βœ…' if HF_TOKEN else '❌'}")
if HF_TOKEN:
st.code(f"Token starts with: {HF_TOKEN[:5]}...")
# Mentor selection
st.markdown("### πŸ” <b>Select Your Mentor Specialization:</b>", unsafe_allow_html=True)
mentor_data = {
"python": {
"label": "🐍 Python",
"color": "python-card",
"description": "Python programming, syntax, and best practices",
"model": "meta-llama/Llama-3.1-8B-Instruct",
"provider": "nebius"
},
"data_analysis": {
"label": "πŸ“Š Data Analysis",
"color": "data-card",
"description": "Data cleaning, visualization, and exploration",
"model": "meta-llama/Llama-3.3-70B-Instruct",
"provider": "nebius"
},
"stats": {
"label": "πŸ“ˆ Statistics",
"color": "stats-card",
"description": "Statistical concepts and analysis techniques",
"model": "meta-llama/Llama-3.2-1B-Instruct",
"provider": "nebius"
},
"machine_learning": {
"label": "πŸ€– Machine Learning",
"color": "ml-card",
"description": "ML algorithms, model training, and evaluation",
"model": "deepseek-ai/DeepSeek-R1",
"provider": "nebius"
},
"deep_learning": {
"label": "🧠 Deep Learning",
"color": "dl-card",
"description": "Neural networks, TensorFlow, PyTorch",
"model": "deepseek-ai/DeepSeek-R1",
"provider": "nebius"
},
"sql_powerbi": {
"label": "πŸ’Ύ SQL & Power BI",
"color": "sql-card",
"description": "Database queries and business intelligence",
"model": "meta-llama/Meta-Llama-3-70B-Instruct",
"provider": "hyperbolic"
}
}
# Display mentor cards
cols = st.columns(3)
for i, (mentor_key, mentor_info) in enumerate(mentor_data.items()):
with cols[i % 3]:
st.markdown(
f"""<div class="mentor-card {mentor_info['color']}">
<h4>{mentor_info['label']}</h4>
<p>{mentor_info['description']}</p>
</div>""",
unsafe_allow_html=True
)
# Mentor selection dropdown
mentor_type = st.selectbox(
"πŸŽ“ Choose a mentor:",
[""] + list(mentor_data.keys()),
format_func=lambda x: mentor_data.get(x, {}).get("label", "Select a mentor"),
key="mentor_select"
)
if mentor_type:
st.markdown(f"<h3 style='color:#6A1B9A;'>🧠 {mentor_data[mentor_type]['label']} Mentor</h3>", unsafe_allow_html=True)
# Experience level
st.markdown("### 🎯 <b>Select Your Experience Level</b>", unsafe_allow_html=True)
experience_options = {
0: "Beginner (0 years)",
1: "Novice (1 year)",
2: "Intermediate (2 years)",
3: "Intermediate (3 years)",
5: "Advanced (5 years)",
10: "Expert (10+ years)"
}
selected_experience = st.radio(
"experience_level",
options=list(experience_options.keys()),
format_func=lambda x: experience_options[x],
horizontal=True,
index=2 # Default to intermediate
)
# User question
user_input = st.text_area(
"πŸ’¬ Ask your question:",
placeholder=f"Ask your {mentor_type.replace('_', ' ')} question here...",
height=100,
key="user_input"
)
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = []
# Display chat messages
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
@st.cache_resource(show_spinner=False)
def get_chat_model(repo_id, provider, _temperature, _max_tokens):
model = HuggingFaceEndpoint(
repo_id=repo_id,
provider=provider,
temperature=_temperature,
max_new_tokens=_max_tokens,
task="conversational"
)
return ChatHuggingFace(
llm=model,
repo_id=repo_id,
provider=provider,
temperature=_temperature,
max_new_tokens=_max_tokens,
task="conversational"
)
# Action buttons
col1, col2, col3 = st.columns([1, 1, 2])
if col1.button("πŸš€ Ask Mentor") and user_input:
try:
# Add user message to chat history
st.session_state.messages.append({"role": "user", "content": user_input})
# Display user message immediately
with st.chat_message("user"):
st.markdown(user_input)
# Get the chat model
chat_model = get_chat_model(
mentor_data[mentor_type]["model"],
mentor_data[mentor_type]["provider"],
temperature,
max_tokens
)
# Create prompt
prompt = ChatPromptTemplate.from_messages([
SystemMessagePromptTemplate.from_template(
f"""You are a helpful and experienced {mentor_type.replace('_', ' ')} mentor.
The learner has {selected_experience} years of experience in this field.
Provide a detailed but clear explanation appropriate for their level.
Format your response with proper markdown for code, lists, etc."""
),
HumanMessagePromptTemplate.from_template("{question}")
])
formatted_prompt = prompt.format_messages(question=user_input)
with st.spinner(f"{mentor_data[mentor_type]['label']} Mentor is thinking..."):
response = chat_model.invoke(formatted_prompt)
# Add assistant response to chat history
st.session_state.messages.append({"role": "assistant", "content": response.content})
# Display assistant response
with st.chat_message("assistant"):
st.markdown(response.content)
except Exception as e:
st.error(f"An error occurred while getting the mentor's response: {str(e)}")
st.session_state.messages.append({"role": "assistant", "content": f"Sorry, I encountered an error: {str(e)}"})
if col2.button("🧹 Clear Chat"):
st.session_state.messages = []
st.rerun()
# Download chat history
if st.session_state.messages:
chat_text = "\n\n".join(
f"{'πŸ‘€ You' if msg['role'] == 'user' else '🧠 Mentor'}: {msg['content']}"
for msg in st.session_state.messages
)
chat_buffer = io.StringIO(chat_text)
st.download_button(
label="πŸ“₯ Download Chat History",
data=chat_buffer.getvalue(),
file_name=f"{mentor_type}_mentor_chat.txt",
mime="text/plain",
use_container_width=True
)