Skip to content

Commit f5c561c

Browse files
committed
style: format code with black
- Run black formatter on all Python files - Fix code formatting to pass CI lint checks - 12 files reformatted to comply with Black style guide
1 parent 5c7b5ab commit f5c561c

12 files changed

Lines changed: 69 additions & 85 deletions

File tree

personaflow/__init__.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,4 @@
22
from .core.memory import Memory, MemoryManager, MemoryConfig
33
from .core.system import PersonaSystem
44

5-
__all__ = [
6-
'Character',
7-
'Memory',
8-
'MemoryManager',
9-
'MemoryConfig',
10-
'PersonaSystem'
11-
]
5+
__all__ = ["Character", "Memory", "MemoryManager", "MemoryConfig", "PersonaSystem"]

personaflow/core/__init__.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,4 @@
22
from .memory import Memory, MemoryConfig, MemoryManager
33
from .system import PersonaSystem
44

5-
__all__ = [
6-
'Character',
7-
'Memory',
8-
'MemoryConfig',
9-
'MemoryManager',
10-
'PersonaSystem'
11-
]
5+
__all__ = ["Character", "Memory", "MemoryConfig", "MemoryManager", "PersonaSystem"]

personaflow/core/character.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ def __init__(
1515
raise ValueError("Character name cannot be empty")
1616
if not prompt:
1717
raise ValueError("Character prompt cannot be empty")
18-
18+
1919
self.name = name
2020
self.prompt = prompt
2121
self.background = background or {}
@@ -64,9 +64,9 @@ def to_dict(self) -> Dict[str, Any]:
6464
def from_dict(cls, data: Dict[str, Any]) -> "Character":
6565
"""Create character from dictionary"""
6666
character = cls(
67-
name=data["name"],
68-
prompt=data["prompt"],
69-
background=data.get("background", {})
67+
name=data["name"],
68+
prompt=data["prompt"],
69+
background=data.get("background", {}),
7070
)
7171
# Restore memory_manager from dict if present
7272
if "memory_manager" in data:

personaflow/core/memory.py

Lines changed: 23 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -2,40 +2,41 @@
22
from datetime import datetime
33
from dataclasses import dataclass, asdict
44

5+
56
@dataclass
67
class Memory:
78
"""Structure for storing individual memory entries"""
9+
810
timestamp: str
911
type: str # 'interaction', 'event', 'system', etc.
1012
content: Dict[str, Any]
1113
metadata: Optional[Dict[str, Any]] = None
1214
character_name: str = ""
1315

16+
1417
@dataclass
1518
class MemoryConfig:
1619
"""Configuration for memory management"""
20+
1721
max_memories: int = 1000
1822
summary_threshold: int = 10
1923
auto_summarize: bool = True
2024

25+
2126
class MemoryManager:
22-
def __init__(
23-
self,
24-
character_name: str,
25-
config: Optional[Dict[str, Any]] = None
26-
):
27+
def __init__(self, character_name: str, config: Optional[Dict[str, Any]] = None):
2728
if not character_name or not character_name.strip():
2829
raise ValueError("Character name cannot be empty")
29-
30+
3031
self.character_name = character_name
3132
self.config = MemoryConfig(**config) if config else MemoryConfig()
32-
33+
3334
# Validate config values
3435
if self.config.max_memories <= 0:
3536
raise ValueError("max_memories must be greater than 0")
3637
if self.config.summary_threshold <= 0:
3738
raise ValueError("summary_threshold must be greater than 0")
38-
39+
3940
self.memories: List[Memory] = []
4041
self.summarized_memories: List[Memory] = []
4142
self._last_accessed = datetime.now()
@@ -44,28 +45,26 @@ def add_memory(
4445
self,
4546
content: Dict[str, Any],
4647
memory_type: str = "interaction",
47-
metadata: Optional[Dict[str, Any]] = None
48+
metadata: Optional[Dict[str, Any]] = None,
4849
):
4950
memory = Memory(
5051
timestamp=datetime.now().isoformat(),
5152
type=memory_type,
5253
content=content,
5354
metadata=metadata or {},
54-
character_name=self.character_name
55+
character_name=self.character_name,
5556
)
5657

5758
self.memories.append(memory)
5859
self._manage_memory_size()
5960

6061
def get_memories(
61-
self,
62-
limit: Optional[int] = None,
63-
memory_types: Optional[List[str]] = None
62+
self, limit: Optional[int] = None, memory_types: Optional[List[str]] = None
6463
) -> List[Memory]:
6564
"""Get relevant memories based on configuration"""
6665
if limit is not None and limit < 0:
6766
raise ValueError("Memory limit cannot be negative")
68-
67+
6968
memories = self.memories
7069

7170
if memory_types:
@@ -83,26 +82,26 @@ def _manage_memory_size(self):
8382
self._summarize_old_memories()
8483
else:
8584
# Keep most recent memories
86-
self.memories = self.memories[-self.config.max_memories:]
85+
self.memories = self.memories[-self.config.max_memories :]
8786

8887
def _summarize_old_memories(self):
8988
"""Summarize old memories to maintain important information"""
90-
memories_to_summarize = self.memories[:-self.config.max_memories]
91-
89+
memories_to_summarize = self.memories[: -self.config.max_memories]
90+
9291
# Only create summary if there are memories to summarize
9392
if memories_to_summarize:
9493
summary = Memory(
9594
timestamp=datetime.now().isoformat(),
9695
type="summary",
9796
content={
9897
"period": f"{memories_to_summarize[0].timestamp} to {memories_to_summarize[-1].timestamp}",
99-
"summary": f"Summary of {len(memories_to_summarize)} memories"
98+
"summary": f"Summary of {len(memories_to_summarize)} memories",
10099
},
101-
character_name=self.character_name
100+
character_name=self.character_name,
102101
)
103102
self.summarized_memories.append(summary)
104-
105-
self.memories = self.memories[-self.config.max_memories:]
103+
104+
self.memories = self.memories[-self.config.max_memories :]
106105

107106
def to_dict(self) -> Dict[str, Any]:
108107
"""Convert memory manager to dictionary"""
@@ -111,16 +110,13 @@ def to_dict(self) -> Dict[str, Any]:
111110
"config": asdict(self.config),
112111
"memories": [asdict(m) for m in self.memories],
113112
"summarized_memories": [asdict(m) for m in self.summarized_memories],
114-
"last_accessed": self._last_accessed.isoformat()
113+
"last_accessed": self._last_accessed.isoformat(),
115114
}
116115

