Skip to content

Commit

Permalink
update and clean scr
Browse files Browse the repository at this point in the history
  • Loading branch information
prgrmcode committed Dec 31, 2024
1 parent 74a57f9 commit 82596d2
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 124 deletions.
68 changes: 34 additions & 34 deletions helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,8 @@ def load_world(filename):
- Never use ellipsis (...)
- Never include 'What would you like to do?' or similar prompts
- Always finish with one real response
- End the response with a period"""
- Never use 'Your turn' or or anything like conversation starting prompts
- Always end the response with a period"""


def get_game_state(inventory: Dict = None) -> Dict[str, Any]:
Expand Down Expand Up @@ -457,13 +458,17 @@ def update_game_inventory(game_state: Dict, story_text: str) -> str:
def extract_response_after_action(full_text: str, action: str) -> str:
"""Extract response text that comes after the user action line"""
try:
if not full_text: # Add null check
logger.error("Received empty response from model")
return "You look around carefully."

# Split into lines
lines = full_text.split("\n")

# Find index of line containing user action
action_line_index = -1
for i, line in enumerate(lines):
if f"user: {action}" in line:
if action.lower() in line.lower(): # More flexible matching
action_line_index = i
break

Expand All @@ -475,30 +480,23 @@ def extract_response_after_action(full_text: str, action: str) -> str:
# Clean up any remaining markers
response = response.split("user:")[0].strip()
response = response.split("system:")[0].strip()
response = response.split("assistant:")[0].strip()

return response
return response if response else "You look around carefully."

return ""
return "You look around carefully." # Default response

except Exception as e:
logger.error(f"Error extracting response: {e}")
return ""
return "You look around carefully."


def run_action(message: str, history: list, game_state: Dict) -> str:
"""Process game actions and generate responses with quest handling"""
try:
# Handle start game command
if message.lower() == "start game":
# # Generate initial quest
# initial_quest = {
# "title": "Investigate the Mist",
# "description": "Strange mists have been gathering around Ravenhurst. Investigate their source.",
# "exp_reward": 100,
# "status": "active",
# }
# game_state["current_quest"] = initial_quest
# Initialize first quest

initial_quest = generate_next_quest(game_state)
game_state["current_quest"] = initial_quest

Expand Down Expand Up @@ -557,6 +555,7 @@ def run_action(message: str, history: list, game_state: Dict) -> str:
# Convert messages to string format for pipeline
prompt = "\n".join([f"{msg['role']}: {msg['content']}" for msg in messages])

logger.info("Generating response...")
# Generate response
model_output = generator(
prompt,
Expand All @@ -567,13 +566,28 @@ def run_action(message: str, history: list, game_state: Dict) -> str:
repetition_penalty=1.2,
pad_token_id=tokenizer.eos_token_id,
)
# logger.info(f"Raw model output: {model_output}")

# Check for None response
if not model_output or not isinstance(model_output, list):
logger.error(f"Invalid model output: {model_output}")
print(f"Invalid model output: {model_output}")
return "You look around carefully."

if not model_output[0] or not isinstance(model_output[0], dict):
logger.error(f"Invalid response format: {type(model_output[0])}")
return "You look around carefully."

# Extract and clean response
full_response = model_output[0]["generated_text"]
print(f"full_response in run_action: {full_response}")
if not full_response:
logger.error("Empty response from model")
return "You look around carefully."

print(f"Full response in run_action: {full_response}")

response = extract_response_after_action(full_response, message)
print(f"response in run_action: {response}")
print(f"Extracted response in run_action: {response}")

# Convert to second person
response = response.replace("Elara", "You")
Expand All @@ -590,10 +604,10 @@ def run_action(message: str, history: list, game_state: Dict) -> str:
response = response.rstrip("?").rstrip(".") + "."
response = response.replace("...", ".")

