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(""" """, unsafe_allow_html=True) # Header st.markdown("

๐Ÿง  Multi-Topic Mentor

", unsafe_allow_html=True) st.markdown("

Get expert guidance tailored to your learning topic and experience level.

", 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("### ๐Ÿ” Select Your Mentor Specialization:", 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"""

{mentor_info['label']}

{mentor_info['description']}

""", 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"

๐Ÿง  {mentor_data[mentor_type]['label']} Mentor

", unsafe_allow_html=True) # Experience level st.markdown("### ๐ŸŽฏ Select Your Experience Level", 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 )