117116
@classmethod
118-
def from_dict(cls, data: Dict[str, Any]) -> 'MemoryManager':
117+
def from_dict(cls, data: Dict[str, Any]) -> "MemoryManager":
119118
"""Create memory manager from dictionary"""
120-
manager = cls(
121-
character_name=data["character_name"],
122-
config=data["config"]
123-
)
119+
manager = cls(character_name=data["character_name"], config=data["config"])
124120
manager.memories = [Memory(**m) for m in data["memories"]]
125121
manager.summarized_memories = [Memory(**m) for m in data["summarized_memories"]]
126122
manager._last_accessed = datetime.fromisoformat(data["last_accessed"])

personaflow/core/system.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def add_interaction(
4545
"""Add interaction to character's memory"""
4646
if character_name not in self.characters:
4747
raise KeyError(f"Character {character_name} not found")
48-
48+
4949
character = self.characters[character_name]
5050
character.add_memory(
5151
content=content, memory_type=memory_type, metadata=metadata

personaflow/utils/__init__.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
from .prompt_manager import PromptTemplate, PromptManager
2-
from .validators import validate_memory_content, validate_prompt_template, validate_memory_config
2+
from .validators import (
3+
validate_memory_content,
4+
validate_prompt_template,
5+
validate_memory_config,
6+
)
37
from .serializer import Serializer
48
from .logger import Logger
59

610
__all__ = [
7-
'PromptTemplate',
8-
'PromptManager',
9-
'validate_memory_content',
10-
'validate_prompt_template',
11-
'validate_memory_config',
12-
'Serializer',
13-
'Logger'
11+
"PromptTemplate",
12+
"PromptManager",
13+
"validate_memory_content",
14+
"validate_prompt_template",
15+
"validate_memory_config",
16+
"Serializer",
17+
"Logger",
1418
]

personaflow/utils/logger.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
import logging
22
from typing import Optional
33

4+
45
class Logger:
56
def __init__(
6-
self,
7-
name: str,
8-
level: int = logging.INFO,
9-
log_file: Optional[str] = None
7+
self, name: str, level: int = logging.INFO, log_file: Optional[str] = None
108
):
119
self.logger = logging.getLogger(name)
1210
self.logger.setLevel(level)
@@ -16,7 +14,7 @@ def __init__(
1614
# Console handler
1715
console_handler = logging.StreamHandler()
1816
formatter = logging.Formatter(
19-
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
17+
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
2018
)
2119
console_handler.setFormatter(formatter)
2220
self.logger.addHandler(console_handler)

personaflow/utils/serializer.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,13 @@
22
from typing import Dict, Any
33
from datetime import datetime
44

5+
56
class Serializer:
67
@staticmethod
78
def to_json(data: Dict[str, Any], file_path: str):
89
"""Serialize data to JSON file"""
910
try:
10-
with open(file_path, 'w') as f:
11+
with open(file_path, "w") as f:
1112
json.dump(data, f, indent=2)
1213
except (IOError, TypeError) as e:
1314
raise IOError(f"Failed to serialize data to {file_path}: {str(e)}")
@@ -16,7 +17,7 @@ def to_json(data: Dict[str, Any], file_path: str):
1617
def from_json(file_path: str) -> Dict[str, Any]:
1718
"""Deserialize data from JSON file"""
1819
try:
19-
with open(file_path, 'r') as f:
20+
with open(file_path, "r") as f:
2021
return json.load(f)
2122
except (IOError, json.JSONDecodeError) as e:
2223
raise IOError(f"Failed to deserialize data from {file_path}: {str(e)}")

personaflow/utils/validators.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from string import Template
33
import json
44

5+
56
def validate_prompt_template(template: str) -> bool:
67
"""Validate prompt template syntax"""
78
try:
@@ -10,25 +11,27 @@ def validate_prompt_template(template: str) -> bool:
1011
except ValueError:
1112
return False
1213

14+
1315
def validate_memory_content(content: Dict[str, Any]) -> bool:
1416
"""Validate memory content structure and types"""
1517
if not isinstance(content, dict):
1618
return False
17-
19+
1820
# Memory content just needs to be a non-empty dictionary
1921
# Different memory types can have different structures
2022
return len(content) > 0
2123

24+
2225
def validate_memory_config(config: Dict[str, Any]) -> bool:
2326
"""Validate memory configuration structure and types"""
2427
if not isinstance(config, dict):
2528
return False
2629

2730
# Define valid fields and their types
2831
valid_fields = {
29-
'max_memories': int,
30-
'summary_threshold': int,
31-
'auto_summarize': bool
32+
"max_memories": int,
33+
"summary_threshold": int,
34+
"auto_summarize": bool,
3235
}
3336

3437
# Check that all provided fields are valid and have correct types
@@ -37,5 +40,5 @@ def validate_memory_config(config: Dict[str, Any]) -> bool:
3740
return False
3841
if not isinstance(value, valid_fields[field]):
3942
return False
40-
43+
4144
return True

tests/test_character.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
import pytest
22
from personaflow.core.character import Character
33

4+
45
class TestCharacter:
56
@pytest.fixture
67
def character(self):
78
return Character(
89
name="test_char",
910
prompt="You are a test character",
10-
background={"role": "test"}
11+
background={"role": "test"},
1112
)
1213

1314
def test_character_creation(self, character):

0 commit comments

Comments
 (0)