Backend API Module¶
This module provides FastAPI backend services.
FastAPI application¶
FastAPI backend service for AI Social Scientist VSCode extension
Associated files: - @packages/agentsociety2/agentsociety2/backend/run.py - Service startup script - @extension/src/services/backendManager.ts - VSCode plug-in backend process management - @extension/src/apiClient.ts - VSCode plug-in API client
Route registration: - @packages/agentsociety2/agentsociety2/backend/routers/prefill_params.py - /api/v1/prefill-params - @packages/agentsociety2/agentsociety2/backend/routers/experiments.py - /api/v1/experiments - @packages/agentsociety2/agentsociety2/backend/routers/replay.py - /api/v1/replay - @packages/agentsociety2/agentsociety2/backend/routers/custom.py - /api/v1/custom - @packages/agentsociety2/agentsociety2/backend/routers/modules.py - /api/v1/modules - @packages/agentsociety2/agentsociety2/backend/routers/agent_skills.py - /api/v1/agent-skills
- agentsociety2.backend.app.lifespan(app)[source]¶
FastAPI application lifecycle management (start/shutdown hooks).
routing module¶
Prefill Parameter Routes¶
Read-only API routes for querying prefill parameters.
Related files: - @packages/agentsociety2/agentsociety2/backend/app.py - main application that registers this route (/api/v1/prefill-params) - @extension/src/prefillParamsViewProvider.ts - VSCode extension frontend that calls this API - @extension/src/webview/prefillParams/ - frontend display components
Reads the following file: - {workspace}/.agentsociety/prefill_params.json - prefill parameter configuration
- async agentsociety2.backend.routers.prefill_params.get_prefill_params(workspace_path=Query(PydanticUndefined))[source]¶
Get global prefill parameters
Returns the prefill parameter configuration for all classes in the workspace, including Agents and environment modules.
- Parameters:
workspace_path (str) – Path to the workspace root directory.
- Returns:
Dict[str, Any]: Prefill parameter configuration, including: - success: whether the request succeeded - data: parameter data, structured as: - version: configuration version - env_modules: dictionary of prefill parameters for environment modules - agents: dictionary of prefill parameters for Agents
- Raises:
HTTPException – 500 - Failed to read the configuration file
- Return type:
Note
Returns an empty configuration structure if the configuration file does not exist.
- async agentsociety2.backend.routers.prefill_params.get_class_prefill_params(class_kind=Path(PydanticUndefined), class_name=Path(PydanticUndefined), workspace_path=Query(PydanticUndefined))[source]¶
Get prefill parameters for a specific class
Returns the prefill parameter configuration for the specified class, either an Agent or an environment module.
- Parameters:
- Returns:
Dict[str, Any]: Prefill parameters for the class, including: - success: whether the request succeeded - class_kind: class kind - class_name: class name - params: prefill parameter dictionary for the class, or an empty dictionary when no configuration exists
- Raises:
HTTPException – 500 - Failed to read the configuration file
- Return type:
Example
GET /api/v1/prefill-params/env_module/mobility_space?workspace_path=/path/to/workspace
Experiment Routes¶
Experiment Data API
Provides experiment basic information and artifact queries. The new replay write format is run/replay/_schema.json plus sharded JSONL; experiment statistics are read through agentsociety2.storage.ReplayReader and no longer access sqlite.db.
- class agentsociety2.backend.routers.experiments.ExperimentInfo(*, experiment_id, hypothesis_id, status, start_time=None, end_time=None, agent_count, step_count)[source]¶
Experiment Information
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- async agentsociety2.backend.routers.experiments.get_experiment_info(hypothesis_id, experiment_id, workspace_path=Query(PydanticUndefined))[source]¶
Get basic experiment information
Returns the basic information for the specified experiment, including status, timestamps, Agent count, and related metadata.
Replay Routes¶
Replay data query API for simulation playback.
Related files: - @extension/src/replayWebviewProvider.ts - VSCode Replay Webview provider - @extension/src/webview/replay/ - VSCode Replay Webview React app
- class agentsociety2.backend.routers.replay.ExperimentInfo(*, hypothesis_id, experiment_id, total_steps, start_time, end_time, agent_count)[source]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.replay.TimelinePoint(*, step, t)[source]¶
- t: datetime¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.replay.AgentProfile(*, id, name, profile=<factory>)[source]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.replay.ReplayDatasetColumn(*, column_name, sqlite_type, logical_type=None, analysis_role=None, title=None, description=None, unit=None, nullable, enum_values=None, example=None, tags=<factory>)[source]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.replay.ReplayDatasetInfo(*, dataset_id, table_name, module_name, kind, title='', description='', entity_key=None, step_key=None, time_key=None, default_order=<factory>, capabilities=<factory>, version, created_at, columns=<factory>)[source]¶
- created_at: datetime¶
- columns: List[ReplayDatasetColumn]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.replay.ReplayDatasetList(*, datasets)[source]¶
- datasets: List[ReplayDatasetInfo]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.replay.ReplayDatasetRows(*, dataset_id, columns, rows, total)[source]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.replay.ReplayPanelSchema(*, agent_profile_dataset=None, agent_state_datasets=<factory>, env_state_datasets=<factory>, geo_dataset=None, primary_agent_state_dataset_id=None, layout_hint='random', supports_map=False)[source]¶
- agent_profile_dataset: ReplayDatasetInfo | None¶
- agent_state_datasets: List[ReplayDatasetInfo]¶
- env_state_datasets: List[ReplayDatasetInfo]¶
- geo_dataset: ReplayDatasetInfo | None¶
- layout_hint: Literal['map', 'random']¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.replay.ReplayDatasetPanelRef(*, dataset_id, module_name, title='')[source]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.replay.ReplayPosition(*, agent_id, lng=None, lat=None)[source]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.replay.ReplayAgentStateAtStep(*, dataset, rows_by_agent_id=<factory>)[source]¶
- dataset: ReplayDatasetPanelRef¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.replay.ReplayEnvStateAtStep(*, dataset, row=None)[source]¶
- dataset: ReplayDatasetPanelRef¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.replay.ReplayStepBundle(*, step, t=None, layout_hint='random', positions=<factory>, agent_state_rows=<factory>, env_state_rows=<factory>)[source]¶
- layout_hint: Literal['map', 'random']¶
- positions: List[ReplayPosition]¶
- agent_state_rows: Dict[str, ReplayAgentStateAtStep]¶
- env_state_rows: Dict[str, ReplayEnvStateAtStep]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- agentsociety2.backend.routers.replay.get_replay_dir(workspace_path, hypothesis_id, experiment_id)[source]¶
- async agentsociety2.backend.routers.replay.get_experiment_info(hypothesis_id, experiment_id, workspace_path=Query(PydanticUndefined))[source]¶
- async agentsociety2.backend.routers.replay.get_replay_datasets(hypothesis_id, experiment_id, workspace_path=Query(PydanticUndefined))[source]¶
- async agentsociety2.backend.routers.replay.get_replay_dataset(hypothesis_id, experiment_id, dataset_id, workspace_path=Query(PydanticUndefined))[source]¶
- async agentsociety2.backend.routers.replay.get_replay_dataset_rows(hypothesis_id, experiment_id, dataset_id, workspace_path=Query(PydanticUndefined), page=Query(1), page_size=Query(20), order_by=Query(None), desc_order=Query(False), step=Query(None), entity_id=Query(None), start_step=Query(None), end_step=Query(None), max_step=Query(None), columns=Query(None), latest_per_entity=Query(False))[source]¶
- async agentsociety2.backend.routers.replay.get_replay_panel_schema(hypothesis_id, experiment_id, workspace_path=Query(PydanticUndefined))[source]¶
- async agentsociety2.backend.routers.replay.get_replay_step_bundle(hypothesis_id, experiment_id, step, workspace_path=Query(PydanticUndefined))[source]¶
Custom Module Routes¶
Custom Module API Routes
Provides API endpoints for scanning, cleaning, and testing custom modules.
Related files: - @extension/src/projectStructureProvider.ts - frontend project structure view that calls this API - @extension/src/apiClient.ts - API client
API endpoints: - POST /api/v1/custom/scan - scan custom modules and generate JSON configuration - POST /api/v1/custom/clean - clean custom module configuration - POST /api/v1/custom/test - test custom modules - GET /api/v1/custom/list - list registered custom modules - GET /api/v1/custom/status - get custom module status
Internal services: - @packages/agentsociety2/agentsociety2/backend/services/custom/scanner.py - module scanning - @packages/agentsociety2/agentsociety2/backend/services/custom/generator.py - JSON generation - @packages/agentsociety2/agentsociety2/registry/ - module registry
- class agentsociety2.backend.routers.custom.ScanRequest(*, workspace_path=None)[source]¶
Scan Request
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.custom.ScanResponse(*, success, agents_found, envs_found, agents_generated, envs_generated, errors=<factory>, agent_diagnostics=<factory>, env_diagnostics=<factory>, message=None)[source]¶
Scan Response
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.custom.CleanResponse(*, success, removed_count, message)[source]¶
Clean Response
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.custom.TestRequest(*, workspace_path=None, module_kind=None, module_class_name=None)[source]¶
Test Request
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.custom.ModuleTestResult(*, name, module_kind='env_module', success, output, error=None, checks=<factory>, metadata=<factory>)[source]¶
Single Module Test Result
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.custom.TestResponse(*, success, test_output, error=None, returncode=None, results=<factory>, total_tests=None, passed_tests=None, failed_tests=None)[source]¶
Test Response
- results: List[ModuleTestResult]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.custom.ListResponse(*, success, agents, envs, total_agents, total_envs)[source]¶
List Response
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- async agentsociety2.backend.routers.custom.scan_custom_modules(request)[source]¶
Scan custom modules and register them in memory
Scans the workspace directories custom/agents/ and custom/envs/ while skipping the examples/ subdirectories, validates discovered modules, and registers them directly in the in-memory registry.
- Parameters:
request (ScanRequest) – Scan request, including: - workspace_path: workspace path, optional; if omitted, the environment variable is used
- Returns:
ScanResponse: Scan result, including: - success: whether the operation succeeded - agents_found: number of discovered Agents - envs_found: number of discovered environment modules - agents_generated: number of successfully registered Agents - envs_generated: number of successfully registered environment modules - errors: list of error messages - message: result message
- Raises:
HTTPException – 400 - Workspace path was not provided
HTTPException – 500 - Scan failed
Note
This endpoint does not generate JSON configuration files. Modules are registered only in memory. To persist the configuration, use the /api/v1/custom/classes endpoint.
- async agentsociety2.backend.routers.custom.clean_custom_modules(request)[source]¶
Clean JSON configuration for custom modules
Deletes all JSON configuration files marked with is_custom=true.
- Parameters:
request (ScanRequest) – Clean request, including: - workspace_path: workspace path, optional
- Returns:
CleanResponse: Clean result, including: - success: whether the operation succeeded - removed_count: number of removed configurations - message: result message
- Raises:
HTTPException – 400 - Workspace path was not provided
HTTPException – 500 - Cleanup failed
- async agentsociety2.backend.routers.custom.test_custom_modules(request)[source]¶
Test custom modules
Scans and tests custom modules to verify that they work correctly. It can test all modules or a specific module.
- Parameters:
request (TestRequest) – Test request, including: - workspace_path: workspace path, optional - module_kind: module kind (‘agent’ or ‘env_module’), optional - module_class_name: class name to test, used together with module_kind and optional
- Returns:
TestResponse: Test result, including: - success: whether all tests passed - test_output: test output content - error: error message, if any - returncode: return code of the test process - results: list of test results for each module - total_tests: total number of tests - passed_tests: number of passed tests - failed_tests: number of failed tests
- Raises:
HTTPException – 400 - Workspace path was not provided
HTTPException – 500 - Test failed
Note
If module_kind and module_class_name are not specified, all discovered modules are tested.
- async agentsociety2.backend.routers.custom.list_custom_modules()[source]¶
List currently registered custom modules
Reads all module information marked with is_custom=true from the in-memory registry.
- Returns:
ListResponse: Module list, including: - success: whether the operation succeeded - agents: list of custom Agents - envs: list of custom environment modules - total_agents: total number of Agents - total_envs: total number of environment modules
- Raises:
HTTPException – 500 - Failed to get the list
- async agentsociety2.backend.routers.custom.get_custom_modules_status()[source]¶
Get an overview of custom module status
Returns status information for the custom module directories in the workspace.
- Returns:
Dict[str, Any]: Status information, including: - custom_dir_exists: whether the custom directory exists - agents_dir_exists: whether the agents subdirectory exists - envs_dir_exists: whether the envs subdirectory exists - agent_files_count: number of Agent files - env_files_count: number of environment module files - registered_agents: number of registered Agents - registered_envs: number of registered environment modules
- Raises:
HTTPException – 400 - Workspace path is not set
- async agentsociety2.backend.routers.custom.list_available_classes(workspace_path=Query(PydanticUndefined), include_custom=Query(True))[source]¶
List all available Agent classes and environment module classes
Returns all available classes and marks which ones already have prefill parameters configured.
- Parameters:
- Returns:
Dict[str, Any]: Available class list, including: - success: whether the operation succeeded - env_modules: dictionary of environment modules, each containing: - type, class_name, description, is_custom, has_prefill - agents: dictionary of Agents, each containing: - type, class_name, description, is_custom, has_prefill - env_module_count: number of environment modules - agent_count: number of Agents
- Raises:
HTTPException – 500 - Failed to get the class list
- Return type:
Module Routes¶
Modules API router
Provides endpoints for listing available agent classes and environment modules. Supports both built-in modules and custom modules from the workspace.
Related files: - @extension/src/apiClient.ts - API client that calls getAgentClasses and getEnvModules - @extension/src/prefillParamsViewProvider.ts - prefill parameter viewer - @extension/src/simSettingsEditorProvider.ts - SIM_SETTINGS editor - @packages/agentsociety2/agentsociety2/registry/ - module registry
API endpoints: - GET /api/v1/modules/agent_classes - get all available Agent classes - GET /api/v1/modules/env_module_classes - get all available environment module classes - GET /api/v1/modules/refresh - refresh the module list by rescanning
- async agentsociety2.backend.routers.modules.get_agent_classes(include_custom=Query(True))[source]¶
Get the list of all available Agent classes
Returns all registered Agent classes in the system, including built-in and custom modules.
- Parameters:
include_custom (bool) – Whether to include custom modules. Defaults to True.
- Returns:
Dict[str, Any]: Response containing Agent class information: - success: whether the operation succeeded - agents: dictionary of Agent classes, keyed by type name, with values containing: - type: type name - class_name: class name - description: description - is_custom: whether it is a custom module - count: total number of Agent classes
- Raises:
HTTPException – 500 - Failed to get Agent classes
- Return type:
- async agentsociety2.backend.routers.modules.get_env_module_classes(include_custom=Query(True))[source]¶
Get the list of all available environment module classes
Returns all registered environment module classes in the system, including built-in and custom modules.
- Parameters:
include_custom (bool) – Whether to include custom modules. Defaults to True.
- Returns:
Dict[str, Any]: Response containing environment module class information: - success: whether the operation succeeded - modules: dictionary of environment module classes, keyed by type name, with values containing: - type: type name - class_name: class name - description: description - is_custom: whether it is a custom module - count: total number of module classes
- Raises:
HTTPException – 500 - Failed to get environment module classes
- Return type:
- async agentsociety2.backend.routers.modules.get_all_modules(include_custom=Query(True))[source]¶
Get all available module classes
Returns all Agent classes and environment module classes in one call to reduce the number of requests.
- Parameters:
include_custom (bool) – Whether to include custom modules. Defaults to True.
- Returns:
Dict[str, Any]: Response containing all module information: - success: whether the operation succeeded - agents: dictionary of Agent classes - agent_count: number of Agent classes - env_modules: dictionary of environment module classes - env_module_count: number of environment module classes
- Raises:
HTTPException – 500 - Failed to get modules
- Return type:
Agent Skills Routing¶
Agent Skills API routing
API endpoints that provide a list of agent skills, enable/disable, scan for custom skills, and import/create/upload skills.
This route is based on the v2 skill registry (agentsociety2.agent.base.skill_registry), a read-only metadata registry: skills are directories that always exist, and PersonAgent selects which ones to activate at runtime from the catalog. Therefore this route has no enable / disable / reload / remove endpoints; those concepts do not exist in the v2 model.
Associated files: - @packages/agentsociety2/agentsociety2/agent/base/skill_registry.py - Skill registry - @extension/src/apiClient.ts - VSCode extension API client - @frontend/src/pages/Skills/index.tsx - Web front-end Skill management page
API 端点: - GET /api/v1/agent-skills/list — 列出所有已发现的 agent skill(built-in + custom + env) - POST /api/v1/agent-skills/scan — 扫描 workspace/custom/skills/ 下的自定义 skill - POST /api/v1/agent-skills/import — 从工作区内路径导入 skill 目录 - POST /api/v1/agent-skills/create — 在线创建新 skill(SKILL.md + 可选脚本) - POST /api/v1/agent-skills/upload — 上传 zip 包导入 skill - GET /api/v1/agent-skills/{skill_id}/info — 获取 SKILL.md 内容
- class agentsociety2.backend.routers.agent_skills.SkillItem(*, skill_id, name, namespace, description, source, source_label, path, has_skill_md, script='')[source]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.agent_skills.ListResponse(*, success, skills, total)[source]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.agent_skills.ScanRequest(*, workspace_path=None)[source]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.agent_skills.ScanResponse(*, success, new_skills, total, message)[source]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.agent_skills.ImportRequest(*, source_path, workspace_path=None)[source]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.agent_skills.ImportResponse(*, success, name, message)[source]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.agent_skills.CreateRequest(*, name, description='', script='', body='', script_content='', workspace_path=None)[source]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.backend.routers.agent_skills.SimpleResponse(*, success, message)[source]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- async agentsociety2.backend.routers.agent_skills.list_skills()[source]¶
List all discovered Agent Skills (builtin + custom + env).
- async agentsociety2.backend.routers.agent_skills.scan_custom_skills(req)[source]¶
Scan the workspace for custom Agent Skills ({workspace}/custom/skills/).
- async agentsociety2.backend.routers.agent_skills.import_skill(req)[source]¶
从工作区内路径导入 Agent Skill(复制到 custom/skills/)。
- async agentsociety2.backend.routers.agent_skills.create_skill(req)[source]¶
Create new custom skills online.
Generate SKILL.md (+ optional script file) under custom/skills/{name}/.
request/response model¶
SkillItem¶
- class agentsociety2.backend.routers.agent_skills.SkillItem(*, skill_id, name, namespace, description, source, source_label, path, has_skill_md, script='')[source]
- skill_id: str
- name: str
- namespace: str
- description: str
- source: str
- source_label: str
- path: str
- has_skill_md: bool
- script: str
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].