neuralleap commited on
Commit
0cf126f
·
verified ·
1 Parent(s): 4a262db

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -216
app.py CHANGED
@@ -2,12 +2,11 @@ import streamlit as st
2
  import requests
3
  from dotenv import load_dotenv
4
  import os
5
- import sys
6
- import time
7
- import random
8
  import uuid
9
  from datetime import datetime
10
  import openai
 
 
11
 
12
  # Load environment variables
13
  load_dotenv()
@@ -19,51 +18,6 @@ st.set_page_config(
19
  layout="wide"
20
  )
21
 
22
- # Add custom CSS for better styling
23
- st.markdown("""
24
- <style>
25
- .main-content {
26
- max-width: 800px;
27
- margin: 0 auto;
28
- padding: 1rem;
29
- }
30
- .chat-message {
31
- padding: 1.5rem;
32
- border-radius: 0.5rem;
33
- margin-bottom: 1rem;
34
- display: flex;
35
- flex-direction: column;
36
- }
37
- .user-message {
38
- background-color: #f0f2f6;
39
- }
40
- .assistant-message {
41
- background-color: #e6f3f7;
42
- }
43
- .chat-input {
44
- position: fixed;
45
- bottom: 0;
46
- width: 100%;
47
- padding: 1rem;
48
- background-color: white;
49
- }
50
- .sidebar-conv {
51
- padding: 0.5rem 1rem;
52
- border-radius: 0.5rem;
53
- margin-bottom: 0.5rem;
54
- cursor: pointer;
55
- transition: background-color 0.3s;
56
- }
57
- .sidebar-conv:hover {
58
- background-color: #f0f2f6;
59
- }
60
- .active-conv {
61
- background-color: #e6f3f7;
62
- font-weight: bold;
63
- }
64
- </style>
65
- """, unsafe_allow_html=True)
66
-
67
  # Initialize session state
68
  if "conversations" not in st.session_state:
69
  st.session_state.conversations = {}
@@ -82,20 +36,10 @@ if "selected_model" not in st.session_state:
82
 
83
  # Get OpenAI API key from environment or let user enter it
84
  openai_api_key = os.getenv("OPENAI_API_KEY_NEW_3")
85
- # For debugging in Hugging Face Spaces, you can temporarily uncomment this:
86
- # openai_api_key = "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"
87
 
88
  # Configure OpenAI client
89
  if openai_api_key:
90
- client = openai.OpenAI(api_key=openai_api_key)
91
- # Optional: Check available models
92
- try:
93
- available_models = client.models.list()
94
- model_ids = [model.id for model in available_models.data]
95
- if 'o3-mini-2025-01-31' not in model_ids:
96
- st.sidebar.warning("The 'o3-mini-2025-01-31' model is not available with this API key.")
97
- except Exception as e:
98
- st.sidebar.error(f"Could not fetch available models: {str(e)}")
99
 
100
  # Available models with descriptions and token limits
101
  AVAILABLE_MODELS = {
@@ -110,60 +54,6 @@ AVAILABLE_MODELS = {
110
  "max_tokens": 8192,
111
  "output_tokens": 800,
112
  "temperature": 0.7
113
- },
114
- "gpt-3.5-turbo-16k": {
115
- "description": "Longer context window",
116
- "max_tokens": 16384,
117
- "output_tokens": 1000,
118
- "temperature": 0.7
119
- },
120
- "gpt-4-turbo": {
121
- "description": "Most powerful model (if available)",
122
- "max_tokens": 128000,
123
- "output_tokens": 1200,
124
- "temperature": 0.7
125
- },
126
- "gpt-4o": {
127
- "description": "Latest GPT-4 Omni model",
128
- "max_tokens": 128000,
129
- "output_tokens": 1200,
130
- "temperature": 0.7
131
- },
132
- "gpt-4o-mini": {
133
- "description": "Efficient version of GPT-4o",
134
- "max_tokens": 128000,
135
- "output_tokens": 1000,
136
- "temperature": 0.7
137
- },
138
- "o1-mini": {
139
- "description": "OpenAI Reasoning Model - Mini",
140
- "max_tokens": 180000,
141
- "output_tokens": 1000,
142
- "temperature": 0.7
143
- },
144
- "o1": {
145
- "description": "OpenAI Reasoning Model - Standard",
146
- "max_tokens": 200000,
147
- "output_tokens": 1200,
148
- "temperature": 0.7
149
- },
150
- "o1-pro": {
151
- "description": "OpenAI Reasoning Model - Professional",
152
- "max_tokens": 200000,
153
- "output_tokens": 1500,
154
- "temperature": 0.7
155
- },
156
- "o3-mini": {
157
- "description": "OpenAI Advanced Reasoning - Mini",
158
- "max_tokens": 200000,
159
- "output_tokens": 1000,
160
- "temperature": 0.7
161
- },
162
- "o3-mini-2025-01-31": {
163
- "description": "OpenAI Advanced Reasoning - Enhanced",
164
- "max_tokens": 200000,
165
- "output_tokens": 1200,
166
- "temperature": 0.7
167
  }
168
  }
