File size: 10,778 Bytes
ad6d2ba
 
 
89e3680
ad6d2ba
 
 
89e3680
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad6d2ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89e3680
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad6d2ba
89e3680
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad6d2ba
 
 
 
 
 
 
89e3680
 
ad6d2ba
 
 
 
 
 
 
 
f9b1046
 
 
 
 
 
ad6d2ba
 
 
 
 
 
 
 
 
 
 
f9b1046
ad6d2ba
 
f9b1046
 
ad6d2ba
 
 
 
 
 
 
 
 
 
 
 
 
89e3680
ad6d2ba
 
 
89e3680
 
 
 
 
 
 
 
ad6d2ba
 
 
89e3680
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad6d2ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
############################################################################################################
# Importing Libraries

import os
import streamlit as st
import hmac
import config

# Must be first Streamlit command so sidebar state applies from first load
st.set_page_config(
    layout="wide",
    page_title="Modular Chatbot",
    page_icon=":lightbulb:",
    initial_sidebar_state="collapsed",
)

try:
    import litellm
except ImportError:
    st.error("Required packages not installed. Run: pip install litellm streamlit")
    st.stop()

try:
    from openai import OpenAI
except ImportError:
    OpenAI = None  # optional for Anthropic-only; required for OpenAI/web search

############################################################################################################
# Password protection

def check_password():
    """Returns `True` if the user had the correct password."""

    def password_entered():
        """Checks whether a password entered by the user is correct."""
        if hmac.compare_digest(st.session_state["password"], st.secrets["password"]):
            st.session_state["password_correct"] = True
            del st.session_state["password"]  # Don't store the password.
        else:
            st.session_state["password_correct"] = False

    # Return True if the password is validated.
    if st.session_state.get("password_correct", False):
        return True

    # Show input for password.
    st.text_input(
        "Password", type="password", on_change=password_entered, key="password"
    )
    if "password_correct" in st.session_state:
        st.error("๐Ÿ˜• Password incorrect")
    return False

if not check_password():
    st.stop()  # Do not continue if check_password is not True.

############################################################################################################
# Streamlit app layout
# st.title(config.app_title)
# with st.expander("INSTRUCTIONS FOR STUDENTS:"):
#     st.markdown(config.instructions)

############################################################################################################
# API key setup (LiteLLM reads from environment)

def get_openai_api_key():
    """Return OpenAI API key from Streamlit secrets (for LiteLLM)."""
    return st.secrets.get("OPENAI_API_KEY") or st.secrets.get("openai_api_key")

def get_anthropic_api_key():
    """Return Anthropic API key from Streamlit secrets (for LiteLLM)."""
    return st.secrets.get("ANTHROPIC_API_KEY") or st.secrets.get("anthropic_api_key")

def setup_api_keys():
    """Set API keys in environment for any code that reads env."""
    key = get_openai_api_key()
    if key:
        os.environ["OPENAI_API_KEY"] = key
    key = get_anthropic_api_key()
    if key:
        os.environ["ANTHROPIC_API_KEY"] = key

setup_api_keys()

# OpenAI client for Responses API (supports web_search; Chat Completions does not)
_openai_client = None

def get_openai_client():
    """Return OpenAI client for Responses API (used when web search is enabled)."""
    global _openai_client
    if _openai_client is None:
        key = get_openai_api_key()
        if not key:
            return None
        _openai_client = OpenAI(api_key=key)
    return _openai_client

############################################################################################################
# Model restriction (Anthropic or GPT only)

def is_openai_model(model_str):
    n = (model_str or "").strip().lower()
    return n.startswith("gpt-") or n.startswith("openai/")

def is_anthropic_model(model_str):
    n = (model_str or "").strip().lower()
    return n.startswith("claude-") or n.startswith("anthropic/")

def allowed_model(model_str):
    return is_openai_model(model_str) or is_anthropic_model(model_str)

if not allowed_model(config.ai_model):
    st.error("Invalid model: only OpenAI (GPT) or Anthropic (Claude) models are allowed. Edit ai_model in config.py (e.g. gpt-4.1, claude-sonnet-4-5).")
    st.stop()

############################################################################################################

# Define a basic initial context at the beginning of your script
initial_context = {
    "role": "system",
    "content": config.prompt
}

# LiteLLM: drop unsupported params per provider
litellm.drop_params = True

# Initialize the session state variables if they don't exist
if "openai_model" not in st.session_state:
    st.session_state["openai_model"] = config.ai_model

# Corrected initialization of display_messages:
if "display_messages" not in st.session_state:
    st.session_state["display_messages"] = [initial_context] 
    
