Module and Parameter Management¶
Overview¶
AgentSociety2 provides a complete module registration and parameter management system, supporting the discovery, registration, query and verification of built-in modules and custom modules.
一、模块管理¶
1.1 Module type¶
AgentSociety2 supports two types of modules:
Built-in Modules: located under
agentsociety2/contrib/Environment module:
contrib/env/DirectoryAgent module:
contrib/agent/DirectoryCore Agent:
PersonAgentout ofagent/person.py
Custom Modules: located under workspace
custom/Agent:
custom/agents/DirectoryEnvironment module:
custom/envs/Directory
1.2 Module registration system¶
Core components¶
agentsociety2/registry/
├── __init__.py # 导出所有公共接口
├── base.py # ModuleRegistry 核心类
├── modules.py # 自动发现和注册逻辑
└── models.py # Pydantic 配置模型
ModuleRegistry (singleton mode)¶
ModuleRegistry is the core of module registration, using singleton mode:
from agentsociety2.registry import get_registry
registry = get_registry()
Main methods:
Method |
Description |
|---|---|
|
Register environment module |
|
Register Agent |
|
Get environment module class |
|
Get Agent class |
|
List all environment modules |
|
List all Agents |
|
Clear all custom modules |
|
Get module details |
1.3 Automatic discovery mechanism¶
Built-in module automatic discovery¶
The system will automatically discover and register the built-in module when importing agentsociety2.registry:
# modules.py 中的自动发现逻辑
def _discover_contrib_env_modules() -> Dict[str, Type[EnvBase]]:
"""使用 pkgutil 遍历 contrib.env 包"""
# 自动发现所有 EnvBase 子类
# 类名转换:SimpleSocialSpace -> simple_social_space
def _discover_contrib_agents() -> Dict[str, Type[AgentBase]]:
"""使用 pkgutil 遍历 contrib.agent 包"""
# 自动发现所有 AgentBase 子类
Custom module scan¶
from agentsociety2.registry import scan_and_register_custom_modules
from pathlib import Path
scan_result = scan_and_register_custom_modules(
workspace_path=Path("/path/to/workspace"),
registry=get_registry(),
)
# 返回:{"agents": [...], "envs": [...], "errors": [...]}
Scanning rules:
Scan
custom/agents/andcustom/envs/directoriesSkip
examples/subdirectories and files starting with__Automatically import and register discovered classes
Custom module tag
_is_custom = True
1.4 Module naming rules¶
Class name |
Module type identification |
|---|---|
|
|
|
|
|
|
|
|
1.5 Module query interface¶
API interface¶
GET /api/v1/custom/classes?workspace_path=/path&include_custom=true
Return example:
{
"success": true,
"env_modules": {
"reputation_game_env": {
"type": "reputation_game_env",
"class_name": "ReputationGameEnv",
"description": "...",
"is_custom": false,
"has_prefill": true
}
},
"agents": {
"llm_donor_agent": {
"type": "llm_donor_agent",
"class_name": "LLMDonorAgent",
"description": "...",
"is_custom": false,
"has_prefill": false
}
},
"env_module_count": 16,
"agent_count": 7
}
二、参数管理¶
2.1 Parameter sources¶
Parameters in AgentSociety2 come from three sources:
Class definition parameters: extracted from the module class
__init__signatureGenerated parameters: configuration created by the code generation process
Prefill Params: user-defined default parameters
2.2 Parameter acquisition process¶
┌─────────────────────┐
│ 请求模块参数 │
└──────────┬──────────┘
│
▼
┌─────────────────────┐
│ 获取模块类信息 │
│ (类签名、文档) │
└──────────┬──────────┘
│
▼
┌─────────────────────┐
│ 加载预填充参数 │
│ (.agentsociety/ │
│ prefill_params.json)│
└──────────┬──────────┘
│
▼
┌─────────────────────┐
│ 合并参数 │
│ (prefill 覆盖默认) │
└──────────┬──────────┘
│
▼
┌─────────────────────┐
│ 返回完整参数信息 │
└─────────────────────┘
2.3 Prefill Params¶
File location¶
<workspace>/.agentsociety/prefill_params.json
File structure¶
{
"version": "1.0",
"env_modules": {
"reputation_game_env": {
"config": {
"Z": 100,
"BENEFIT": 5,
"COST": 1,
"norm_type": "stern_judging"
}
},
"social_media_space": {
"num_users": 1000
}
},
"agents": {
"person_agent": {
"profile": {
"custom_fields": {
"learning_frequency": 0.1,
"risk_tolerance": 0.5
}
}
}
}
}
API interface¶
# 获取所有预填充参数
GET /api/v1/prefill-params?workspace_path=/path
# 获取特定类的预填充参数
GET /api/v1/prefill-params/env_module/reputation_game_env?workspace_path=/path
GET /api/v1/prefill-params/agent/person_agent?workspace_path=/path
2.4 Parameter verification¶
Validation script¶
extension/skills/agentsociety-experiment-config/scripts/validate_config.py is used for end-to-end verification of the generated configuration.
Validation content:
Loading
init_config.jsonParse
SIM_SETTINGS.jsonInstantiate each environment module class (strict verification)
Instantiate each Agent class (strict validation)
Report detailed errors for initialization failures
三、配置模型¶
3.1 Core configuration model¶
# 环境模块配置
class EnvModuleConfig(BaseModel):
module_type: str # 模块类型标识
kwargs: Dict[str, Any] # 初始化参数
# Agent 配置
class AgentConfig(BaseModel):
agent_id: int # Agent ID
agent_type: str # Agent 类型
kwargs: Dict[str, Any] # 初始化参数(包含 id、profile 等)
# 初始化配置
class InitConfig(BaseModel):
env_modules: List[EnvModuleConfig]
agents: List[AgentConfig]
3.2 Create instance request¶
class CreateInstanceRequest(BaseModel):
instance_id: str
env_modules: List[EnvModuleInitConfig]
agents: List[AgentInitConfig]
start_t: datetime
tick: int = 600
四、自定义模块开发¶
4.1 Directory structure¶
<workspace>/
├── custom/
│ ├── agents/
│ │ └── my_agent.py # 自定义 Agent
│ └── envs/
│ └── my_env.py # 自定义环境模块
└── .agentsociety/
├── agent_classes/ # 生成的 Agent 类 JSON
└── env_modules/ # 生成的环境模块 JSON
4.2 Custom Agent Example¶
# custom/agents/my_agent.py
from agentsociety2.agent.base import AgentBase
from pathlib import Path
from typing import Any
class MyCustomAgent(AgentBase):
"""我的自定义 Agent"""
async def restore(self, workspace_path: Path, service_proxy: Any) -> None:
await super().restore(workspace_path, service_proxy)
self.custom_param = self.config.get("custom_param", "default")
async def ask(self, message: str, readonly: bool = True, *, t=None) -> str:
return await self.run_react_loop(
tick=0,
t=t,
observations=[],
question=message,
readonly=readonly,
)
async def step(self, tick: int, t) -> str:
return await self.run_react_loop(tick=tick, t=t, observations=[])
4.3 Example of custom environment module¶
# custom/envs/my_env.py
from agentsociety2.env.base import EnvBase
class MyCustomEnv(EnvBase):
"""我的自定义环境模块"""
def __init__(
self,
config_param: int = 100, # 自定义参数
):
super().__init__()
self.config_param = config_param
@tool(readonly=True, kind="observe")
def get_state(self, agent_id: int) -> str:
"""返回环境状态"""
return f"Current state: {self.config_param}"
async def step(self, tick: int, t) -> None:
"""环境每步推进"""
self.t = t
# 若模块带动态态且希望支持 --resume,可覆盖 to_workspace/restore:
# async def to_workspace(self, workspace_path=None) -> None: ...
# async def restore(self, workspace_path) -> bool: ...
# 见 docs/env_modules.rst 的「状态持久化与 resume」
4.4 Scan and register¶
# 扫描自定义模块
curl -X POST http://localhost:8001/api/v1/custom/scan \
-d '{"workspace_path": "/path/to/workspace"}'
# 重新扫描(清除旧的自定义模块)
curl -X POST http://localhost:8001/api/v1/custom/rescan \
-d '{"workspace_path": "/path/to/workspace"}'
五、使用示例¶
5.1 Get module information¶
from agentsociety2.registry import get_registry
registry = get_registry()
# 获取环境模块信息
env_info = registry.get_module_info("reputation_game_env", "env_module")
print(env_info)
# {
# "success": True,
# "type": "reputation_game_env",
# "class_name": "ReputationGameEnv",
# "description": "...",
# "parameters": {...},
# "is_custom": False
# }
# 获取 Agent 信息
agent_info = registry.get_module_info("person_agent", "agent")
5.2 Instantiating modules¶
from agentsociety2.registry import get_env_module_class
# 获取类
EnvClass = get_env_module_class("reputation_game_env")
# 实例化
env_instance = EnvClass(config={"Z": 100, "BENEFIT": 5})
5.3 List all modules¶
from agentsociety2.registry import (
get_registered_env_modules,
get_registered_agent_modules,
)
# 列出环境模块
for module_type, module_class in get_registered_env_modules():
print(f"{module_type}: {module_class.__name__}")
# 列出 Agent
for agent_type, agent_class in get_registered_agent_modules():
print(f"{agent_type}: {agent_class.__name__}")
5.4 Using prefilled parameters¶
import json
from pathlib import Path
# 读取预填充参数
prefill_file = Path("/workspace/.agentsociety/prefill_params.json")
prefill_params = json.loads(prefill_file.read_text())
# 获取特定模块的预填充参数
env_prefill = prefill_params["env_modules"].get("reputation_game_env", {})
print(env_prefill) # {"config": {"Z": 100, ...}}
六、总结¶
AgentSociety2’s module and parameter management system provides:
Automatic discovery mechanism: Automatically discover built-in and custom modules
Unified registry: ModuleRegistry in singleton mode
Multi-source parameter management: Class definition, generated parameters, pre-filled parameters
Flexible query interface: Command line script and API interface
Strict validation: Verify configuration validity through instantiation