PeterPinetree commited on
Commit
6d9ff47
·
verified ·
1 Parent(s): 084a537

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -44
app.py CHANGED
@@ -81,7 +81,7 @@ GENRE_EXAMPLES = {
81
  ]
82
  }
83
 
84
- # 2. Add constants at the top for magic numbers
85
  MAX_HISTORY_LENGTH = 20
86
  MEMORY_WINDOW = 5 # Reduced from 10 to limit context
87
  MAX_TOKENS = 1024 # Reduced from 2048 for faster responses
@@ -133,12 +133,14 @@ def create_story_summary(chat_history):
133
  }
134
  return summary_instruction
135
 
136
- def format_history_for_gradio(history_tuples):
137
- """Convert chat history to Gradio's message format."""
138
- return [(str(user_msg), str(bot_msg)) for user_msg, bot_msg in history_tuples]
 
 
 
 
139
 
140
- # 1. Add type hints for better code maintainability
141
- # 4. Add input validation
142
  def respond(message: str, chat_history: List[Tuple[str, str]], genre: Optional[str] = None, use_full_memory: bool = True) -> Tuple[str, List[Tuple[str, str]]]:
143
  """Generate a response based on the current message and conversation history."""
144
  if not message.strip():
@@ -149,22 +151,23 @@ def respond(message: str, chat_history: List[Tuple[str, str]], genre: Optional[s
149
  api_messages = [{"role": "system", "content": get_enhanced_system_prompt(genre)}]
150
  logging.debug(f"System Message: {api_messages[0]}")
151
 
152
- # Add chat history
153
  if chat_history and use_full_memory:
154
- for user_msg, bot_msg in chat_history[-MEMORY_WINDOW:]:
155
- api_messages.extend([
156
- {"role": "user", "content": str(user_msg)},
157
- {"role": "assistant", "content": str(bot_msg)}
158
- ])
159
- logging.debug(f"Chat History Messages: {api_messages[1:]}")
160
 
161
  # Add current message
162
  api_messages.append({"role": "user", "content": str(message)})
163
- logging.debug(f"Final Message List: {api_messages}")
 
 
 
164
 
165
  # Make API call
166
  logging.debug("Making API call...")
167
  response = client.chat_completion(
 
168
  messages=api_messages,
169
  max_tokens=MAX_TOKENS,
170
  temperature=TEMPERATURE,
@@ -197,25 +200,41 @@ def save_story(chat_history):
197
 
198
  return story_text
199
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
201
  gr.Markdown("# 🔮 Interactive Story Time")
202
- with gr.Row():
203
- status_message = gr.Markdown("Ready to begin your adventure...", visible=True)
 
 
204
  gr.Markdown("Create a completely unique literary world, one choice at a time. Dare to explore the unknown.")
205
 
206
  with gr.Row():
207
  with gr.Column(scale=3):
208
  # Chat window + user input
209
  chatbot = gr.Chatbot(
210
- height=500, # Increased height
211
- bubble_full_width=True, # Allow bubbles to use full width
212
  show_copy_button=True,
213
  avatar_images=(None, "🧙"),
214
- type="messages",
215
  container=True,
216
  scale=1,
217
- min_width=800, # Ensure minimum width
218
- value=[], # Initialize with empty list
219
  render=True
220
  )
221
  msg = gr.Textbox(
@@ -242,6 +261,10 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
242
  info="When enabled, the AI tries to remember the entire story. If disabled, only the last few exchanges are used."
243
  )
244
 
 
 
 
 
245
  gr.Markdown("## Story Starters")
246
 
247
  # Create four placeholder buttons for story starters
@@ -262,32 +285,34 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
262
  results.append("")
263
  return tuple(results)
264
 
265
- # New direct handler for starter clicks
 
 
 
 
 
 
 
266
  def use_starter(starter_text, history, selected_genre, memory_flag):
267
- """Handle starter button clicks with proper message formatting"""
268
  if not starter_text:
269
  return "", history
270
 
271
- try:
272
- # Use the respond function for consistent handling
273
- _, updated_history = respond(
274
- message=starter_text,
275
- chat_history=history,
276
- genre=selected_genre,
277
- use_full_memory=memory_flag
278
- )
279
- return "", updated_history
280
-
281
- except Exception as e:
282
- error_msg = f"Story magic temporarily interrupted. Please try again. (Error: {str(e)})"
283
- return "", history + [(starter_text, error_msg)]
284
 
285
- # Simplified button connections
286
  for starter_button in starter_buttons:
287
  starter_button.click(
288
  fn=use_starter,
289
  inputs=[starter_button, chatbot, genre, full_memory],
290
- outputs=[msg, chatbot], # Now returning both message and chat history
291
  queue=True
292
  )
293
 
@@ -298,16 +323,30 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
298
  outputs=starter_buttons
299
  )
300
 
301
- # Handler for user input
 
 
 
 
 
 
 
 
 
 
 
 
 
302
  msg.submit(
303
- fn=respond,
304
  inputs=[msg, chatbot, genre, full_memory],
305
- outputs=[msg, chatbot] # Now returning both message and chat history
306
  )
 
307
  submit.click(
308
- fn=respond,
309
  inputs=[msg, chatbot, genre, full_memory],
310
- outputs=[msg, chatbot] # Now returning both message and chat history
311
  )
312
 
313
  # Clear the chatbot for a new adventure
@@ -341,7 +380,14 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
341
  outputs=starter_buttons,
342
  queue=False
343
  )
 
 
 
 
 
 
 
344
 
345
  # Run the app
346
  if __name__ == "__main__":
347
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
81
  ]