169
 
@@ -185,60 +75,39 @@ def get_ai_response(prompt, history):
185
  output_tokens = model_config["output_tokens"]
186
  temperature = model_config["temperature"]
187
 
188
- response = client.chat.completions.create(
189
  model=model,
190
  messages=messages,
191
  temperature=temperature,
192
  max_tokens=output_tokens,
193
  stream=False
194
  )
195
- return response.choices[0].message.content
196
 
197
- except openai.AuthenticationError as auth_err:
198
  return f"Authentication error: {str(auth_err)}. Check your API key."
199
- except openai.InvalidRequestError as inv_err:
200
  return f"Invalid request: {str(inv_err)}. The model '{model}' might not be available with your API key."
 
 
 
 
 
 
201
  except Exception as e:
202
- return f"An error occurred: {str(e)}. Please try a different model or check your setup."
203
 
204
  # Demo mode responses for when no API key is available
205
  def get_demo_response(prompt):
206
- prompt_lower = prompt.lower()
207
- greetings = [
208
- "Hello! How can I assist you today?",
209
- "Hi there! I'm a demo AI assistant. What can I help you with?",
210
- "Greetings! I'm running in demo mode. Feel free to ask simple questions."
211
- ]
212
- farewells = [
213
- "Goodbye! Have a great day!",
214
- "Farewell! Come back soon!",
215
- "Take care! It was nice chatting with you."
216
- ]
217
- info_responses = [
218
- "I'm a simple AI assistant running in demo mode. To use the full features, please provide an OpenAI API key.",
219
- "This is a demo version with limited capabilities. For a better experience, add your OpenAI API key.",
220
- "I'm just demonstrating basic functionality. Get a free API key from OpenAI to unlock my full potential!"
221
- ]
222
- reasoning_examples = [
223
- "This is a demonstration of how I would process a reasoning task. In a real scenario with the full model, I would analyze the problem step by step, consider multiple angles, and provide a detailed explanation.",
224
- "When solving problems, I would typically break them down into smaller parts, examine each component, and build towards a comprehensive solution. This demo just simulates that process.",
225
- "Reasoning typically involves identifying key facts, applying logical rules, and drawing conclusions based on available information. With a proper API key, I could demonstrate this more effectively."
226
- ]
227
 
228
- if any(word in prompt_lower for word in ["hello", "hi", "hey", "greetings"]):
229
  return random.choice(greetings)
230
- elif any(word in prompt_lower for word in ["bye", "goodbye", "farewell", "see you"]):
231
  return random.choice(farewells)
232
- elif any(phrase in prompt_lower for phrase in ["who are you", "what are you", "tell me about yourself", "what can you do"]):
233
- return random.choice(info_responses)
234
- elif any(word in prompt_lower for word in ["think", "reason", "analyze", "solve", "explain", "why", "how"]):
235
- return random.choice(reasoning_examples)
236
- elif "weather" in prompt_lower:
237
- return "I'm sorry, I don't have access to real-time weather data in demo mode."
238
- elif any(word in prompt_lower for word in ["help", "assist", "support"]):
239
- return "To get better assistance, please add your OpenAI API key. You can get one for free at https://platform.openai.com/account/api-keys."
240
  else:
241
- return "I'm running in demo mode with limited responses. For a full conversation experience, please add your OpenAI API key above."
242
 
