File size: 3,993 Bytes
ee86ee0
fbf97c0
 
ee86ee0
fbf97c0
ee86ee0
fbf97c0
ee86ee0
f4dbfb2
586b270
fbf97c0
ee86ee0
f4dbfb2
fbf97c0
32297e4
f4dbfb2
 
 
 
 
 
ee86ee0
fbf97c0
 
ee86ee0
09a77a7
9720f44
ee86ee0
fbf97c0
 
ff48373
 
 
fbf97c0
 
ee86ee0
9720f44
 
 
fbf97c0
 
ee86ee0
 
09a77a7
fbf97c0
 
ee86ee0
9720f44
ee86ee0
 
32297e4
 
ff48373
32297e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff48373
ee86ee0
09a77a7
ee86ee0
 
 
32297e4
ee86ee0
 
586b270
32297e4
 
586b270
 
ee86ee0
32297e4
ff48373
ee86ee0
 
32297e4
ee86ee0
fbf97c0
 
ee86ee0
32297e4
09a77a7
 
 
 
 
586b270
 
ee86ee0
32297e4
ee86ee0
586b270
ee86ee0
32297e4
ee86ee0
 
fbf97c0
 
32297e4
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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(
    """
    <style>
        .stApp {
            padding-top: 0.5rem;
            padding-bottom: 1rem;
        }
        .stTitle {
            margin-bottom: -0.5rem;
            font-size: 2rem;
            font-weight: 600;
            color: #4CAF50;
        }
        .stChatInputContainer {
            margin-top: -1.0rem;
        }
        .stMarkdown {
            font-size: 1rem;
            line-height: 1.6;
        }
        .css-1kyxreq {
            display: none;
        }
    </style>
    """,
    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()