# Initialize chat with opening message if it doesn't exist
if "chat_initialized" not in st.session_state:
    st.session_state["chat_initialized"] = True
    # Add the opening message to the display
    st.session_state["display_messages"].append({"role": "assistant", "content": config.opening_message})

# Get user input
prompt = st.chat_input("Type your message here...")

# Input for new messages
if prompt:
    # Ensure initial context is in the session state and then append user messages
    if not st.session_state["display_messages"]:
        st.session_state["display_messages"] = [initial_context]
    st.session_state["display_messages"].append({"role": "user", "content": prompt})

# Function to reset all chat history
def reset_chat_history():
    st.session_state["display_messages"] = [initial_context]
    # Re-add opening message when chat is reset
    st.session_state["display_messages"].append({"role": "assistant", "content": config.opening_message})
    st.rerun()

# Main chat container
with st.container(border=False):
    # Display chat history in reverse order including new messages
    for message in st.session_state["display_messages"][1:]:
        if message["role"] == "user":
            with st.chat_message("user"):
                st.markdown(message["content"])
        else:
            with st.chat_message("assistant"):
                st.markdown(message["content"])

    # Generate assistant's response and add it to the messages
    if prompt:
        with st.chat_message("assistant"):
            try:
                model = st.session_state["openai_model"]
                messages = [
                    {"role": m["role"], "content": m["content"]}
                    for m in st.session_state["display_messages"]
                ]
                use_openai_responses_api = (
                    is_openai_model(model)
                    and getattr(config, "web_search_enabled", False)
                )
                full_response = ""
                message_placeholder = st.empty()

                if use_openai_responses_api:
                    # OpenAI Responses API supports web_search; Chat Completions does not
                    if OpenAI is None:
                        st.error("Web search with OpenAI requires the openai package. Run: pip install openai")
                        st.stop()
                    client = get_openai_client()
                    if not client:
                        st.error("OpenAI API key not set. Add openai_api_key or OPENAI_API_KEY to .streamlit/secrets.toml")
                        st.stop()
                    # Responses API uses "input" not "messages"; model name without prefix
                    req_model = model.replace("openai/", "", 1) if model.startswith("openai/") else model
                    request_data = {
                        "model": req_model,
                        "input": messages,
                        "stream": True,
                        "temperature": config.temperature,
                        "max_output_tokens": config.max_tokens,
                    }
                    request_data["tools"] = [{"type": "web_search", "search_context_size": "low"}]
                    request_data["tool_choice"] = "auto"
                    stream = client.responses.create(**request_data)
                    for event in stream:
                        if getattr(event, "type", None) == "response.output_text.delta":
                            delta = getattr(event, "delta", "") or ""
                            full_response += delta
                            message_placeholder.markdown(full_response + "โ–Œ")
                    message_placeholder.markdown(full_response)
                else:
                    # LiteLLM Chat Completions (no web_search tools)
                    request_kwargs = {
                        "model": model,
                        "messages": messages,
                        "stream": True,
                        "temperature": config.temperature,
                        "max_tokens": config.max_tokens,
                        "frequency_penalty": config.frequency_penalty,
                        "presence_penalty": config.presence_penalty,
                    }
                    if is_openai_model(model):
                        api_key = get_openai_api_key()
                        if not api_key:
                            st.error("OpenAI API key not set. Add openai_api_key or OPENAI_API_KEY to .streamlit/secrets.toml")
                            st.stop()
                        request_kwargs["api_key"] = api_key
                    else:
                        api_key = get_anthropic_api_key()
                        if not api_key:
                            st.error("Anthropic API key not set. Add anthropic_api_key or ANTHROPIC_API_KEY to .streamlit/secrets.toml")
                            st.stop()
                        request_kwargs["api_key"] = api_key
                    stream = litellm.completion(**request_kwargs)
                    for chunk in stream:
                        if chunk.choices and chunk.choices[0].delta and getattr(chunk.choices[0].delta, "content", None) is not None:
                            full_response += chunk.choices[0].delta.content
                            message_placeholder.markdown(full_response + "โ–Œ")
                    message_placeholder.markdown(full_response)

                st.session_state["display_messages"].append(
                    {"role": "assistant", "content": full_response}
                )
            except Exception as e:
                st.error(f"An error occurred: {str(e)}")

# Create a sidebar
with st.sidebar:
    st.markdown(config.warning_message, unsafe_allow_html=True)

    # Add Clear Chat History button to sidebar
    if st.button("Clear Chat History"):
        reset_chat_history()
    
    # Add license link with markdown
    st.markdown("---")  # Separator line
    st.markdown("""
        <small>Licensed under [GNU GPL v3.0](https://www.gnu.org/licenses/gpl-3.0.en.html)</small>
        """, unsafe_allow_html=True)