243
  # Function to create a new conversation
244
  def create_new_chat():
@@ -249,23 +118,6 @@ def create_new_chat():
249
  "messages": []
250
  }
251
 
252
- # Function to update conversation title based on first message
253
- def update_conversation_title(conv_id, user_message):
254
- current_title = st.session_state.conversations[conv_id]["title"]
255
- if current_title.startswith("New chat"):
256
- new_title = user_message[:30] + "..." if len(user_message) > 30 else user_message
257
- st.session_state.conversations[conv_id]["title"] = new_title
258
-
259
- # Function to delete a conversation
260
- def delete_conversation(conv_id):
261
- if conv_id in st.session_state.conversations:
262
- del st.session_state.conversations[conv_id]
263
- if conv_id == st.session_state.current_conversation_id:
264
- if st.session_state.conversations:
265
- st.session_state.current_conversation_id = next(iter(st.session_state.conversations))
266
- else:
267
- create_new_chat()
268
-
269
  # Create a two-column layout
270
  sidebar, main_content = st.columns([1, 3])
271
 
@@ -284,54 +136,14 @@ with sidebar:
284
  entered_token = st.sidebar.text_input("Enter OpenAI API Key", type="password")
285
  if entered_token:
286
  openai_api_key = entered_token
287
- client = openai.OpenAI(api_key=openai_api_key)
288
 
289
  st.sidebar.subheader("Model Selection")
290
  model_options = list(AVAILABLE_MODELS.keys())
291
- model_descriptions = [f"{model} - {AVAILABLE_MODELS[model]['description']}" for model in model_options]
292
- selected_model_index = model_options.index(st.session_state.selected_model) if st.session_state.selected_model in model_options else 0
293
-
294
- selected_description = st.sidebar.selectbox(
295
- "Choose a model:",
296
- model_descriptions,
297
- index=selected_model_index
298
- )
299
-
300
- selected_model = model_options[model_descriptions.index(selected_description)]
301
- if selected_model != st.session_state.selected_model:
302
- st.session_state.selected_model = selected_model
303
- st.sidebar.info(f"Model set to {selected_model}")
304
-
305
- with st.sidebar.expander("Model Details"):
306
- model_info = AVAILABLE_MODELS[selected_model]
307
- st.write(f"**Description:** {model_info['description']}")
308
- st.write(f"**Max tokens:** {model_info['max_tokens']}")
309
- st.write(f"**Default temperature:** {model_info['temperature']}")
310
- st.write("""
311
- **Note:** Some models may not be available with your current API key.
312
- If you encounter an error, try selecting a different model.
313
- """)
314
-
315
  st.sidebar.markdown("---")
316
-
317
- for conv_id, conv_data in st.session_state.conversations.items():
318
- col1, col2 = st.sidebar.columns([4, 1])
319
- is_active = conv_id == st.session_state.current_conversation_id
320
-
321
- with col1:
322
- if st.button(
323
- conv_data["title"],
324
- key=f"conv_{conv_id}",
325
- use_container_width=True,
326
- type="secondary" if is_active else "tertiary"
327
- ):
328
- st.session_state.current_conversation_id = conv_id
329
- st.rerun()
330
-
331
- with col2:
332
- if st.button("🗑️", key=f"del_{conv_id}"):
333
- delete_conversation(conv_id)
334
- st.rerun()
335
 
336
  # Main content area
337
  with main_content:
@@ -344,7 +156,7 @@ with main_content:
344
  chat_container = st.container()
345
 
346
  with chat_container:
347
- for i, message in enumerate(messages):
348
  with st.chat_message(message["role"]):
349
  st.markdown(message["content"])
350
 
@@ -353,9 +165,6 @@ with main_content:
353
  if prompt:
354
  messages.append({"role": "user", "content": prompt})
355
 
356
- if len(messages) == 1:
357
- update_conversation_title(current_id, prompt)
358
-
359
  with st.chat_message("user"):
360
  st.markdown(prompt)
361
 
@@ -369,4 +178,4 @@ with main_content:
369
  time.sleep(0.005)
370
  message_placeholder.markdown(full_response)
371
  messages.append({"role": "assistant", "content": full_response})
372
- st.rerun()
 
