File size: 4,010 Bytes
5bd0c5e
 
 
1fa6e70
5bd0c5e
 
fa6de7f
9209303
 
 
1fa6e70
 
 
 
 
 
 
 
9209303
1fa6e70
 
 
 
5bd0c5e
 
 
308b460
fa6de7f
1a54c01
1fa6e70
9209303
 
fa6de7f
5bd0c5e
3fa0141
9209303
1a54c01
1fa6e70
5bd0c5e
fa6de7f
308b460
1a54c01
308b460
 
 
 
 
 
 
 
 
fa6de7f
63b23af
1a54c01
c969c2f
308b460
 
c969c2f
9209303
c969c2f
fa6de7f
 
308b460
 
 
 
 
 
 
 
fa6de7f
1fa6e70
5bd0c5e
3fa0141
9209303
5bd0c5e
1fa6e70
9209303
5bd0c5e
 
3fa0141
fa6de7f
9209303
 
5bd0c5e
1fa6e70
5bd0c5e
 
 
 
1fa6e70
5bd0c5e
 
fa6de7f
1fa6e70
5bd0c5e
 
 
9209303
 
 
5bd0c5e
 
 
9209303
5bd0c5e
 
 
 
 
fa6de7f
1fa6e70
5bd0c5e
 
 
 
 
 
 
 
 
 
 
1fa6e70
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
import streamlit as st
from google import genai

# ---------------- Page Config ----------------
st.set_page_config(page_title="Gemini API Tester", page_icon="⚑")
st.title("⚑ Gemini API Tester")

# ---------------- Session State Defaults ----------------
defaults = {
    "api_key_input": "",
    "api_key": None,
    "api_validated": False,
    "client": None,
    "models": [],
    "selected_model": None,
    "messages": []
}

for k, v in defaults.items():
    if k not in st.session_state:
        st.session_state[k] = v

# ---------------- Sidebar ----------------
with st.sidebar:
    st.header("πŸ” API Configuration")

    # ---------- BEFORE VALIDATION ----------
    if not st.session_state.api_validated:
        api_key_input = st.text_input(
            "Enter Google API Key",
            type="password",
            key="api_key_input"
        )

        # Validate API Key immediately when button is clicked
        if st.button("Validate API Key"):
            if not api_key_input:
                st.warning("Please enter an API key.")
            else:
                try:
                    # Initialize client
                    client = genai.Client(api_key=api_key_input)

                    # Attempt to list models (authentication test)
                    try:
                        models = [
                            m.name for m in client.models.list()
                            if "gemini" in m.name.lower()
                        ]
                    except Exception:
                        models = []

                    # Persist validated state
                    st.session_state.api_key = api_key_input
                    st.session_state.client = client
                    st.session_state.models = models or ["gemini-2.5-flash"]
                    st.session_state.selected_model = st.session_state.models[0]
                    st.session_state.api_validated = True

                    st.success("βœ… API key validated successfully")

                except Exception as e:
                    error_msg = str(e).lower()
                    if "401" in error_msg or "403" in error_msg or "unauthorized" in error_msg:
                        st.error("❌ Invalid API key")
                    else:
                        st.warning("⚠️ API key accepted, but model access may be restricted")
                        st.caption(str(e))

    # ---------- AFTER VALIDATION ----------
    else:
        st.success("πŸ”’ API Key validated (hidden)")

        # Model selector is now immediately visible
        st.selectbox(
            "Available Models",
            st.session_state.models,
            key="selected_model"
        )

        # Allow changing API key
        if st.button("πŸ”„ Change API Key"):
            for k in defaults:
                st.session_state[k] = defaults[k]

# ---------------- Chat History ----------------
for msg in st.session_state.messages:
    with st.chat_message(msg["role"]):
        st.markdown(msg["content"])

# ---------------- Chat Input ----------------
if prompt := st.chat_input("Ask something..."):

    if not st.session_state.api_validated:
        st.error("Please validate an API key first.")
        st.stop()

    # User message
    st.session_state.messages.append(
        {"role": "user", "content": prompt}
    )
    with st.chat_message("user"):
        st.markdown(prompt)

    # Assistant response
    with st.chat_message("assistant"):
        placeholder = st.empty()
        placeholder.markdown("Thinking...")

        try:
            response = st.session_state.client.models.generate_content(
                model=st.session_state.selected_model,
                contents=prompt
            )

            reply = response.text
            placeholder.markdown(reply)

            st.session_state.messages.append(
                {"role": "assistant", "content": reply}
            )

        except Exception as e:
            placeholder.error(f"Error: {e}")