11"""
22Agent import system for the AgentFarm DB to Memory System converter.
3+
4+ This module provides functionality to import agents from the AgentFarm database into the memory system.
5+ It handles the conversion of database records into memory system compatible metadata, including:
6+
7+ - Agent identification and basic information
8+ - Position and state data
9+ - Resource and health metrics
10+ - Genome and generation tracking
11+ - Action weights and behavioral data
12+
13+ The system supports multiple import modes:
14+ - Full: Import all agents from the database
15+ - Incremental: Import only new or modified agents
16+ - Selective: Import specific agents by ID
17+
18+ Features:
19+ - Batch processing for efficient memory usage
20+ - Configurable error handling (fail/log/skip)
21+ - Validation of required fields
22+ - Metadata preservation and transformation
23+ - Flexible query filtering
24+
25+ Example:
26+ ```python
27+ from converter.agent_import import AgentImporter
28+ from converter.config import ConverterConfig
29+ from converter.db import DatabaseManager
30+
31+ config = ConverterConfig(batch_size=100, validate=True)
32+ db_manager = DatabaseManager()
33+ importer = AgentImporter(db_manager, config)
34+ agents = importer.import_agents()
35+ ```
36+
37+ Note:
38+ The system assumes the presence of specific fields in the database records
39+ and will raise validation errors if required fields are missing.
340"""
441
542import logging
643from dataclasses import dataclass
7- from typing import Any , Dict , List
44+ from typing import Any , Dict , Generator , List , Optional
45+
46+ from sqlalchemy .orm import Query , Session
847
948from .config import ConverterConfig
1049from .db import DatabaseManager
@@ -31,17 +70,30 @@ class AgentImporter:
3170 metadata preservation, and error handling.
3271 """
3372
34- def __init__ (self , db_manager : DatabaseManager , config : ConverterConfig ):
73+ def __init__ (self , db_manager : DatabaseManager , config : ConverterConfig ) -> None :
3574 """
3675 Initialize the agent importer.
3776
3877 Args:
3978 db_manager: Database manager instance
4079 config: Converter configuration
80+
81+ Raises:
82+ ValueError: If configuration is invalid
4183 """
4284 self .db_manager = db_manager
4385 self .config = config
4486
87+ # Validate configuration
88+ if config .batch_size <= 0 :
89+ raise ValueError ("Batch size must be greater than 0" )
90+
91+ if config .error_handling not in ["fail" , "log" , "skip" ]:
92+ raise ValueError ("Invalid error handling mode" )
93+
94+ if config .import_mode not in ["full" , "incremental" , "selective" ]:
95+ raise ValueError ("Invalid import mode" )
96+
4597 def import_agents (self ) -> List [AgentMetadata ]:
4698 """
4799 Import agents from the database.
@@ -68,7 +120,7 @@ def import_agents(self) -> List[AgentMetadata]:
68120
69121 return agents [0 :1 ] #! TODO: Remove this
70122
71- def _get_agent_query (self , session ) :
123+ def _get_agent_query (self , session : Session ) -> Query :
72124 """Get the appropriate agent query based on import mode."""
73125 query = session .query (self .db_manager .AgentModel )
74126
@@ -83,7 +135,7 @@ def _get_agent_query(self, session):
83135
84136 return query
85137
86- def _batch_query (self , query ) :
138+ def _batch_query (self , query : Query ) -> Generator [ List [ Any ], None , None ] :
87139 """Process query in batches."""
88140 offset = 0
89141 while True :
@@ -93,7 +145,7 @@ def _batch_query(self, query):
93145 yield batch
94146 offset += self .config .batch_size
95147
96- def _import_agent (self , agent ) -> AgentMetadata :
148+ def _import_agent (self , agent : Any ) -> AgentMetadata :
97149 """
98150 Import a single agent.
99151
@@ -113,16 +165,15 @@ def _import_agent(self, agent) -> AgentMetadata:
113165 # Create agent metadata
114166 metadata = AgentMetadata (
115167 agent_id = agent .agent_id ,
116- # Use agent_id as the name if agent doesn't have a name attribute
117- name = getattr (agent , "name" , f"Agent-{ agent .agent_id } " ),
168+ name = f"Agent-{ agent .agent_id } " ,
118169 metadata = self ._extract_agent_metadata (agent ),
119170 created_at = str (agent .birth_time ),
120171 updated_at = str (agent .death_time or agent .birth_time ),
121172 )
122173
123174 return metadata
124175
125- def _validate_agent (self , agent ) :
176+ def _validate_agent (self , agent : Any ) -> None :
126177 """
127178 Validate an agent.
128179
@@ -135,7 +186,7 @@ def _validate_agent(self, agent):
135186 if not agent .agent_id :
136187 raise ValueError ("Agent must have an ID" )
137188
138- def _extract_agent_metadata (self , agent ) -> Dict [str , Any ]:
189+ def _extract_agent_metadata (self , agent : Any ) -> Dict [str , Any ]:
139190 """
140191 Extract metadata from an agent.
141192
@@ -156,7 +207,7 @@ def _extract_agent_metadata(self, agent) -> Dict[str, Any]:
156207 "action_weights" : agent .action_weights ,
157208 }
158209
159- def _handle_import_error (self , error : Exception , agent : Any ):
210+ def _handle_import_error (self , error : Exception , agent : Any ) -> None :
160211 """
161212 Handle agent import error based on configuration.
162213
0 commit comments