2
  import requests
3
  from dotenv import load_dotenv
4
  import os
 
 
 
5
  import uuid
6
  from datetime import datetime
7
  import openai
8
+ import time
9
+ import random
10
 
11
  # Load environment variables
12
  load_dotenv()
 
18
  layout="wide"
19
  )
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  # Initialize session state
22
  if "conversations" not in st.session_state:
23
  st.session_state.conversations = {}
 
36
 
37
  # Get OpenAI API key from environment or let user enter it
38
  openai_api_key = os.getenv("OPENAI_API_KEY_NEW_3")
 
 
39
 
40
  # Configure OpenAI client
41
  if openai_api_key:
42
+ openai.api_key = openai_api_key
 
 
 
 
 
 
 
 
43
 
44
  # Available models with descriptions and token limits
45
  AVAILABLE_MODELS = {
 
54
  "max_tokens": 8192,
55
  "output_tokens": 800,
56
  "temperature": 0.7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  }
58
  }
59
 
 
75
  output_tokens = model_config["output_tokens"]
76
  temperature = model_config["temperature"]
77
 
78
+ response = openai.ChatCompletion.create(
79
  model=model,
80
  messages=messages,
81
  temperature=temperature,
82
  max_tokens=output_tokens,
83
  stream=False
84
  )
85
+ return response['choices'][0]['message']['content']
86
 
87
+ except openai.error.AuthenticationError as auth_err:
88
  return f"Authentication error: {str(auth_err)}. Check your API key."
89
+ except openai.error.InvalidRequestError as inv_err:
90
  return f"Invalid request: {str(inv_err)}. The model '{model}' might not be available with your API key."
91
+ except openai.error.APIConnectionError as conn_err:
92
+ return f"API connection error: {str(conn_err)}. Please check your network and try again."
93
+ except openai.error.RateLimitError as rate_err:
94
+ return f"Rate limit exceeded: {str(rate_err)}. Please wait before trying again."
95
+ except openai.error.OpenAIError as openai_err:
96
+ return f"OpenAI error: {str(openai_err)}. An unexpected error occurred."
97
  except Exception as e:
98
+ return f"An unexpected error occurred: {str(e)}."
99
 
100
  # Demo mode responses for when no API key is available
101
  def get_demo_response(prompt):
102
+ greetings = ["Hello! How can I assist you today?", "Hi there! What can I help you with?"]
103
+ farewells = ["Goodbye! Have a great day!", "Take care! It was nice chatting with you."]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
+ if any(word in prompt.lower() for word in ["hello", "hi", "hey"]):
106
  return random.choice(greetings)
107
+ elif any(word in prompt.lower() for word in ["bye", "goodbye", "farewell"]):
108
  return random.choice(farewells)
 
 
 
 
 
 
 
 
109
  else:
110
+ return "I'm running in demo mode. Provide an OpenAI API key for full functionality."
111
 
112
  # Function to create a new conversation
113
  def create_new_chat():
 
118
  "messages": []
119
  }
120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  # Create a two-column layout
122
  sidebar, main_content = st.columns([1, 3])
123
 
 
136
  entered_token = st.sidebar.text_input("Enter OpenAI API Key", type="password")
137
  if entered_token:
138
  openai_api_key = entered_token
139
+ openai.api_key = openai_api_key
140
 
141
  st.sidebar.subheader("Model Selection")
142
  model_options = list(AVAILABLE_MODELS.keys())
143
+ selected_model = st.sidebar.selectbox("Choose a model:", model_options)
144
+ st.session_state.selected_model = selected_model
145
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  st.sidebar.markdown("---")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
  # Main content area
149
  with main_content:
 
156
  chat_container = st.container()
157
 
158
  with chat_container:
159
+ for message in messages:
160
  with st.chat_message(message["role"]):
161
  st.markdown(message["content"])
162
 
 
165
  if prompt:
166
  messages.append({"role": "user", "content": prompt})
167
 
 
 
 
168
  with st.chat_message("user"):
169
  st.markdown(prompt)
170
 
 
178
  time.sleep(0.005)
179
  message_placeholder.markdown(full_response)
180
  messages.append({"role": "assistant", "content": full_response})
181
+ st.rerun()