diegocp01 commited on
Commit
16565e1
·
verified ·
1 Parent(s): 9109896

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -130
app.py CHANGED
@@ -3,228 +3,195 @@ from openai import OpenAI
3
  from datetime import datetime
4
  import gradio as gr
5
  import time
6
- import openai # Already imported OpenAI above, this line is redundant
7
 
8
  # --- Constants ---
9
- # Use a model available in the dropdown as the default
10
- DEFAULT_MODEL = "gpt-4o-mini-2024-07-18"
11
- DEFAULT_TEMPERATURE = 1.0
12
- DEFAULT_TOP_P = 1.0
13
- DEFAULT_FREQ_PENALTY = 0
14
- DEFAULT_PRES_PENALTY = 0
15
- MAX_TOKENS = 2048 # This is often controlled by the model, but can be a limit
16
- MAX_HISTORY_LENGTH = 5
17
 
18
  # --- API Key and Client Initialization ---
19
- # Ensure the API key is set in your Hugging Face Space secrets
20
  API_KEY = os.getenv("OPENAI_API_KEY")
21
  if not API_KEY:
22
- # Provide a clear error message if the key is missing
23
- # In a real HF Space, you might raise an exception or disable the UI
24
  print("Error: OPENAI_API_KEY environment variable not set.")
25
- # Consider adding a gr.Markdown warning in the UI as well if API_KEY is None
26
- # For now, we'll let it proceed, but OpenAI() will likely raise an error later.
27
  client = OpenAI(api_key=API_KEY)
28
 
29
  # --- Helper Functions ---
30
- def get_openai_response(prompt, model=DEFAULT_MODEL, temperature=DEFAULT_TEMPERATURE, top_p=DEFAULT_TOP_P,
31
- frequency_penalty=DEFAULT_FREQ_PENALTY, presence_penalty=DEFAULT_PRES_PENALTY,
32
- max_tokens=MAX_TOKENS, system_prompt="", chat_history=None):
33
- """Gets a response from the OpenAI API, handling errors and streaming."""
 
 
 
 
34
  today_day = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
35
- messages = []
 
 
36
  # Add system prompt if provided
37
  effective_system_prompt = f"Today's date is: {today_day}. {system_prompt}".strip()
38
  if effective_system_prompt:
39
- messages.append({"role": "system", "content": effective_system_prompt})
 
40
 
41
- # Add chat history
42
  if chat_history:
43
  for turn in chat_history:
44
- # Ensure turn has two elements before trying to access them
45
- if len(turn) == 2 and turn[0] is not None and turn[1] is not None:
46
- messages.append({"role": "user", "content": str(turn[0])}) # Ensure content is string
47
- messages.append({"role": "assistant", "content": str(turn[1])}) # Ensure content is string
48
- # else: # Optional: Handle malformed history entries
49
- # print(f"Skipping malformed history entry: {turn}")
50
 
51
  # Add the current user prompt
52
- messages.append({"role": "user", "content": prompt})
53
 
54
  try:
55
- # *** This is the correct, modern API call for chat models ***
56
- response = client.chat.completions.create(
 
 
 
57
  model=model,
58
- messages=messages,
59
- temperature=temperature,
60
- max_tokens=max_tokens, # Correct parameter name for this call
61
- top_p=top_p,
62
- frequency_penalty=frequency_penalty,
63
- presence_penalty=presence_penalty,
64
- # response_format={"type": "text"}, # Usually not needed unless forcing JSON etc. Let model decide default.
65
- stream=True # Enable streaming
66
  )
 
 
67
 
68
- collected_messages = []
69
- full_reply_content = "" # Initialize before loop
70
- for chunk in response:
71
- # Check if delta and content exist before accessing
72
- if chunk.choices and chunk.choices[0].delta and chunk.choices[0].delta.content is not None:
73
- chunk_message = chunk.choices[0].delta.content
74
- collected_messages.append(chunk_message)
75
- full_reply_content = ''.join(collected_messages)
76
- yield full_reply_content # Yield the accumulated message
77
-
78
- # Use specific exceptions from the openai library
79
  except openai.APIConnectionError as e:
80
  print(f"OpenAI API request failed: {e}")
81
- yield f"Error: Could not connect to OpenAI API. {e}"
82
  except openai.RateLimitError as e:
83
  print(f"OpenAI API request failed: {e}")
84
- yield f"Error: Rate limit exceeded. Please try again later. {e}"
85
  except openai.AuthenticationError as e:
86
  print(f"OpenAI API request failed: {e}")
87
- yield f"Error: Authentication failed. Check your API key. {e}"
88
  except openai.APIStatusError as e:
89
  print(f"OpenAI API request failed: {e}")
90
- yield f"Error: OpenAI API returned an error (Status: {e.status_code}). {e}"
 
 
 
91
  except Exception as e:
92
  print(f"An unexpected error occurred: {e}")
93
- yield f"An unexpected error occurred: {e}"
94
-
95
-
96
- def update_ui(message, chat_history, model, temperature, top_p, frequency_penalty, presence_penalty, system_prompt, history_length):
97
- """Updates the Gradio UI; handles streaming response."""
98
- if not message: # Don't send empty messages
99
- yield "", chat_history
100
- return
101
-
102
- # Trim history before sending to API if it's longer than needed for context
103
- # (Optional optimization, the API call does include full history passed here)
104
- # history_for_api = chat_history[-(MAX_HISTORY_LENGTH*2):] # Keep pairs
105
-
106
- bot_message_gen = get_openai_response(
107
- prompt=message, model=model, temperature=temperature, top_p=top_p,
108
- frequency_penalty=frequency_penalty, presence_penalty=presence_penalty,
109
- system_prompt=system_prompt, chat_history=chat_history # Pass full history for context
110
  )
111
 
112
- chat_history.append((message, "")) # Add user message and placeholder for bot response
 
113
 
114
- # Stream the response
115
- for bot_message_chunk in bot_message_gen:
116
- chat_history[-1] = (message, bot_message_chunk) # Update the last entry with the streamed chunk
117
- # Control visibility based on the slider
118
- visible_history = chat_history[-int(history_length):] if history_length > 0 else []
119
- # time.sleep(0.02) # Slightly shorter delay might feel more responsive
120
- yield "", visible_history
121
 
122
- # --- Gradio Interface ---
123
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
124
- # Keep your informative Markdown sections
125
- gr.Markdown("# Chat with OpenAI Models") # Updated Title
126
- gr.Markdown("❗ GPT-4.5 experiment details from Feb 27, 2025...") # Keep context
127
- gr.Markdown(" [Buy me a Coffee](https://buymeacoffee.com/diegocp01m)")
128
  gr.Markdown("---")
129
- gr.Markdown("""
130
- 🚀 **GPT-4.5 EXPERIMENT RECAP:** GPT-4.5 was briefly accessible via API on Feb 27, 2025.
131
- This space allowed free access during that window.
132
 
133
- 📊 **Chat Completions Metrics (Feb 27, 2025):**
134
- - 111 requests
135
- - 64,764 Total tokens processed
136
- - Total spend: $10.99
137
 
138
- This space went live at 4:23 PM ET, Feb 27, 2025 until 8:53 PM ET. [Read More](https://x.com/diegocabezas01/status/1895291365376041045)
139
- Results from OpenAI platform: 👇
140
- """)
141
- gr.Image("https://pbs.twimg.com/media/Gk1tVnRXkAASa2U?format=jpg&name=4096x4096", elem_id="gpt4_5_image")
142
- gr.Markdown("Chat with available models like GPT-4o mini below: 👇")
143
 
144
  with gr.Row():
145
  with gr.Column(scale=4):
146
  chatbot = gr.Chatbot(
147
- label="Chat Window", # Added label for clarity
148
  show_label=False,
149
  avatar_images=(
150
- # Using generic user icon
151
  "https://cdn-icons-png.flaticon.com/512/1077/1077114.png", # User
152
- # Using generic AI icon
153
  "https://cdn-icons-png.flaticon.com/512/8649/8649540.png" # AI
154
  ),
155
  render_markdown=True,
156
  height=500,
157
- bubble_full_width=False # Optional: makes bubbles look nicer
158
  )
159
  msg = gr.Textbox(
160
- label="Your Message", # Added label
161
  placeholder="Type your message here and press Enter...",
162
  scale=4,
163
  show_label=False,
164
- container=False # Makes it sit closer to the button
165
  )
166
 
167
- with gr.Accordion("Advanced Options", open=False):
 
