78 lines
2.8 KiB
Python
78 lines
2.8 KiB
Python
import yaml
|
|
from pathlib import Path
|
|
from typing import List, Dict
|
|
|
|
from living_agents import Character
|
|
|
|
|
|
# def load_characters(characters_dir: str = "characters") -> List[Tuple[Character, List[str]]]:
|
|
def load_characters(characters_dir: str = "characters") -> Dict[Character, List[str]]:
|
|
"""
|
|
Load all character YAML files from the specified directory.
|
|
|
|
Args:
|
|
characters_dir (str): Path to the directory containing character YAML files
|
|
|
|
Returns:
|
|
List[Character]: List of Character objects loaded from YAML files
|
|
|
|
Raises:
|
|
FileNotFoundError: If the characters directory doesn't exist
|
|
yaml.YAMLError: If there's an error parsing a YAML file
|
|
ValueError: If a YAML file is missing required fields
|
|
"""
|
|
characters = {}
|
|
characters_path = Path(characters_dir)
|
|
|
|
if not characters_path.exists():
|
|
raise FileNotFoundError(f"Characters directory '{characters_dir}' not found")
|
|
|
|
if not characters_path.is_dir():
|
|
raise ValueError(f"'{characters_dir}' is not a directory")
|
|
|
|
# Find all YAML files in the directory
|
|
yaml_files = list(characters_path.glob("*.yaml")) + list(characters_path.glob("*.yml"))
|
|
|
|
if not yaml_files:
|
|
print(f"No YAML files found in '{characters_dir}'")
|
|
return characters
|
|
|
|
for yaml_file in yaml_files:
|
|
try:
|
|
with open(yaml_file, 'r', encoding='utf-8') as file:
|
|
data = yaml.safe_load(file)
|
|
|
|
if data is None:
|
|
print(f"Warning: Empty YAML file '{yaml_file.name}', skipping")
|
|
continue
|
|
|
|
# Validate required fields
|
|
required_fields = ['name', 'age', 'personality', 'occupation', 'location']
|
|
missing_fields = [field for field in required_fields if field not in data]
|
|
|
|
if missing_fields:
|
|
raise ValueError(f"File '{yaml_file.name}' missing required fields: {missing_fields}")
|
|
|
|
# Create Character object
|
|
character = Character(
|
|
name=data['name'],
|
|
age=data['age'],
|
|
personality=data['personality'],
|
|
occupation=data['occupation'],
|
|
location=data['location'],
|
|
relationships=data.get('relationships', {}),
|
|
goals=data.get('goals', [])
|
|
)
|
|
initialize_memories = data.get('initialize_memories', [])
|
|
|
|
characters[character] = initialize_memories
|
|
# characters.append((character, initialize_memories))
|
|
print(f"Loaded character: {character.name} from {yaml_file.name}")
|
|
|
|
except yaml.YAMLError as e:
|
|
print(f"Error parsing YAML file '{yaml_file.name}': {e}")
|
|
except Exception as e:
|
|
print(f"Error loading character from '{yaml_file.name}': {e}")
|
|
|
|
return characters
|