Spaces:
Running
Running
update and clean scr
Browse files
helper.py
CHANGED
@@ -156,7 +156,8 @@ CRITICAL Rules:
|
|
156 |
- Never use ellipsis (...)
|
157 |
- Never include 'What would you like to do?' or similar prompts
|
158 |
- Always finish with one real response
|
159 |
-
-
|
|
|
160 |
|
161 |
|
162 |
def get_game_state(inventory: Dict = None) -> Dict[str, Any]:
|
@@ -457,13 +458,17 @@ def update_game_inventory(game_state: Dict, story_text: str) -> str:
|
|
457 |
def extract_response_after_action(full_text: str, action: str) -> str:
|
458 |
"""Extract response text that comes after the user action line"""
|
459 |
try:
|
|
|
|
|
|
|
|
|
460 |
# Split into lines
|
461 |
lines = full_text.split("\n")
|
462 |
|
463 |
# Find index of line containing user action
|
464 |
action_line_index = -1
|
465 |
for i, line in enumerate(lines):
|
466 |
-
if
|
467 |
action_line_index = i
|
468 |
break
|
469 |
|
@@ -475,14 +480,15 @@ def extract_response_after_action(full_text: str, action: str) -> str:
|
|
475 |
# Clean up any remaining markers
|
476 |
response = response.split("user:")[0].strip()
|
477 |
response = response.split("system:")[0].strip()
|
|
|
478 |
|
479 |
-
return response
|
480 |
|
481 |
-
return ""
|
482 |
|
483 |
except Exception as e:
|
484 |
logger.error(f"Error extracting response: {e}")
|
485 |
-
return ""
|
486 |
|
487 |
|
488 |
def run_action(message: str, history: list, game_state: Dict) -> str:
|
@@ -490,15 +496,7 @@ def run_action(message: str, history: list, game_state: Dict) -> str:
|
|
490 |
try:
|
491 |
# Handle start game command
|
492 |
if message.lower() == "start game":
|
493 |
-
|
494 |
-
# initial_quest = {
|
495 |
-
# "title": "Investigate the Mist",
|
496 |
-
# "description": "Strange mists have been gathering around Ravenhurst. Investigate their source.",
|
497 |
-
# "exp_reward": 100,
|
498 |
-
# "status": "active",
|
499 |
-
# }
|
500 |
-
# game_state["current_quest"] = initial_quest
|
501 |
-
# Initialize first quest
|
502 |
initial_quest = generate_next_quest(game_state)
|
503 |
game_state["current_quest"] = initial_quest
|
504 |
|
@@ -557,6 +555,7 @@ Inventory: {json.dumps(game_state['inventory'])}"""
|
|
557 |
# Convert messages to string format for pipeline
|
558 |
prompt = "\n".join([f"{msg['role']}: {msg['content']}" for msg in messages])
|
559 |
|
|
|
560 |
# Generate response
|
561 |
model_output = generator(
|
562 |
prompt,
|
@@ -567,13 +566,28 @@ Inventory: {json.dumps(game_state['inventory'])}"""
|
|
567 |
repetition_penalty=1.2,
|
568 |
pad_token_id=tokenizer.eos_token_id,
|
569 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
570 |
|
571 |
# Extract and clean response
|
572 |
full_response = model_output[0]["generated_text"]
|
573 |
-
|
|
|
|
|
|
|
|
|
574 |
|
575 |
response = extract_response_after_action(full_response, message)
|
576 |
-
print(f"response in run_action: {response}")
|
577 |
|
578 |
# Convert to second person
|
579 |
response = response.replace("Elara", "You")
|
@@ -590,10 +604,10 @@ Inventory: {json.dumps(game_state['inventory'])}"""
|
|
590 |
response = response.rstrip("?").rstrip(".") + "."
|
591 |
response = response.replace("...", ".")
|
592 |
|
593 |
-
# Perform safety check before returning
|
594 |
-
safe = is_safe(response)
|
595 |
-
print(f"\nSafety Check Result: {'SAFE' if safe else 'UNSAFE'}")
|
596 |
-
logger.info(f"Safety check result: {'SAFE' if safe else 'UNSAFE'}")
|
597 |
|
598 |
# if not safe:
|
599 |
# logging.warning("Unsafe content detected - blocking response")
|
@@ -667,20 +681,6 @@ def chat_response(message: str, chat_history: list, current_state: dict) -> tupl
|
|
667 |
chat_history = chat_history or []
|
668 |
chat_history.append((message, output))
|
669 |
|
670 |
-
# # Create status text
|
671 |
-
# status_text = "Health: 100/100\nLevel: 1\nExp: 0/100"
|
672 |
-
# if current_state.get("player"):
|
673 |
-
# status_text = (
|
674 |
-
# f"Health: {current_state['player'].health}/{current_state['player'].max_health}\n"
|
675 |
-
# f"Level: {current_state['player'].level}\n"
|
676 |
-
# f"Exp: {current_state['player'].exp}/{current_state['player'].exp_to_level}"
|
677 |
-
# )
|
678 |
-
|
679 |
-
# quest_text = "No active quest"
|
680 |
-
# if current_state.get("current_quest"):
|
681 |
-
# quest = current_state["current_quest"]
|
682 |
-
# quest_text = f"{quest['title']}\n{quest['description']}"
|
683 |
-
|
684 |
# Update status displays
|
685 |
status_text, quest_text = update_game_status(current_state)
|
686 |
|
|
|
156 |
- Never use ellipsis (...)
|
157 |
- Never include 'What would you like to do?' or similar prompts
|
158 |
- Always finish with one real response
|
159 |
+
- Never use 'Your turn' or or anything like conversation starting prompts
|
160 |
+
- Always end the response with a period"""
|
161 |
|
162 |
|
163 |
def get_game_state(inventory: Dict = None) -> Dict[str, Any]:
|
|
|
458 |
def extract_response_after_action(full_text: str, action: str) -> str:
|
459 |
"""Extract response text that comes after the user action line"""
|
460 |
try:
|
461 |
+
if not full_text: # Add null check
|
462 |
+
logger.error("Received empty response from model")
|
463 |
+
return "You look around carefully."
|
464 |
+
|
465 |
# Split into lines
|
466 |
lines = full_text.split("\n")
|
467 |
|
468 |
# Find index of line containing user action
|
469 |
action_line_index = -1
|
470 |
for i, line in enumerate(lines):
|
471 |
+
if action.lower() in line.lower(): # More flexible matching
|
472 |
action_line_index = i
|
473 |
break
|
474 |
|
|
|
480 |
# Clean up any remaining markers
|
481 |
response = response.split("user:")[0].strip()
|
482 |
response = response.split("system:")[0].strip()
|
483 |
+
response = response.split("assistant:")[0].strip()
|
484 |
|
485 |
+
return response if response else "You look around carefully."
|
486 |
|
487 |
+
return "You look around carefully." # Default response
|
488 |
|
489 |
except Exception as e:
|
490 |
logger.error(f"Error extracting response: {e}")
|
491 |
+
return "You look around carefully."
|
492 |
|
493 |
|
494 |
def run_action(message: str, history: list, game_state: Dict) -> str:
|
|
|
496 |
try:
|
497 |
# Handle start game command
|
498 |
if message.lower() == "start game":
|
499 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
500 |
initial_quest = generate_next_quest(game_state)
|
501 |
game_state["current_quest"] = initial_quest
|
502 |
|
|
|
555 |
# Convert messages to string format for pipeline
|
556 |
prompt = "\n".join([f"{msg['role']}: {msg['content']}" for msg in messages])
|
557 |
|
558 |
+
logger.info("Generating response...")
|
559 |
# Generate response
|
560 |
model_output = generator(
|
561 |
prompt,
|
|
|
566 |
repetition_penalty=1.2,
|
567 |
pad_token_id=tokenizer.eos_token_id,
|
568 |
)
|
569 |
+
# logger.info(f"Raw model output: {model_output}")
|
570 |
+
|
571 |
+
# Check for None response
|
572 |
+
if not model_output or not isinstance(model_output, list):
|
573 |
+
logger.error(f"Invalid model output: {model_output}")
|
574 |
+
print(f"Invalid model output: {model_output}")
|
575 |
+
return "You look around carefully."
|
576 |
+
|
577 |
+
if not model_output[0] or not isinstance(model_output[0], dict):
|
578 |
+
logger.error(f"Invalid response format: {type(model_output[0])}")
|
579 |
+
return "You look around carefully."
|
580 |
|
581 |
# Extract and clean response
|
582 |
full_response = model_output[0]["generated_text"]
|
583 |
+
if not full_response:
|
584 |
+
logger.error("Empty response from model")
|
585 |
+
return "You look around carefully."
|
586 |
+
|
587 |
+
print(f"Full response in run_action: {full_response}")
|
588 |
|
589 |
response = extract_response_after_action(full_response, message)
|
590 |
+
print(f"Extracted response in run_action: {response}")
|
591 |
|
592 |
# Convert to second person
|
593 |
response = response.replace("Elara", "You")
|
|
|
604 |
response = response.rstrip("?").rstrip(".") + "."
|
605 |
response = response.replace("...", ".")
|
606 |
|
607 |
+
# # Perform safety check before returning
|
608 |
+
# safe = is_safe(response)
|
609 |
+
# print(f"\nSafety Check Result: {'SAFE' if safe else 'UNSAFE'}")
|
610 |
+
# logger.info(f"Safety check result: {'SAFE' if safe else 'UNSAFE'}")
|
611 |
|
612 |
# if not safe:
|
613 |
# logging.warning("Unsafe content detected - blocking response")
|
|
|
681 |
chat_history = chat_history or []
|
682 |
chat_history.append((message, output))
|
683 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
684 |
# Update status displays
|
685 |
status_text, quest_text = update_game_status(current_state)
|
686 |
|
main.py
CHANGED
@@ -91,93 +91,3 @@ def main():
|
|
91 |
|
92 |
if __name__ == "__main__":
|
93 |
main()
|
94 |
-
|
95 |
-
|
96 |
-
# def main_loop(message, history):
|
97 |
-
# logging.info(f"main_loop called with message: {message}")
|
98 |
-
|
99 |
-
# # Initialize history if None
|
100 |
-
# history = history or []
|
101 |
-
|
102 |
-
# # Get AI response
|
103 |
-
# output = run_action(message, history, game_state)
|
104 |
-
|
105 |
-
# # Safety check
|
106 |
-
# safe = is_safe(output)
|
107 |
-
# if not safe:
|
108 |
-
# logging.error("Unsafe output detected")
|
109 |
-
# return "Invalid Output"
|
110 |
-
|
111 |
-
# # Format the output nicely
|
112 |
-
# output_lines = [output]
|
113 |
-
|
114 |
-
# # Handle movement and exploration
|
115 |
-
# if message.lower().startswith(("go", "move", "walk")):
|
116 |
-
# direction = message.split()[1]
|
117 |
-
# game_state["player"].move(direction, game_state["dungeon"])
|
118 |
-
# room_desc = game_state["dungeon"].get_room_description(
|
119 |
-
# game_state["dungeon"].current_room, game_state
|
120 |
-
# )
|
121 |
-
# output_lines.append(f"\n{room_desc}")
|
122 |
-
|
123 |
-
# # Handle NPC interactions
|
124 |
-
# elif message.lower().startswith("talk"):
|
125 |
-
# npc_name = message.split()[2]
|
126 |
-
# for npc in game_state["dungeon"].npcs:
|
127 |
-
# if npc.name.lower() == npc_name.lower():
|
128 |
-
# dialogue = game_state["player"].interact(npc, game_state)
|
129 |
-
# output_lines += f"\n{dialogue}"
|
130 |
-
|
131 |
-
# # Handle item interactions and inventory
|
132 |
-
# elif message.lower().startswith(("take", "pick up")):
|
133 |
-
# item_name = " ".join(message.split()[1:])
|
134 |
-
# for item in game_state["dungeon"].items:
|
135 |
-
# if item.name.lower() == item_name.lower():
|
136 |
-
# game_state["player"].inventory.append(item)
|
137 |
-
# game_state["dungeon"].items.remove(item)
|
138 |
-
# output += f"\nYou picked up {item.name}"
|
139 |
-
# item_desc = game_state["player"].examine(item, game_state)
|
140 |
-
# output_lines += f"\n{item_desc}"
|
141 |
-
|
142 |
-
# # Format final output
|
143 |
-
# final_output = "\n".join(output_lines)
|
144 |
-
# history.append((message, final_output))
|
145 |
-
# logging.info(f"main_loop output: {final_output}")
|
146 |
-
|
147 |
-
# return final_output, history
|
148 |
-
|
149 |
-
|
150 |
-
# def main():
|
151 |
-
# logging.info("Starting main function")
|
152 |
-
|
153 |
-
# try:
|
154 |
-
# # Initialize game state with error handling
|
155 |
-
# global game_state
|
156 |
-
# game_state = get_game_state(
|
157 |
-
# inventory={
|
158 |
-
# "cloth pants": 1,
|
159 |
-
# "cloth shirt": 1,
|
160 |
-
# "goggles": 1,
|
161 |
-
# "leather bound journal": 1,
|
162 |
-
# "gold": 5,
|
163 |
-
# }
|
164 |
-
# )
|
165 |
-
|
166 |
-
# # Verify game state initialization
|
167 |
-
# if not game_state:
|
168 |
-
# raise ValueError("Failed to initialize game state")
|
169 |
-
|
170 |
-
# # Create dungeon and populate with AI-generated content
|
171 |
-
# dungeon = Dungeon(10, 10)
|
172 |
-
# game_state["dungeon"] = dungeon
|
173 |
-
|
174 |
-
# # Create player and add to game state
|
175 |
-
# player = Player("Hero")
|
176 |
-
# game_state["player"] = player
|
177 |
-
|
178 |
-
# # Start game interface
|
179 |
-
# start_game(main_loop, True)
|
180 |
-
|
181 |
-
# except Exception as e:
|
182 |
-
# logging.error(f"Error in main: {str(e)}")
|
183 |
-
# raise
|
|
|
91 |
|
92 |
if __name__ == "__main__":
|
93 |
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|