168
  model_select = gr.Dropdown(
169
  label="Model",
170
- # Ensure these models are available to your API key
171
- choices=["gpt-4o-mini-2024-07-18", "gpt-3.5-turbo-0125", "gpt-4o"],
172
- value=DEFAULT_MODEL, # Use the constant defined above
173
  interactive=True
174
  )
175
- temperature_slider = gr.Slider(label="Temperature (Randomness)", minimum=0.0, maximum=2.0, value=DEFAULT_TEMPERATURE, step=0.1, interactive=True)
176
- top_p_slider = gr.Slider(label="Top P (Nucleus Sampling)", minimum=0.0, maximum=1.0, value=DEFAULT_TOP_P, step=0.05, interactive=True)
177
- frequency_penalty_slider = gr.Slider(label="Frequency Penalty (Discourage repetition)", minimum=-2.0, maximum=2.0, value=DEFAULT_FREQ_PENALTY, step=0.1, interactive=True)
178
- presence_penalty_slider = gr.Slider(label="Presence Penalty (Discourage repeating topics)", minimum=-2.0, maximum=2.0, value=DEFAULT_PRES_PENALTY, step=0.1, interactive=True)
 
179
  system_prompt_textbox = gr.Textbox(label="System Prompt", placeholder="e.g., You are a helpful assistant.", lines=3, interactive=True)
180
- history_length_slider = gr.Slider(label="Chat History Display Length", minimum=1, maximum=20, value=MAX_HISTORY_LENGTH, step=1, interactive=True)
 
181
 
182
  with gr.Row():
183
- # Place clear button first maybe?
184
  clear = gr.Button("Clear Chat")
185
- send = gr.Button("Send Message", variant="primary") # Make send more prominent
186
 
187
 
188
- # --- Event Handlers ---
189
- # Define reusable inputs list
190
- inputs = [
191
- msg, chatbot, model_select, temperature_slider, top_p_slider,
192
- frequency_penalty_slider, presence_penalty_slider, system_prompt_textbox,
193
  history_length_slider
194
  ]
195
- # Define reusable outputs list
196
- outputs = [msg, chatbot]
197
 
198
  # Connect send button click
199
  send.click(
200
- update_ui,
201
- inputs=inputs,
202
  outputs=outputs,
203
- queue=True # Use queue for handling multiple users potentially
204
  )
205
 
206
  # Connect textbox submit (Enter key)
207
  msg.submit(
208
- update_ui,
209
- inputs=inputs,
210
  outputs=outputs,
211
  queue=True
212
  )
213
 
214
  # Connect clear button
215
- # Clears the message box and the chatbot history
216
  clear.click(lambda: (None, []), None, outputs=[msg, chatbot], queue=False)
217
 
218
  gr.Examples(
219
  examples=["Tell me about the latest AI developments", "Write a short story about a friendly robot", "Explain black holes simply"],
220
  inputs=msg,
221
- label="Example Prompts" # Add label
222
  )
223
- # msg.focus() # Autoselect msg box - Sometimes causes issues, use if needed
224
 
225
  # --- Launch ---
226
  if __name__ == "__main__":
227
- # Add share=True for a public link if running locally and want to share
228
- # Add debug=True for more verbose logging during development
229
- demo.queue() # Enable queue for better handling of multiple requests
230
  demo.launch()
 
3
  from datetime import datetime
4
  import gradio as gr
5
  import time
6
+ import openai # Redundant import
7
 
8
  # --- Constants ---
9
+ # Default model might need to align with what client.responses.create supports
10
+ DEFAULT_MODEL = "gpt-4.1" # As per your example
11
+ MAX_HISTORY_LENGTH = 5 # History formatting will be manual and limited
 
 
 
 
 
12
 
13
  # --- API Key and Client Initialization ---
 
14
  API_KEY = os.getenv("OPENAI_API_KEY")
15
  if not API_KEY:
 
 
16
  print("Error: OPENAI_API_KEY environment variable not set.")
17
+ # Handle missing key appropriately (e.g., disable UI, raise error)
 
18
  client = OpenAI(api_key=API_KEY)
19
 
20
  # --- Helper Functions ---
21
+
22
+ # !!! WARNING: This function is adapted to the requested format and LOSES features !!!
23
+ def get_openai_response_simplified(prompt, model=DEFAULT_MODEL, system_prompt="", chat_history=None):
24
+ """
25
+ Gets a response using the client.responses.create format.
26
+ NOTE: This is NON-STREAMING and handles history/system prompt crudely.
27
+ Advanced parameters (temp, top_p etc.) are NOT supported by this structure.
28
+ """
29
  today_day = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
30
+
31
+ # --- Attempt to manually format history and system prompt into 'input' ---
32
+ formatted_input = ""
33
  # Add system prompt if provided
34
  effective_system_prompt = f"Today's date is: {today_day}. {system_prompt}".strip()
35
  if effective_system_prompt:
36
+ # How best to include system prompt? Prepend? Specific tags? Unknown.
37
+ formatted_input += f"System: {effective_system_prompt}\n\n"
38
 
39
+ # Add chat history (simple concatenation)
40
  if chat_history:
41
  for turn in chat_history:
42
+ if len(turn) == 2 and turn[0] is not None and turn[1] is not None:
43
+ formatted_input += f"User: {turn[0]}\nAssistant: {turn[1]}\n"
 
 
 
 
44
 
45
  # Add the current user prompt
46
+ formatted_input += f"User: {prompt}\nAssistant:" # Prompt the model for the next turn
47
 
48
  try:
49
+ # *** Using the requested client.responses.create format ***
50
+ # NOTE: This assumes client.responses.create actually exists and works this way.
51
+ # NOTE: Parameters like temperature, top_p, max_tokens are NOT included here
52
+ # as they are not part of the provided example format.
53
+ response = client.responses.create(
54
  model=model,
55
+ input=formatted_input
 
 
 
 
 
 
 
56
  )
57
+ # Assuming the response object has an 'output_text' attribute
58
+ return response.output_text
59
 
60
+ # Error handling might need adjustment based on how client.responses.create fails
 
 
 
 
 
 
 
 
 
 
61
  except openai.APIConnectionError as e:
62
  print(f"OpenAI API request failed: {e}")
63
+ return f"Error: Could not connect to OpenAI API. {e}"
64
  except openai.RateLimitError as e:
65
  print(f"OpenAI API request failed: {e}")
66
+ return f"Error: Rate limit exceeded. Please try again later. {e}"
67
  except openai.AuthenticationError as e:
68
  print(f"OpenAI API request failed: {e}")
69
+ return f"Error: Authentication failed. Check your API key. {e}"
70
  except openai.APIStatusError as e:
71
  print(f"OpenAI API request failed: {e}")
72
+ return f"Error: OpenAI API returned an error (Status: {e.status_code}). {e}"
73
+ except AttributeError as e:
74
+ print(f"Error accessing response or client method: {e}")
75
+ return f"Error: The API call structure 'client.responses.create' or its response format might be incorrect or not available. {e}"
76
  except Exception as e:
77
  print(f"An unexpected error occurred: {e}")
78
+ return f"An unexpected error occurred: {e}"
79
+
80
+ # !!! WARNING: This update function is now NON-STREAMING !!!
81
+ def update_ui_simplified(message, chat_history, model, system_prompt, history_length):
82
+ """Updates the Gradio UI WITHOUT streaming."""
83
+ if not message:
84
+ return "", chat_history # Return original history if message is empty
85
+
86
+ # Keep only the specified length of history for the *next* call
87
+ history_for_api = chat_history[-int(history_length):] if history_length > 0 else []
88
+
89
+ # Call the simplified, non-streaming function
90
+ bot_response = get_openai_response_simplified(
91
+ prompt=message,
92
+ model=model,
93
+ system_prompt=system_prompt,
94
+ chat_history=history_for_api # Pass the potentially trimmed history
95
  )
96
 
97
+ # Append the user message and the *complete* bot response
98
+ chat_history.append((message, bot_response))
99
 
100
+ # Update UI only once with the full response
101
+ # Always display history based on the slider length for visibility
102
+ visible_history = chat_history[-int(history_length):] if history_length > 0 else []
103
+ return "", visible_history # Clear input, return updated history
 
 
 
104
 
105
+ # --- Gradio Interface (Modified for Simplified API Call) ---
106
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
107
+ # Keep your Markdown, titles, etc.
108
+ gr.Markdown("# Chat (Simplified API Demo)")
109
+ gr.Markdown("---")
110
+ gr.Markdown("Using a simplified, non-streaming API call structure.")
111
  gr.Markdown("---")
 
 
 
