Utiric commited on
Commit
f8d223b
·
verified ·
1 Parent(s): 49e8747

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +206 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,208 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import uuid
3
+ import os
4
+ from dotenv import load_dotenv
5
+ import config
6
+ from g4f.client import Client
7
+ import time
8
 
9
+ load_dotenv()
10
+
11
+ st.set_page_config(
12
+ page_title=config.APP_NAME,
13
+ page_icon=":robot_face:",
14
+ layout="wide"
15
+ )
16
+
17
+ st.markdown("""
18
+ <style>
19
+ .stChatMessage {
20
+ background-color: #262730;
21
+ border-radius: 10px;
22
+ padding: 15px;
23
+ margin-bottom: 10px;
24
+ color: white;
25
+ box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2);
26
+ }
27
+
28
+ .stSidebar {
29
+ background-color: #1E1E1E;
30
+ color: white;
31
+ padding: 20px;
32
+ }
33
+
34
+ .stSidebar h2, .stSidebar h3 {
35
+ color: #007BFF;
36
+ }
37
+
38
+ .stSidebar .stButton>button {
39
+ width: 100%;
40
+ border-radius: 5px;
41
+ margin-bottom: 10px;
42
+ }
43
+
44
+ .main .block-container {
45
+ padding-top: 2rem;
46
+ padding-bottom: 2rem;
47
+ }
48
+
49
+ .stChatInputContainer {
50
+ margin-top: 20px;
51
+ }
52
+
53
+ body {
54
+ color: white;
55
+ }
56
+ </style>
57
+ """, unsafe_allow_html=True)
58
+
59
+ if "chat_sessions" not in st.session_state:
60
+ st.session_state.chat_sessions = {}
61
+ if "current_chat_id" not in st.session_state:
62
+ st.session_state.current_chat_id = None
63
+ if "system_message" not in st.session_state:
64
+ st.session_state.system_message = "Hello! I am ready to help you."
65
+ if "selected_model" not in st.session_state:
66
+ st.session_state.selected_model = config.DEFAULT_MODEL
67
+ if "model_selected" not in st.session_state:
68
+ st.session_state.model_selected = False
69
+ if "request_timestamps" not in st.session_state:
70
+ st.session_state.request_timestamps = []
71
+
72
+
73
+ def start_new_chat():
74
+ new_chat_id = str(uuid.uuid4())
75
+ st.session_state.chat_sessions[new_chat_id] = [{"role": "assistant", "content": st.session_state.system_message}]
76
+ st.session_state.current_chat_id = new_chat_id
77
+ st.session_state.model_selected = False
78
+ st.session_state.request_timestamps = []
79
+
80
+
81
+ with st.sidebar:
82
+ st.header("Chat History")
83
+
84
+ if st.button("New Chat"):
85
+ start_new_chat()
86
+ st.rerun()
87
+
88
+ if st.session_state.current_chat_id is None:
89
+ start_new_chat()
90
+ st.rerun()
91
+
92
+ st.subheader("Existing Chats")
93
+ if st.session_state.chat_sessions:
94
+ for chat_id in reversed(list(st.session_state.chat_sessions.keys())):
95
+ history = st.session_state.chat_sessions[chat_id]
96
+ if len(history) > 1 and history[1]['role'] == 'user':
97
+ chat_title_content = str(history[1]['content'])
98
+ chat_title = chat_title_content[:30] + "..." if len(chat_title_content) > 30 else chat_title_content
99
+ else:
100
+ chat_title_content = str(history[0]['content'])
101
+ chat_title = chat_title_content[:30] + "..." if len(chat_title_content) > 30 else chat_title_content
102
+
103
+ button_style = "background-color: #007BFF;" if chat_id == st.session_state.current_chat_id else ""
104
+
105
+ if st.button(chat_title, key=f"select_chat_{chat_id}"):
106
+ st.session_state.current_chat_id = chat_id
107
+ st.session_state.model_selected = True
108
+ st.rerun()
109
+ else:
110
+ st.info("No chats yet.")
111
+
112
+
113
+ st.title(config.APP_NAME)
114
+ st.markdown(f"*{config.APP_DESCRIPTION}*")
115
+
116
+ if not st.session_state.model_selected:
117
+ available_models_display = list(config.MODELS.keys())
118
+ available_models_api = list(config.MODELS.values())
119
+ default_model_index = available_models_api.index(config.DEFAULT_MODEL) if config.DEFAULT_MODEL in available_models_api else 0
120
+ st.session_state.selected_model = st.selectbox("Select AI Model", available_models_display, index=default_model_index)
121
+
122
+
123
+ current_chat_history = st.session_state.chat_sessions.get(st.session_state.current_chat_id, [])
124
+
125
+ chat_container = st.container(border=True)
126
+ with chat_container:
127
+ for message in current_chat_history:
128
+ role = message["role"]
129
+ content = message["content"]
130
+ avatar_icon = "👤" if role == "user" else "🤖"
131
+
132
+ with st.chat_message(role, avatar=avatar_icon):
133
+ st.markdown(content)
134
+
135
+
136
+ user_input = st.chat_input("Type your message here...")
137
+
138
+ if user_input:
139
+ current_time = time.time()
140
+ st.session_state.request_timestamps.append(current_time)
141
+
142
+ one_minute_ago = current_time - 60
143
+ one_hour_ago = current_time - 3600
144
+ one_day_ago = current_time - 86400
145
+
146
+ recent_requests_minute = [ts for ts in st.session_state.request_timestamps if ts > one_minute_ago]
147
+ recent_requests_hour = [ts for ts in st.session_state.request_timestamps if ts > one_hour_ago]
148
+ recent_requests_day = [ts for ts in st.session_state.request_timestamps if ts > one_day_ago]
149
+
150
+ st.session_state.request_timestamps = recent_requests_day
151
+
152
+ if len(recent_requests_minute) > config.RPM or \
153
+ len(recent_requests_hour) > config.RPH or \
154
+ len(recent_requests_day) > config.RPD:
155
+ st.warning("Rate limit exceeded. Please wait before sending another message.")
156
+ else:
157
+ st.session_state.chat_sessions[st.session_state.current_chat_id].append({"role": "user", "content": user_input})
158
+ st.session_state.model_selected = True
159
+
160
+ with chat_container:
161
+ with st.chat_message("user", avatar="👤"):
162
+ st.markdown(user_input)
163
+
164
+ with chat_container:
165
+ with st.chat_message("assistant", avatar="🤖"):
166
+ message_placeholder = st.empty()
167
+ full_response = ""
168
+
169
+ with st.spinner(f"Generating response with {st.session_state.selected_model}..."):
170
+ try:
171
+ client_params = {}
172
+ if config.ALGORITHM == 'openai':
173
+ openai_base_url = os.getenv("OPENAI_BASE_URL")
174
+ openai_api_key = os.getenv("OPENAI_API_KEY")
175
+ if openai_base_url:
176
+ client_params['base_url'] = openai_base_url
177
+ if openai_api_key:
178
+ client_params['api_key'] = openai_api_key
179
+
180
+ client = Client(**client_params)
181
+
182
+ messages_for_api = [{"role": msg["role"], "content": msg["content"]} for msg in st.session_state.chat_sessions[st.session_state.current_chat_id]]
183
+
184
+ api_model_name = config.MODELS.get(st.session_state.selected_model, config.DEFAULT_MODEL)
185
+ if api_model_name not in config.MODELS.values():
186
+ api_model_name = config.DEFAULT_MODEL
187
+
188
+ stream = client.chat.completions.create(
189
+ model=api_model_name,
190
+ messages=messages_for_api,
191
+ stream=True,
192
+ web_search=False
193
+ )
194
+
195
+ for chunk in stream:
196
+ if chunk.choices[0].delta.content is not None:
197
+ full_response += chunk.choices[0].delta.content
198
+ message_placeholder.markdown(full_response + "▌")
199
+
200
+ message_placeholder.markdown(full_response)
201
+
202
+ except Exception as e:
203
+ full_response = f"Error generating response: {e}"
204
+ message_placeholder.markdown(full_response)
205
+
206
+ st.session_state.chat_sessions[st.session_state.current_chat_id].append({"role": "assistant", "content": full_response})
207
+
208
+ st.rerun()