import streamlit as st from langchain_google_genai import ChatGoogleGenerativeAI from langchain.chains import ConversationChain from langchain.memory import ConversationBufferMemory from langchain.prompts import PromptTemplate import os from dotenv import load_dotenv # βœ… Load API Key from Environment Variables or User Input load_dotenv() api_key = os.getenv("GOOGLE_API_KEY") # If .env file is missing or API key is not found, ask the user to input it if not api_key: st.warning("πŸ”‘ Google API key not found in `.env` file. Please enter your API key below:") api_key = st.text_input("Enter your Google API Key:", type="password") if not api_key: st.error("🚨 API key is required to proceed.") st.stop() else: os.environ["GOOGLE_API_KEY"] = api_key # βœ… Configure Gemini Model model = ChatGoogleGenerativeAI(model="gemini-1.5-pro", api_key=api_key) # βœ… Add Memory to Make It Context-Aware memory = ConversationBufferMemory(input_key="input") # βœ… Define Prompt for Data Science Focus prompt_template = """ You are an AI Python Mentor. - Your task is to help the user with Python-related queries ONLY. - If the question is unrelated to python, politely refuse to answer. - Provide clear, detailed, and accurate explanations with examples where applicable. - Avoid overly technical language unless necessary. Chat History: {history} User: {input} AI: """ # βœ… Create Conversation Chain conversation = ConversationChain( llm=model, memory=memory, prompt=PromptTemplate(template=prompt_template, input_variables=["history", "input"]) ) # βœ… Streamlit UI Config st.set_page_config( page_title="AI Python Mentor", layout="wide", initial_sidebar_state="collapsed" ) # βœ… Custom CSS for Clean UI and Reduced Spacing st.markdown( """ """, unsafe_allow_html=True ) # βœ… Title st.title("🧠 Python Mentor") # Initialize session state for messages if "messages" not in st.session_state: st.session_state.messages = [] # βœ… Display Previous Messages for message in st.session_state.messages: with st.chat_message(message["role"]): if message["role"] == "assistant": # Use Markdown for better readability and formatting st.markdown(f"```python\n{message['content']}\n```") else: st.markdown(message["content"]) # βœ… User Input user_input = st.chat_input("Ask a Python question (e.g., What is list ?)...") if user_input: # Display User Message st.session_state.messages.append({"role": "user", "content": user_input}) with st.chat_message("user"): st.markdown(user_input) # Generate AI Response with st.spinner("Thinking..."): try: response = conversation.predict(input=user_input) except Exception as e: response = f"An error occurred: {str(e)}" with st.expander("See error details"): st.code(str(e)) # Display AI Response with st.chat_message("assistant"): st.markdown(f"```python\n{response}\n```") # Save AI Message to History st.session_state.messages.append({"role": "assistant", "content": response}) # βœ… Reset Chat Button if st.button("Reset Chat"): if st.session_state.messages: # Only show confirmation if there’s a conversation history if st.confirm("Are you sure you want to reset the chat?"): st.session_state.messages = [] memory.clear() st.rerun()