# Perform safety check before returning
safe = is_safe(response)
print(f"\nSafety Check Result: {'SAFE' if safe else 'UNSAFE'}")
logger.info(f"Safety check result: {'SAFE' if safe else 'UNSAFE'}")
# # Perform safety check before returning
# safe = is_safe(response)
# print(f"\nSafety Check Result: {'SAFE' if safe else 'UNSAFE'}")
# logger.info(f"Safety check result: {'SAFE' if safe else 'UNSAFE'}")

# if not safe:
# logging.warning("Unsafe content detected - blocking response")
Expand Down Expand Up @@ -667,20 +681,6 @@ def chat_response(message: str, chat_history: list, current_state: dict) -> tupl
chat_history = chat_history or []
chat_history.append((message, output))

# # Create status text
# status_text = "Health: 100/100\nLevel: 1\nExp: 0/100"
# if current_state.get("player"):
# status_text = (
# f"Health: {current_state['player'].health}/{current_state['player'].max_health}\n"
# f"Level: {current_state['player'].level}\n"
# f"Exp: {current_state['player'].exp}/{current_state['player'].exp_to_level}"
# )

# quest_text = "No active quest"
# if current_state.get("current_quest"):
# quest = current_state["current_quest"]
# quest_text = f"{quest['title']}\n{quest['description']}"

# Update status displays
status_text, quest_text = update_game_status(current_state)

Expand Down
90 changes: 0 additions & 90 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,93 +91,3 @@ def main():

if __name__ == "__main__":
main()


# def main_loop(message, history):
# logging.info(f"main_loop called with message: {message}")

# # Initialize history if None
# history = history or []

# # Get AI response
# output = run_action(message, history, game_state)

# # Safety check
# safe = is_safe(output)
# if not safe:
# logging.error("Unsafe output detected")
# return "Invalid Output"

# # Format the output nicely
# output_lines = [output]

# # Handle movement and exploration
# if message.lower().startswith(("go", "move", "walk")):
# direction = message.split()[1]
# game_state["player"].move(direction, game_state["dungeon"])
# room_desc = game_state["dungeon"].get_room_description(
# game_state["dungeon"].current_room, game_state
# )
# output_lines.append(f"\n{room_desc}")

# # Handle NPC interactions
# elif message.lower().startswith("talk"):
# npc_name = message.split()[2]
# for npc in game_state["dungeon"].npcs:
# if npc.name.lower() == npc_name.lower():
# dialogue = game_state["player"].interact(npc, game_state)
# output_lines += f"\n{dialogue}"

# # Handle item interactions and inventory
# elif message.lower().startswith(("take", "pick up")):
# item_name = " ".join(message.split()[1:])
# for item in game_state["dungeon"].items:
# if item.name.lower() == item_name.lower():
# game_state["player"].inventory.append(item)
# game_state["dungeon"].items.remove(item)
# output += f"\nYou picked up {item.name}"
# item_desc = game_state["player"].examine(item, game_state)
# output_lines += f"\n{item_desc}"

# # Format final output
# final_output = "\n".join(output_lines)
# history.append((message, final_output))
# logging.info(f"main_loop output: {final_output}")

# return final_output, history


# def main():
# logging.info("Starting main function")

# try:
# # Initialize game state with error handling
# global game_state
# game_state = get_game_state(
# inventory={
# "cloth pants": 1,
# "cloth shirt": 1,
# "goggles": 1,
# "leather bound journal": 1,
# "gold": 5,
# }
# )

# # Verify game state initialization
# if not game_state:
# raise ValueError("Failed to initialize game state")

# # Create dungeon and populate with AI-generated content
# dungeon = Dungeon(10, 10)
# game_state["dungeon"] = dungeon

# # Create player and add to game state
# player = Player("Hero")
# game_state["player"] = player

# # Start game interface
# start_game(main_loop, True)

# except Exception as e:
# logging.error(f"Error in main: {str(e)}")
# raise

0 comments on commit 82596d2

Please sign in to comment.