82
  }
83
 
84
+ # Constants
85
  MAX_HISTORY_LENGTH = 20
86
  MEMORY_WINDOW = 5 # Reduced from 10 to limit context
87
  MAX_TOKENS = 1024 # Reduced from 2048 for faster responses
 
133
  }
134
  return summary_instruction
135
 
136
+ def format_history_for_api(chat_history):
137
+ """Format chat history for the API - fixed to ensure proper message format"""
138
+ formatted_messages = []
139
+ for user_msg, bot_msg in chat_history:
140
+ formatted_messages.append({"role": "user", "content": str(user_msg)})
141
+ formatted_messages.append({"role": "assistant", "content": str(bot_msg)})
142
+ return formatted_messages
143
 
 
 
144
  def respond(message: str, chat_history: List[Tuple[str, str]], genre: Optional[str] = None, use_full_memory: bool = True) -> Tuple[str, List[Tuple[str, str]]]:
145
  """Generate a response based on the current message and conversation history."""
146
  if not message.strip():
 
151
  api_messages = [{"role": "system", "content": get_enhanced_system_prompt(genre)}]
152
  logging.debug(f"System Message: {api_messages[0]}")
153
 
154
+ # Add chat history - fixed to ensure proper formatting
155
  if chat_history and use_full_memory:
156
+ history_messages = format_history_for_api(chat_history[-MEMORY_WINDOW:])
157
+ api_messages.extend(history_messages)
158
+ logging.debug(f"Added {len(history_messages)} history messages")
 
 
 
159
 
160
  # Add current message
161
  api_messages.append({"role": "user", "content": str(message)})
162
+
163
+ # Log api message structure for debugging
164
+ logging.debug(f"API messages structure: {[msg['role'] for msg in api_messages]}")
165
+ logging.debug(f"Final user message: {message}")
166
 
167
  # Make API call
168
  logging.debug("Making API call...")
