PeterPinetree commited on
Commit
ca074f4
·
verified ·
1 Parent(s): 43d4e1c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -13
app.py CHANGED
@@ -136,7 +136,7 @@ def create_story_summary(chat_history):
136
  return summary_instruction
137
 
138
  # Modified function for proper Gradio format (lists)
139
- def respond(message: str, chat_history: List[str], genre: Optional[str] = None, use_full_memory: bool = True) -> Tuple[str, List[str]]:
140
  """Generate a response based on the current message and conversation history."""
141
  if not message.strip():
142
  return "", chat_history
@@ -146,11 +146,9 @@ def respond(message: str, chat_history: List[str], genre: Optional[str] = None,
146
  api_messages = [{"role": "system", "content": get_enhanced_system_prompt(genre)}]
147
  logging.debug(f"System Message: {api_messages[0]}")
148
 
149
- # Add chat history - convert from lists to API format
150
  if chat_history and use_full_memory:
151
- # Take pairs of messages (user, bot) from history
152
- history_pairs = list(zip(chat_history[::2], chat_history[1::2]))
153
- for user_msg, bot_msg in history_pairs[-MEMORY_WINDOW:]:
154
  api_messages.extend([
155
  {"role": "user", "content": str(user_msg)},
156
  {"role": "assistant", "content": str(bot_msg)}
@@ -161,28 +159,30 @@ def respond(message: str, chat_history: List[str], genre: Optional[str] = None,
161
  api_messages.append({"role": "user", "content": str(message)})
162
  logging.debug(f"Final Message List: {api_messages}")
163
 
164
- # Make API call
165
  logging.debug("Making API call...")
166
  response = client.chat_completion(
167
  messages=api_messages,
168
  max_tokens=MAX_TOKENS,
169
  temperature=TEMPERATURE,
170
- top_p=TOP_P
 
171
  )
172
  logging.debug("API call completed")
173
 
174
  # Extract response
175
  bot_message = response.choices[0].message.content
176
- logging.debug(f"Bot Response: {bot_message[:100]}...") # First 100 chars
177
 
178
- # Update history using list format [user_msg, bot_msg, user_msg, bot_msg, ...]
179
- updated_history = chat_history + [message, bot_message]
 
180
  return "", updated_history
181
 
182
  except Exception as e:
183
  logging.error("Error in respond function", exc_info=True)
184
  error_msg = f"Story magic temporarily interrupted. Please try again. (Error: {str(e)})"
185
- return "", chat_history + [message, error_msg]
186
 
187
  def save_story(chat_history):
188
  """Convert chat history to markdown and return as downloadable file"""
@@ -281,7 +281,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
281
  return tuple(results)
282
 
283
  # New direct handler for starter clicks
284
- def use_starter(starter_text, history, selected_genre, memory_flag):
285
  """Handle starter button clicks with proper message formatting"""
286
  if not starter_text:
287
  return "", history
@@ -298,7 +298,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
298
 
299
  except Exception as e:
300
  error_msg = f"Story magic temporarily interrupted. Please try again. (Error: {str(e)})"
301
- return "", history + [starter_text, error_msg]
302
 
303
  # Simplified button connections
304
  for starter_button in starter_buttons:
 
136
  return summary_instruction
137
 
138
  # Modified function for proper Gradio format (lists)
139
+ 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]]]:
140
  """Generate a response based on the current message and conversation history."""
141
  if not message.strip():
142
  return "", chat_history
 
146
  api_messages = [{"role": "system", "content": get_enhanced_system_prompt(genre)}]
147
  logging.debug(f"System Message: {api_messages[0]}")
148
 
149
+ # Add chat history - convert from tuples to API format
150
  if chat_history and use_full_memory:
151
+ for user_msg, bot_msg in chat_history[-MEMORY_WINDOW:]:
 
 
152
  api_messages.extend([
153
  {"role": "user", "content": str(user_msg)},
154
  {"role": "assistant", "content": str(bot_msg)}
 
159
  api_messages.append({"role": "user", "content": str(message)})
160
  logging.debug(f"Final Message List: {api_messages}")
161
 
162
+ # Make API call with timeout
163
  logging.debug("Making API call...")
164
  response = client.chat_completion(
165
  messages=api_messages,
166
  max_tokens=MAX_TOKENS,
167
  temperature=TEMPERATURE,
168
+ top_p=TOP_P,
169
+ timeout=30 # 30 second timeout
170
  )
171
  logging.debug("API call completed")
172
 
173
  # Extract response
174
  bot_message = response.choices[0].message.content
175
+ logging.debug(f"Bot Response: {bot_message[:100]}...")
176
 
177
+ # Update history using tuple format [(user_msg, bot_msg), ...]
178
+ updated_history = list(chat_history) # Create a copy
179
+ updated_history.append((message, bot_message)) # Add as tuple
180
  return "", updated_history
181
 
182
  except Exception as e:
183
  logging.error("Error in respond function", exc_info=True)
184
  error_msg = f"Story magic temporarily interrupted. Please try again. (Error: {str(e)})"
185
+ return "", list(chat_history) + [(message, error_msg)]
186
 
187
  def save_story(chat_history):
188
  """Convert chat history to markdown and return as downloadable file"""
 
281
  return tuple(results)
282
 
283
  # New direct handler for starter clicks
284
+ def use_starter(starter_text: str, history: List[Tuple[str, str]], selected_genre: str, memory_flag: bool) -> Tuple[str, List[Tuple[str, str]]]:
285
  """Handle starter button clicks with proper message formatting"""
286
  if not starter_text:
287
  return "", history
 
298
 
299
  except Exception as e:
300
  error_msg = f"Story magic temporarily interrupted. Please try again. (Error: {str(e)})"
301
+ return "", list(history) + [(starter_text, error_msg)]
302
 
303
  # Simplified button connections
304
  for starter_button in starter_buttons: