Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -81,7 +81,7 @@ GENRE_EXAMPLES = {
|
|
| 81 |
]
|
| 82 |
}
|
| 83 |
|
| 84 |
-
#
|
| 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,14 +133,12 @@ def create_story_summary(chat_history):
|
|
| 133 |
}
|
| 134 |
return summary_instruction
|
| 135 |
|
| 136 |
-
def
|
| 137 |
-
"""
|
| 138 |
-
|
| 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,23 +149,22 @@ def respond(message: str, chat_history: List[Tuple[str, str]], genre: Optional[s
|
|
| 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
|
| 155 |
if chat_history and use_full_memory:
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
|
|
|
|
|
|
|
|
|
| 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,27 +197,8 @@ def save_story(chat_history):
|
|
| 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():
|
|
@@ -230,12 +208,14 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 230 |
height=500,
|
| 231 |
bubble_full_width=True,
|
| 232 |
show_copy_button=True,
|
| 233 |
-
avatar_images=(
|
|
|
|
| 234 |
container=True,
|
| 235 |
scale=1,
|
| 236 |
min_width=800,
|
| 237 |
value=[],
|
| 238 |
-
render=True
|
|
|
|
| 239 |
)
|
| 240 |
msg = gr.Textbox(
|
| 241 |
placeholder="Describe what you want to do next in the story...",
|
|
@@ -261,10 +241,6 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 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,34 +261,32 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 285 |
results.append("")
|
| 286 |
return tuple(results)
|
| 287 |
|
| 288 |
-
#
|
| 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 |
-
"""
|
| 298 |
if not starter_text:
|
| 299 |
return "", history
|
| 300 |
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
|
| 310 |
-
#
|
| 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,30 +297,16 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 323 |
outputs=starter_buttons
|
| 324 |
)
|
| 325 |
|
| 326 |
-
# Handler for user input
|
| 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=
|
| 342 |
inputs=[msg, chatbot, genre, full_memory],
|
| 343 |
-
outputs=[msg, chatbot]
|
| 344 |
)
|
| 345 |
-
|
| 346 |
submit.click(
|
| 347 |
-
fn=
|
| 348 |
inputs=[msg, chatbot, genre, full_memory],
|
| 349 |
-
outputs=[msg, chatbot]
|
| 350 |
)
|
| 351 |
|
| 352 |
# Clear the chatbot for a new adventure
|
|
@@ -380,14 +340,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 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)
|
|
|
|
| 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 |
}
|
| 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 |
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 |
|
| 198 |
return story_text
|
| 199 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 201 |
gr.Markdown("# 🔮 Interactive Story Time")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
gr.Markdown("Create a completely unique literary world, one choice at a time. Dare to explore the unknown.")
|
| 203 |
|
| 204 |
with gr.Row():
|
|
|
|
| 208 |
height=500,
|
| 209 |
bubble_full_width=True,
|
| 210 |
show_copy_button=True,
|
| 211 |
+
avatar_images=("👤", "🧙♂️"), # Updated avatars
|
| 212 |
+
type="chat",
|
| 213 |
container=True,
|
| 214 |
scale=1,
|
| 215 |
min_width=800,
|
| 216 |
value=[],
|
| 217 |
+
render=True,
|
| 218 |
+
layout="bubble"
|
| 219 |
)
|
| 220 |
msg = gr.Textbox(
|
| 221 |
placeholder="Describe what you want to do next in the story...",
|
|
|
|
| 241 |
info="When enabled, the AI tries to remember the entire story. If disabled, only the last few exchanges are used."
|
| 242 |
)
|
| 243 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
gr.Markdown("## Story Starters")
|
| 245 |
|
| 246 |
# Create four placeholder buttons for story starters
|
|
|
|
| 261 |
results.append("")
|
| 262 |
return tuple(results)
|
| 263 |
|
| 264 |
+
# New direct handler for starter clicks
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
def use_starter(starter_text, history, selected_genre, memory_flag):
|
| 266 |
+
"""Handle starter button clicks with proper message formatting"""
|
| 267 |
if not starter_text:
|
| 268 |
return "", history
|
| 269 |
|
| 270 |
+
try:
|
| 271 |
+
# Use the respond function for consistent handling
|
| 272 |
+
_, updated_history = respond(
|
| 273 |
+
message=starter_text,
|
| 274 |
+
chat_history=history,
|
| 275 |
+
genre=selected_genre,
|
| 276 |
+
use_full_memory=memory_flag
|
| 277 |
+
)
|
| 278 |
+
return "", updated_history
|
| 279 |
+
|
| 280 |
+
except Exception as e:
|
| 281 |
+
error_msg = f"Story magic temporarily interrupted. Please try again. (Error: {str(e)})"
|
| 282 |
+
return "", history + [(starter_text, error_msg)]
|
| 283 |
|
| 284 |
+
# Simplified button connections
|
| 285 |
for starter_button in starter_buttons:
|
| 286 |
starter_button.click(
|
| 287 |
fn=use_starter,
|
| 288 |
inputs=[starter_button, chatbot, genre, full_memory],
|
| 289 |
+
outputs=[msg, chatbot], # Now returning both message and chat history
|
| 290 |
queue=True
|
| 291 |
)
|
| 292 |
|
|
|
|
| 297 |
outputs=starter_buttons
|
| 298 |
)
|
| 299 |
|
| 300 |
+
# Handler for user input
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
msg.submit(
|
| 302 |
+
fn=respond,
|
| 303 |
inputs=[msg, chatbot, genre, full_memory],
|
| 304 |
+
outputs=[msg, chatbot] # Now returning both message and chat history
|
| 305 |
)
|
|
|
|
| 306 |
submit.click(
|
| 307 |
+
fn=respond,
|
| 308 |
inputs=[msg, chatbot, genre, full_memory],
|
| 309 |
+
outputs=[msg, chatbot] # Now returning both message and chat history
|
| 310 |
)
|
| 311 |
|
| 312 |
# Clear the chatbot for a new adventure
|
|
|
|
| 340 |
outputs=starter_buttons,
|
| 341 |
queue=False
|
| 342 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
|
| 344 |
# Run the app
|
| 345 |
if __name__ == "__main__":
|
| 346 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|