112
 
113
+ # ... (rest of your Markdown) ...
 
 
 
114
 
115
+ gr.Markdown("Chat below (Note: Responses will appear all at once): 👇")
 
 
 
 
116
 
117
  with gr.Row():
118
  with gr.Column(scale=4):
119
  chatbot = gr.Chatbot(
120
+ label="Chat Window",
121
  show_label=False,
122
  avatar_images=(
 
123
  "https://cdn-icons-png.flaticon.com/512/1077/1077114.png", # User
 
124
  "https://cdn-icons-png.flaticon.com/512/8649/8649540.png" # AI
125
  ),
126
  render_markdown=True,
127
  height=500,
128
+ bubble_full_width=False
129
  )
130
  msg = gr.Textbox(
131
+ label="Your Message",
132
  placeholder="Type your message here and press Enter...",
133
  scale=4,
134
  show_label=False,
135
+ container=False
136
  )
137
 
138
+ # Accordion remains, but parameters might not be used by the simplified API call
139
+ with gr.Accordion("Advanced Options (May Not Apply to Simplified API)", open=False):
140
  model_select = gr.Dropdown(
141
  label="Model",
142
+ # Ensure gpt-4.1 is a valid choice if used
143
+ choices=["gpt-4.1", "gpt-4o-mini-2024-07-18", "gpt-3.5-turbo-0125", "gpt-4o"],
144
+ value=DEFAULT_MODEL,
145
  interactive=True
146
  )
147
+ # These sliders are kept for UI, but won't be passed to the simplified API call
148
+ temperature_slider = gr.Slider(label="Temperature (Not Used)", minimum=0.0, maximum=2.0, value=1.0, step=0.1, interactive=True)
149
+ top_p_slider = gr.Slider(label="Top P (Not Used)", minimum=0.0, maximum=1.0, value=1.0, step=0.05, interactive=True)
150
+ frequency_penalty_slider = gr.Slider(label="Frequency Penalty (Not Used)", minimum=-2.0, maximum=2.0, value=0.0, step=0.1, interactive=True)
151
+ presence_penalty_slider = gr.Slider(label="Presence Penalty (Not Used)", minimum=-2.0, maximum=2.0, value=0.0, step=0.1, interactive=True)
152
  system_prompt_textbox = gr.Textbox(label="System Prompt", placeholder="e.g., You are a helpful assistant.", lines=3, interactive=True)
153
+ history_length_slider = gr.Slider(label="Chat History Length (Affects Input & Display)", minimum=1, maximum=20, value=MAX_HISTORY_LENGTH, step=1, interactive=True)
154
+
155
 
156
  with gr.Row():
 
157
  clear = gr.Button("Clear Chat")
158
+ send = gr.Button("Send Message", variant="primary")
159
 
160
 
161
+ # --- Event Handlers (Using Simplified Functions) ---
162
+ # Define inputs, excluding sliders not used by the simplified function
163
+ inputs_simplified = [
164
+ msg, chatbot, model_select, system_prompt_textbox,
 
165
  history_length_slider
166
  ]
167
+ outputs = [msg, chatbot] # Outputs remain the same
 
168
 
169
  # Connect send button click
170
  send.click(
171
+ update_ui_simplified, # Use the non-streaming UI update function
172
+ inputs=inputs_simplified,
173
  outputs=outputs,
174
+ queue=True
175
  )
176
 
177
  # Connect textbox submit (Enter key)
178
  msg.submit(
179
+ update_ui_simplified, # Use the non-streaming UI update function
180
+ inputs=inputs_simplified,
181
  outputs=outputs,
182
  queue=True
183
  )
184
 
185
  # Connect clear button
 
186
  clear.click(lambda: (None, []), None, outputs=[msg, chatbot], queue=False)
187
 
188
  gr.Examples(
189
  examples=["Tell me about the latest AI developments", "Write a short story about a friendly robot", "Explain black holes simply"],
190
  inputs=msg,
191
+ label="Example Prompts"
192
  )
 
193
 
194
  # --- Launch ---
195
  if __name__ == "__main__":
196
+ demo.queue()
 
 
197
  demo.launch()