169
  response = client.chat_completion(
170
+ model="HuggingFaceH4/zephyr-7b-beta", # Explicitly specify model
171
  messages=api_messages,
172
  max_tokens=MAX_TOKENS,
173
  temperature=TEMPERATURE,
 
200
 
201
  return story_text
202
 
203
+ def test_api_connection():
204
+ """Test API connection and return result"""
205
+ try:
206
+ response = client.chat_completion(
207
+ model="HuggingFaceH4/zephyr-7b-beta",
208
+ messages=[
209
+ {"role": "system", "content": "You are a helpful assistant."},
210
+ {"role": "user", "content": "Say hello!"}
211
+ ],
212
+ max_tokens=50
213
+ )
214
+ return f"✅ API Connection Test: Success! Response: {response.choices[0].message.content[:30]}..."
215
+ except Exception as e:
216
+ return f"❌ API Connection Failed: {str(e)}"
217
+
218
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
219
  gr.Markdown("# 🔮 Interactive Story Time")
220
+
221
+ # Add API status indicator
222
+ api_status = gr.Markdown("Checking API connection...", visible=True)
223
+
224
  gr.Markdown("Create a completely unique literary world, one choice at a time. Dare to explore the unknown.")
225
 
226
  with gr.Row():
227
  with gr.Column(scale=3):
228
  # Chat window + user input
229
  chatbot = gr.Chatbot(
230
+ height=500,
231
+ bubble_full_width=True,
232
  show_copy_button=True,
233
  avatar_images=(None, "🧙"),
 
234
  container=True,
235
  scale=1,
236
+ min_width=800,
237
+ value=[],
238
  render=True
239
  )
240
  msg = gr.Textbox(
 
261
  info="When enabled, the AI tries to remember the entire story. If disabled, only the last few exchanges are used."
262
  )
263
 
264
+ # Add debug button
265
+ debug_btn = gr.Button("Test API Connection", variant="secondary")
266
+ debug_output = gr.Markdown(visible=True)
267
+
268
  gr.Markdown("## Story Starters")
269
 
270
  # Create four placeholder buttons for story starters
 
285
  results.append("")
286
  return tuple(results)
287
 
288
+ # Debug button handler
289
+ debug_btn.click(
290
+ fn=test_api_connection,
291
+ inputs=None,
292
+ outputs=debug_output
293
+ )
294
+
295
+ # Function to handle starter button clicks
296
  def use_starter(starter_text, history, selected_genre, memory_flag):
297
+ """Direct handler for starter buttons"""
298
  if not starter_text:
299
  return "", history
300
 
301
+ # Simply call the respond function with the starter text
302
+ empty_msg, new_history = respond(
303
+ message=starter_text,
304
+ chat_history=history,
305
+ genre=selected_genre,
306
+ use_full_memory=memory_flag
307
+ )
308
+ return empty_msg, new_history
 
 
 
 
 
309
 
310
+ # Connect each starter button
311
  for starter_button in starter_buttons:
312
  starter_button.click(
313
  fn=use_starter,
314
  inputs=[starter_button, chatbot, genre, full_memory],
315
+ outputs=[msg, chatbot],
316
  queue=True
317
  )
318
 
 
323
  outputs=starter_buttons
324
  )
325
 
326
+ # Handler for user input - now using the fixed respond function
327
+ def submit_message(message, history, selected_genre, memory_flag):
328
+ """Handle user message submission"""
329
+ if not message.strip():
330
+ return "", history
331
+
332
+ empty_msg, new_history = respond(
333
+ message=message,
334
+ chat_history=history,
335
+ genre=selected_genre,
336
+ use_full_memory=memory_flag
337
+ )
338
+ return empty_msg, new_history
339
+
340
  msg.submit(
341
+ fn=submit_message,
342
  inputs=[msg, chatbot, genre, full_memory],
343
+ outputs=[msg, chatbot]
344
  )
345
+
346
  submit.click(
347
+ fn=submit_message,
348
  inputs=[msg, chatbot, genre, full_memory],
349
+ outputs=[msg, chatbot]
350
  )
351
 
352
  # Clear the chatbot for a new adventure
 
380
  outputs=starter_buttons,
381
  queue=False
382
  )
383
+
384
+ # Also test API connection on load
385
+ demo.load(
386
+ fn=test_api_connection,
387
+ outputs=api_status,
388
+ queue=False
389
+ )
390
 
391
  # Run the app
392
  if __name__ == "__main__":
393
+ demo.launch(server_name="0.0.0.0", server_port=7860)