Skills Module

This page is divided into two parts:

  • Research Skills: research workflow modules under agentsociety2.skills.

  • Agent Skills: PersonAgent skill registration and runtime mechanisms under agentsociety2.agent.skills.

Research Skills

Top-level Entry

AgentSociety2 skills module.

This module provides the entry points for research workflows and analysis tooling, supporting a complete research process:

Skill List

  • literature: academic literature search and management, including retrieval, indexing, and formatting

  • experiment: experiment configuration and execution, including parameter generation and configuration validation

  • hypothesis: hypothesis generation and management, including create, read, list, and delete operations

  • analysis: data analysis tooling, providing experiment context loading, EDA, and tool registration capabilities

Usage Example

from pathlib import Path

from agentsociety2.skills import analysis, hypothesis, literature

# 文献检索
results = await literature.search_literature("machine learning")

# 创建假设
hypothesis.add_hypothesis(
    workspace_path=Path("./workspace"),
    hypothesis="社会网络密度影响信息传播速度"
)

# 读取实验 replay catalog
from agentsociety2.storage import ReplayReader

reader = ReplayReader(Path("./workspace/hypothesis_1/experiment_1/run/replay"))
datasets = reader.load_dataset_catalog()
reader.close()

analysis

Analysis tool layer: data access, execution helpers, output helpers, and path utilities.

class agentsociety2.skills.analysis.AnalysisResult(*, experiment_id, hypothesis_id, insights=<factory>, findings=<factory>, conclusions='', recommendations=<factory>, generated_at=<factory>)[source]

Experiment Analysis Result

experiment_id: str
hypothesis_id: str
insights: List[Any]
findings: List[Any]
conclusions: Any
recommendations: List[Any]
generated_at: datetime
model_config = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class agentsociety2.skills.analysis.AssetManager(workspace_path)[source]

Discover and normalize analysis assets.

__init__(workspace_path)[source]
discover_assets(experiment_id, hypothesis_id)[source]

Discover image assets under run/artifacts.

process_assets(assets, output_dir, *, include_embedded_data=True)[source]

Copy assets into assets/; optionally generate base64 payloads.

class agentsociety2.skills.analysis.ContextLoader(workspace_path)[source]

Experiment Context Loading

__init__(workspace_path)[source]
load_context(hypothesis_id, experiment_id)[source]

Load the complete experiment context

load_design(hypothesis_base, experiment_path)[source]

Load the experiment design

class agentsociety2.skills.analysis.DataReader(db_path)[source]

Database Reading and Interpretation

__init__(db_path)[source]
read_schema()[source]

Read the database schema

read_sample_data(tables=None, limit=5)[source]

Read sample data

compute_stats(schema)[source]

Compute statistical summary

read_full_summary()[source]

Read the full data summary

class agentsociety2.skills.analysis.DataStats(numeric_stats=<factory>, categorical_stats=<factory>, sample_data=<factory>, quick_stats_md='')[source]

Data Statistics Summary

numeric_stats: Dict[str, Dict[str, Any]]
categorical_stats: Dict[str, Dict[str, Any]]
sample_data: Dict[str, List[Dict]]
quick_stats_md: str = ''
__init__(numeric_stats=<factory>, categorical_stats=<factory>, sample_data=<factory>, quick_stats_md='')
class agentsociety2.skills.analysis.DataSummary(db_path=None, schema=None, stats=None)[source]

Complete Data Summary

db_path: str | None = None
schema: DatabaseSchema | None = None
stats: DataStats | None = None
property tables: List[str]
property row_counts: Dict[str, int]
property schema_markdown: str
property quick_stats: str
property numeric_stats: Dict[str, Dict[str, Any]]
property categorical_stats: Dict[str, Dict[str, Any]]
property sample_data: Dict[str, List[Dict]]
__init__(db_path=None, schema=None, stats=None)
class agentsociety2.skills.analysis.DatabaseSchema(tables, columns, row_counts, markdown='')[source]

Database Schema Information

tables: List[str]
columns: Dict[str, List[Dict[str, Any]]]
row_counts: Dict[str, int]
markdown: str = ''
__init__(tables, columns, row_counts, markdown='')
class agentsociety2.skills.analysis.EDAGenerator[source]

Generate exploratory data analysis artifacts.

__init__()[source]
resolve_table_selection(reader, tables)[source]

Return requested, selected, and invalid table names.

generate_quick_stats(db_path, max_rows=5000, tables=None)[source]
generate_missingno_report(db_path, output_dir, max_rows=50000, tables=None)[source]

Generate a missing-value report with missingno.

generate_correlation_report(db_path, output_dir, max_rows=50000, tables=None)[source]

Generate a correlation report.

generate_ydata_profile(db_path, output_dir, max_rows=10000, tables=None)[source]

Generate a ydata-profiling report.

generate_sweetviz_profile(db_path, output_dir, max_rows=10000, tables=None)[source]

Generate a Sweetviz report.

generate_pygwalker_profile(db_path, output_dir, max_rows=10000, tables=None)[source]
generate_datatable_profile(db_path, output_dir, max_rows=5000, tables=None)[source]
generate_plotly_profile(db_path, output_dir, max_rows=8000, tables=None)[source]
generate_eda_hub(output_dir, *, title='AgentSociety EDA Hub')[source]
generate_eda_bundle(db_path, output_dir, profiles=None, tables=None, max_rows=10000)[source]
agentsociety2.skills.analysis.export_altair_html(chart, path, *, inline=True)[source]
agentsociety2.skills.analysis.export_plotly_html(fig, path, *, include_plotlyjs=True)[source]
agentsociety2.skills.analysis.export_pygwalker_html(df, path, *, embed_lib=True)[source]
class agentsociety2.skills.analysis.ExecutionResult(success, stdout='', stderr='', artifacts=<factory>, generated_code='', error='')[source]

Code execution result.

success: bool
stdout: str = ''
stderr: str = ''
artifacts: List[str]
generated_code: str = ''
error: str = ''
__init__(success, stdout='', stderr='', artifacts=<factory>, generated_code='', error='')
class agentsociety2.skills.analysis.ExperimentContext(*, experiment_id, hypothesis_id, design, duration_seconds=None, execution_status=ExperimentStatus.UNKNOWN, completion_percentage=0.0, error_messages=<factory>)[source]

Complete Experiment State

experiment_id: str
hypothesis_id: str
design: ExperimentDesign
duration_seconds: float | None
execution_status: ExperimentStatus
completion_percentage: float
error_messages: List[str]
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class agentsociety2.skills.analysis.ExperimentDesign(*, hypothesis, objectives=<factory>, variables=<factory>, methodology='', success_criteria=<factory>, hypothesis_markdown=None, experiment_markdown=None)[source]

Experiment Design

hypothesis: str
objectives: List[str]
variables: Dict[str, Any]
methodology: str
success_criteria: List[str]
hypothesis_markdown: str | None
experiment_markdown: str | None
model_config = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class agentsociety2.skills.analysis.ExperimentPaths(*, hypothesis_base, experiment_path, run_path, db_path, pid_path, assets_path)[source]

Conventional read-only paths for a single experiment under the workspace, built by utils.experiment_paths.

hypothesis_base: Path
experiment_path: Path
run_path: Path
db_path: Path
pid_path: Path
assets_path: Path
model_config = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class agentsociety2.skills.analysis.ExperimentStatus(*values)[source]

Experiment Execution Status

SUCCESSFUL = 'successful'
PARTIAL_SUCCESS = 'partial_success'
FAILED = 'failed'
INTERRUPTED = 'interrupted'
UNKNOWN = 'unknown'
class agentsociety2.skills.analysis.HypothesisSummary(*, hypothesis_id, hypothesis_text, experiment_count=0, successful_experiments=0, total_completion=0.0, key_insights=<factory>, main_findings=<factory>, experiment_results=<factory>)[source]

Analysis result across multiple experiments

hypothesis_id: str
hypothesis_text: str
experiment_count: int
successful_experiments: int
total_completion: float
key_insights: List[str]
main_findings: List[str]
experiment_results: List[Dict[str, Any]]
model_config = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class agentsociety2.skills.analysis.PresentationPaths(*, output_dir, charts_dir, report_assets_dir, report_zh_md, report_zh_html, report_en_md, report_en_html, result_json, readme)[source]

Output paths for analysis artifacts of a single experiment.

These paths are grouped by hypothesis under presentation/ and built by utils.presentation_paths.

Typical artifacts include:

  • bilingual reports, compatibility alias reports, README.md, and data/analysis_summary.json under output_dir/.

  • generated charts under charts/, together with report reference assets copied into assets/.

output_dir: Path
charts_dir: Path
report_assets_dir: Path
report_zh_md: Path
report_zh_html: Path
report_en_md: Path
report_en_html: Path
result_json: Path
readme: Path
model_config = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class agentsociety2.skills.analysis.ReportAsset(*, asset_id, asset_type, title, description='', file_path, embedded_content=None, file_size=0, created_at=<factory>, dimensions=None)[source]

Additional assets required by the report

asset_id: str
asset_type: str
title: str
description: str
file_path: str
embedded_content: str | None
file_size: int
created_at: datetime
dimensions: Dict[str, int] | None
model_config = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class agentsociety2.skills.analysis.ReportContent(*, title, subtitle='', format_preference='markdown', full_content_markdown_zh=None, full_content_html_zh=None, full_content_markdown_en=None, full_content_html_en=None)[source]

Report content with Chinese and English variants

title: str
subtitle: str
format_preference: str
full_content_markdown_zh: str | None
full_content_html_zh: str | None
full_content_markdown_en: str | None
full_content_html_en: str | None
property full_content_markdown: str | None

Chinese first; otherwise English.

property full_content_html: str | None

Chinese first; otherwise English.

model_config = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class agentsociety2.skills.analysis.ReportPaths(markdown, html, markdown_zh=None, html_zh=None, markdown_en=None, html_en=None, assets_dir=None)[source]

Report file paths.

markdown: Path
html: Path
markdown_zh: Path | None = None
html_zh: Path | None = None
markdown_en: Path | None = None
html_en: Path | None = None
assets_dir: Path | None = None
__init__(markdown, html, markdown_zh=None, html_zh=None, markdown_en=None, html_en=None, assets_dir=None)
class agentsociety2.skills.analysis.SynthesisPaths(*, output_dir, report_assets_dir, report_zh_md, report_en_md)[source]

Output paths for synthesis reports under the standalone synthesis root directory.

output_dir: Path
report_assets_dir: Path
report_zh_md: Path
report_en_md: Path
model_config = {'arbitrary_types_allowed': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class agentsociety2.skills.analysis.ToolInfo(name, description, tool_type='builtin', parameters=<factory>)[source]

Tool metadata.

name: str
description: str
tool_type: str = 'builtin'
parameters: List[str]
__init__(name, description, tool_type='builtin', parameters=<factory>)
class agentsociety2.skills.analysis.ToolResult(*, success, content, error=None, data=None)[source]

Tool execution result.

success: bool
content: str
error: str | None
data: Any
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

agentsociety2.skills.analysis.collect_experiment_files(db_path)[source]

Collect file paths under the run directory that executors may use, including replay/, sibling files, and run/artifacts.

agentsociety2.skills.analysis.experiment_paths(workspace_path, hypothesis_id, experiment_id)[source]

Aggregate paths for a single experiment by convention; the id is sanitized for safety.

agentsociety2.skills.analysis.extract_database_schema(db_path)[source]

Extract replay schema from metadata catalog tables.

agentsociety2.skills.analysis.format_database_schema_markdown(schema, include_row_counts=False, db_path=None)[source]

Format the replay metadata schema as Markdown, with an optional row limit.

agentsociety2.skills.analysis.presentation_paths(presentation_root, hypothesis_id, experiment_id)[source]

Paths for single-experiment analysis artifacts: grouped by hypothesis, while the experiment id is retained only for interface compatibility.

agentsociety2.skills.analysis.synthesis_paths(workspace_path)[source]

Paths for synthesis reports: written under an independent synthesis/ root directory.

experiment

Experiment execution skills

Provides experiment execution and result management.

class agentsociety2.skills.experiment.ExperimentConfig(*, hypothesis_id, experiment_id, run_id='run', agent_classes=<factory>, env_modules=<factory>, user_instructions=None, **extra_data)[source]

Experiment configuration model

Basic configuration for an experiment run.

model_config = {'extra': 'allow'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

hypothesis_id: str
experiment_id: str
run_id: str
agent_classes: List[str]
env_modules: List[str]
user_instructions: str | None
class agentsociety2.skills.experiment.ExperimentConfigTool(workspace_path, progress_callback=None, tool_id='')[source]

Tool for initializing and validating experiment configurations

__init__(workspace_path, progress_callback=None, tool_id='')[source]

Initialize the experiment config tool

Parameters:
  • workspace_path (str | Path) – Path to the workspace directory

  • progress_callback (Any) – Optional callback for progress updates

  • tool_id (str) – Optional tool identifier

property name: str
property description: str
get_parameters_schema()[source]
async execute(arguments)[source]

Execute the experiment configuration

Parameters:

arguments (Dict[str, Any]) – Dictionary with hypothesis_id, experiment_id, and optional parameters

Returns:

ToolResult-like object with success, content, error fields

Return type:

Any

class agentsociety2.skills.experiment.ExperimentInfo(*, hypothesis_id, experiment_id, run_id='run', has_init=False, has_run=False, status=None, pid=None, is_running=False, **extra_data)[source]

Information about an experiment

Summary of an experiment’s configuration and status.

model_config = {'extra': 'allow'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

hypothesis_id: str
experiment_id: str
run_id: str
has_init: bool
has_run: bool
status: str | None
pid: int | None
is_running: bool
class agentsociety2.skills.experiment.ExperimentStatus(*, hypothesis_id, experiment_id, run_id, status, pid=None, start_time=None, end_time=None, stdout_log=None, stderr_log=None, is_running=False, **extra_data)[source]

Experiment execution status model

Represents the current status of a running or completed experiment.

model_config = {'extra': 'allow'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

hypothesis_id: str
experiment_id: str
run_id: str
status: str
pid: int | None
start_time: str | None
end_time: str | None
stdout_log: str | None
stderr_log: str | None
is_running: bool
agentsociety2.skills.experiment.format_module_suggestion_message(suggestions)[source]

Format module suggestions into a helpful message

Parameters:

suggestions (Dict[str, Any]) – Dictionary from suggest_modules_for_topic()

Returns:

Formatted message string

Return type:

str

agentsociety2.skills.experiment.generate_hypothesis_config(topic, description, rationale, groups, agent_classes=None, env_modules=None)[source]

Generate a complete hypothesis configuration

This function creates a properly formatted hypothesis configuration that can be passed to add_hypothesis_with_validation().

Parameters:
  • topic (str) – Research topic

  • description (str) – Hypothesis description

  • rationale (str) – Theoretical basis

  • groups (List[Dict[str, Any]]) – List of experiment groups

  • agent_classes (List[str] | None) – Agent types (optional, will suggest if not provided)

  • env_modules (List[str] | None) – Environment modules (optional, will suggest if not provided)

Returns:

Complete hypothesis configuration dictionary

Return type:

Dict[str, Any]

agentsociety2.skills.experiment.get_available_agent_modules()[source]

Get available agent modules with their descriptions

Returns:

Dictionary mapping agent_type to description

Return type:

Dict[str, str]

agentsociety2.skills.experiment.get_available_env_modules()[source]

Get available environment modules with their descriptions

Returns:

Dictionary mapping module_type to description

Return type:

Dict[str, str]

async agentsociety2.skills.experiment.get_experiment_status(workspace_path, hypothesis_id, experiment_id, run_id='run')[source]

Get experiment status

Parameters:
  • workspace_path (Path) – Path to the workspace directory

  • hypothesis_id (str) – Hypothesis ID

  • experiment_id (str) – Experiment ID

  • run_id (str) – Run ID (default: ‘run’)

Returns:

ExperimentStatus object

Return type:

ExperimentStatus

agentsociety2.skills.experiment.get_experiment_template(workspace_path, hypothesis_id, experiment_id)[source]

Get a template for experiment configuration

This function provides a template structure that Claude Code can use to generate the full experiment configuration.

Parameters:
  • workspace_path (Path) – Path to the workspace directory

  • hypothesis_id (str) – Hypothesis ID

  • experiment_id (str) – Experiment ID

Returns:

Template dictionary with structure to fill in

Return type:

Dict[str, Any]

agentsociety2.skills.experiment.get_module_selection_guidance(topic, agent_classes=None, env_modules=None)[source]

Generate guidance text for module selection

Parameters:
  • topic (str) – Research topic for context

  • agent_classes (List[str] | None) – Currently selected agent classes

  • env_modules (List[str] | None) – Currently selected environment modules

Returns:

Guidance text for helping with module selection

Return type:

str

agentsociety2.skills.experiment.get_modules_summary()[source]

Get a formatted summary of available modules for LLM prompts

Returns:

Formatted string with available modules

Return type:

str

async agentsociety2.skills.experiment.list_experiments(workspace_path, hypothesis_id=None)[source]

List experiments

Parameters:
  • workspace_path (Path) – Path to the workspace directory

  • hypothesis_id (str | None) – Optional hypothesis ID to filter by

Returns:

List of ExperimentInfo objects

Return type:

List[ExperimentInfo]

Note

Uses simplified init structure: init/init_config.json, init/steps.yaml

async agentsociety2.skills.experiment.start_experiment(workspace_path, hypothesis_id, experiment_id, run_id='run', init_config_path=None, steps_path=None)[source]

Start an experiment

Parameters:
  • workspace_path (Path) – Path to the workspace directory

  • hypothesis_id (str) – Hypothesis ID (e.g., ‘1’, ‘2’)

  • experiment_id (str) – Experiment ID (e.g., ‘1’, ‘2’)

  • run_id (str) – Run ID (default: ‘run’)

  • init_config_path (Path | None) – Optional path to init_config.json (default: init/init_config.json)

  • steps_path (Path | None) – Optional path to steps.yaml (default: init/steps.yaml)

Returns:

Result dictionary with status and info

Return type:

Dict[str, Any]

async agentsociety2.skills.experiment.stop_experiment(workspace_path, hypothesis_id, experiment_id, run_id='run')[source]

Stop a running experiment

Parameters:
  • workspace_path (Path) – Path to the workspace directory

  • hypothesis_id (str) – Hypothesis ID

  • experiment_id (str) – Experiment ID

  • run_id (str) – Run ID (default: ‘run’)

Returns:

Result dictionary with status

Return type:

Dict[str, Any]

agentsociety2.skills.experiment.suggest_modules_for_topic(topic)[source]

Suggest appropriate agent and environment modules for a research topic

This function analyzes the research topic and suggests suitable agent types and environment modules based on keywords and common patterns.

Parameters:

topic (str) – Research topic or description

Returns:

Dictionary with suggested modules and rationale

Return type:

Dict[str, Any]

agentsociety2.skills.experiment.validate_experiment_ready(workspace_path, hypothesis_id, experiment_id)[source]

Check if an experiment is ready to run

This function validates that all necessary configuration is in place for an experiment to be executed.

Parameters:
  • workspace_path (Path) – Path to the workspace directory

  • hypothesis_id (str) – Hypothesis ID

  • experiment_id (str) – Experiment ID

Returns:

Tuple of (is_ready, missing_items, context)

Return type:

Tuple[bool, List[str], Dict[str, Any]]

agentsociety2.skills.experiment.validate_hypothesis_modules(hypothesis_data)[source]

Validate that a hypothesis has required modules

Parameters:

hypothesis_data (Dict[str, Any]) – Hypothesis data dictionary

Returns:

Tuple of (is_valid, error_messages, guidance_dict)

Return type:

Tuple[bool, List[str], Dict[str, Any] | None]

agentsociety2.skills.experiment.validate_module_selection(agent_classes=None, env_modules=None)[source]

Validate that at least one agent and one environment module are selected

Parameters:
  • agent_classes (List[str] | None) – List of agent class types

  • env_modules (List[str] | None) – List of environment module types

Returns:

Tuple of (is_valid, list of error messages)

Return type:

Tuple[bool, List[str]]

hypothesis

Hypothesis management module

Provides functionality for: - Creating hypotheses - Reading hypotheses - Listing hypotheses - Deleting hypotheses

class agentsociety2.skills.hypothesis.ExperimentGroupModel(*, name, group_type, description, agent_selection_criteria=None)[source]

Experiment group model (for hypothesis generation phase)

name: str
group_type: str
description: str
agent_selection_criteria: str | None
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class agentsociety2.skills.hypothesis.HypothesisDataModel(*, hypothesis, groups, agent_classes=None, env_modules=None)[source]

Hypothesis data model (including hypothesis and experiment groups)

hypothesis: HypothesisModel
groups: List[ExperimentGroupModel]
agent_classes: List[str] | None
env_modules: List[str] | None
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class agentsociety2.skills.hypothesis.HypothesisModel(*, description, rationale)[source]

Hypothesis model

description: str
rationale: str
model_config = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

agentsociety2.skills.hypothesis.add_hypothesis(workspace_path, hypothesis_data)[source]

Add a new hypothesis

Parameters:
  • workspace_path (Path) – Path to the workspace directory

  • hypothesis_data (Dict[str, Any]) – Hypothesis data dictionary

Returns:

Result dictionary with success status and info

Return type:

Dict[str, Any]

agentsociety2.skills.hypothesis.add_hypothesis_with_validation(workspace_path, hypothesis_data, validate_modules=True)[source]

Add a new hypothesis with enhanced module validation

This function provides enhanced validation that checks: 1. Schema validity (via Pydantic) 2. Agent and environment module selection (at least one of each required)

Parameters:
  • workspace_path (Path) – Path to the workspace directory

  • hypothesis_data (Dict[str, Any]) – Hypothesis data dictionary

  • validate_modules (bool) – Whether to validate module selection (default: True)

Returns:

Result dictionary with success status and info. If module validation fails, includes guidance for module selection.

Return type:

Dict[str, Any]

agentsociety2.skills.hypothesis.create_hypothesis_structure(workspace_path, hypothesis_id, hypothesis_model)[source]

Create hypothesis directory structure

Parameters:
  • workspace_path (Path) – Path to the workspace directory

  • hypothesis_id (str) – Hypothesis ID

  • hypothesis_model (HypothesisDataModel) – Validated hypothesis data model

Returns:

Path to created hypothesis directory

Return type:

Path

agentsociety2.skills.hypothesis.delete_hypothesis(workspace_path, hypothesis_id=None, hypothesis_path=None)[source]

Delete a hypothesis folder

Parameters:
  • workspace_path (Path) – Path to the workspace directory

  • hypothesis_id (str | None) – Hypothesis ID (e.g., ‘1’, ‘2’)

  • hypothesis_path (str | None) – Relative path to hypothesis folder

Returns:

Result dictionary with deletion status

Return type:

Dict[str, Any]

agentsociety2.skills.hypothesis.find_existing_hypotheses(workspace_path)[source]

Find existing hypothesis directories

Parameters:

workspace_path (Path) – Path to the workspace directory

Returns:

Sorted list of hypothesis directory paths

Return type:

List[Path]

agentsociety2.skills.hypothesis.generate_experiment_markdown(group, exp_idx)[source]

Generate EXPERIMENT.md content

Parameters:
Returns:

Markdown content for EXPERIMENT.md

Return type:

str

agentsociety2.skills.hypothesis.generate_hypothesis_markdown(hypothesis_model)[source]

Generate HYPOTHESIS.md content

Parameters:

hypothesis_model (HypothesisDataModel) – Validated hypothesis data model

Returns:

Markdown content for HYPOTHESIS.md

Return type:

str

agentsociety2.skills.hypothesis.generate_sim_settings(hypothesis_model)[source]

Generate SIM_SETTINGS.json content

Parameters:

hypothesis_model (HypothesisDataModel) – Validated hypothesis data model

Returns:

SIM_SETTINGS dictionary

Return type:

Dict[str, Any]

agentsociety2.skills.hypothesis.get_hypothesis(workspace_path, hypothesis_id=None, hypothesis_path=None)[source]

Get hypothesis details

Parameters:
  • workspace_path (Path) – Path to the workspace directory

  • hypothesis_id (str | None) – Hypothesis ID (e.g., ‘1’, ‘2’)

  • hypothesis_path (str | None) – Relative path to hypothesis folder

Returns:

Result dictionary with hypothesis details

Return type:

Dict[str, Any]

agentsociety2.skills.hypothesis.get_next_hypothesis_id(workspace_path)[source]

Get the next hypothesis ID

Parameters:

workspace_path (Path) – Path to the workspace directory

Returns:

Next hypothesis ID as string

Return type:

str

agentsociety2.skills.hypothesis.list_hypotheses(workspace_path)[source]

List all hypotheses

Parameters:

workspace_path (Path) – Path to the workspace directory

Returns:

Result dictionary with list of hypotheses

Return type:

Dict[str, Any]

agentsociety2.skills.hypothesis.validate_hypothesis_schema(hypothesis_data)[source]

Validate hypothesis data against schema

Parameters:

hypothesis_data (Dict[str, Any]) – Hypothesis data dictionary

Returns:

Tuple of (is_valid, error_message, validated_model)

Return type:

Tuple[bool, str | None, HypothesisDataModel | None]

literature

Literature search and management module

Academic literature search (MCP), workspace indexing, formatting, and full-text helpers.

class agentsociety2.skills.literature.LiteratureEntry(*, title, journal=None, doi=None, abstract=None, file_path, file_type, source, query=None, avg_similarity=None, saved_at, extra_fields=None)[source]

Literature entry data model

Used to standardize literature JSON entries, ensuring data structure consistency and type safety.

title: str
journal: str | None
doi: str | None
abstract: str | None
file_path: str
file_type: Literal['markdown', 'pdf', 'docx', 'txt', 'md']
source: Literal['literature_search', 'user_upload']
query: str | None
avg_similarity: float | None
saved_at: str
extra_fields: Dict[str, Any] | None
model_config = {'extra': 'forbid', 'json_schema_extra': {'example': {'abstract': 'This is an example abstract...', 'avg_similarity': 0.85, 'doi': '10.1000/example', 'file_path': 'papers/Example_Research_Paper_2024-01-01.md', 'file_type': 'markdown', 'journal': 'Journal of Example Studies', 'query': 'example research', 'saved_at': '2024-01-01T12:00:00', 'source': 'literature_search', 'title': 'Example Research Paper'}}}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

classmethod validate_saved_at(v)[source]

Validate save time format

classmethod validate_doi(v)[source]

Validate DOI format (basic check)

class agentsociety2.skills.literature.LiteratureIndex(*, entries=<factory>, version='1.0', created_at=None, updated_at=None)[source]

Literature index data model

Used to standardize the entire literature index JSON file structure.

entries: list[LiteratureEntry]
version: str
created_at: str | None
updated_at: str | None
model_config = {'extra': 'forbid', 'json_schema_extra': {'example': {'created_at': '2024-01-01T12:00:00', 'entries': [{'abstract': 'This is an example abstract...', 'avg_similarity': 0.85, 'doi': '10.1000/example', 'file_path': 'papers/Example_Research_Paper_2024-01-01.md', 'file_type': 'markdown', 'journal': 'Journal of Example Studies', 'query': 'example research', 'saved_at': '2024-01-01T12:00:00', 'source': 'literature_search', 'title': 'Example Research Paper'}], 'updated_at': '2024-01-01T12:00:00', 'version': '1.0'}}}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

agentsociety2.skills.literature.format_article_as_markdown(article, query)[source]

Format a single literature article as markdown

Parameters:
  • article (Dict[str, Any]) – Article data dictionary

  • query (str) – Search query used to find the article

Returns:

Markdown formatted string

Return type:

str

agentsociety2.skills.literature.format_search_results(articles, total, query)[source]

Format search results for display

Parameters:
  • articles (list) – List of article dictionaries

  • total (int) – Total number of articles

  • query (str) – Search query

Returns:

Formatted string for display

Return type:

str

async agentsociety2.skills.literature.generate_summary(query, articles, total, router=None)[source]

Generate a summary using LLM to guide users on next steps

Parameters:
  • query (str) – Original search query

  • articles (list) – List of found articles

  • total (int) – Total number of articles found

  • router (Any | None) – Optional LLM router. When omitted, the default LLM dispatcher is used.

Returns:

Generated summary text

Return type:

str

agentsociety2.skills.literature.is_chinese_text(text)[source]

Check whether the text contains Chinese characters

Parameters:

text (str) – Text to examine

Returns:

Returns True if the text contains Chinese characters; otherwise returns False.

Return type:

bool

agentsociety2.skills.literature.load_literature_index(workspace_path)[source]

Load literature index from workspace

Parameters:

workspace_path (Path) – Path to the workspace directory

Returns:

LiteratureIndex object or None if file doesn’t exist

Return type:

LiteratureIndex | None

agentsociety2.skills.literature.sanitize_filename(filename)[source]

Clean filename by removing illegal characters

Parameters:

filename (str) – Original filename

Returns:

Sanitized filename safe for filesystem

Return type:

str

async agentsociety2.skills.literature.search_literature(query, limit=10, router=None, year_from=None, year_to=None, sources=None, similarity_threshold=None, vector_similarity_weight=None, chunk_content_limit=None, relevant_content_limit=None, max_chunks_per_article=None, return_chunks=True, enable_multi_query=False, mcp_url=None, api_key=None, timeout=120)[source]

Search academic literature through the MCP gateway.

Parameters:
  • query (str) – Search query (supports Chinese, will be translated to English)

  • limit (int) – Number of articles to return (default: 10)

  • router (Router | None) – LLM router for translation and query splitting.

  • year_from (int | None) – Filter by publication year (start)

  • year_to (int | None) – Filter by publication year (start)

  • sources (List[Literal['local', 'arxiv', 'crossref', 'openalex']] | None) – Optional source list (local, arxiv, crossref, openalex); default all.

  • similarity_threshold (float | None) – Local index similarity threshold (0.0–1.0).

  • vector_similarity_weight (float | None) – Vector weight for hybrid local search (0.0–1.0).

  • chunk_content_limit (int | None) – Max characters per chunk in the response.

  • relevant_content_limit (int | None) – Max characters of relevant content per article.

  • max_chunks_per_article (int | None) – Max chunks returned per article.

  • return_chunks (bool) – Whether to include chunk text in results.

  • enable_multi_query (bool) – Enable multi-query mode to split complex queries into subtopics

  • mcp_url (str | None) – MCP gateway URL; uses Config.get_literature_search_mcp_url() when omitted.

  • api_key (str | None) – Bearer API key; uses Config.get_literature_search_api_key() when omitted.

  • timeout (int) – MCP request timeout in seconds.

Returns:

Dict with articles, total, query, and optional sources; None on failure.

Return type:

Dict[str, Any] | None

async agentsociety2.skills.literature.search_literature_and_save(query, workspace_path, router=None, limit=10, year_from=None, year_to=None, sources=None, enable_multi_query=False, download_full_text=True)[source]

Search for literature and save results to workspace

Parameters:
  • query (str) – Search query (supports Chinese, will be translated to English)

  • workspace_path (Path) – Path to the workspace directory

  • router (Any | None) – Optional litellm router. When omitted, the default LLM dispatcher is used.

  • limit (int) – Number of articles to return (default: 10)

  • year_from (int | None) – Filter by publication year (start)

  • year_to (int | None) – Filter by publication year (end)

  • sources (List[Literal['local', 'arxiv', 'crossref', 'openalex']] | None) – Data sources to search (default: all sources)

  • enable_multi_query (bool) – Enable multi-query mode to split complex queries into subtopics

  • download_full_text (bool) – After saving metadata, try to download open-access PDFs

Returns:

Dictionary with search results and saved file information

Return type:

Dict[str, Any]

Note

The publicly documented research skill modules in this repository are analysis, experiment, hypothesis, and literature. The web_research directory does not currently retain readable source code, so it is not included in the documented API surface.

Agent Skills

Skill infrastructure (discovery, visibility / activation, script execution, and lifecycle hooks) has moved from agent/skills/ down into agentsociety2.agent.base. The agent/skills/ directory now only contains skill content, such as the built-in daily-guidance/. For design notes, see Agent Skills.

SkillRegistry

class agentsociety2.agent.base.skill_registry.SkillRegistry[source]

Bases: object

Tool metadata.

Parameters:

None.

__init__()[source]

Initialize an empty registry.

Parameters:

None.

Returns:

None.

Return type:

None

scan_builtin(root=None)[source]

Scan built-in skills from the agent/skills directory.

Parameters:

root (Path | None) – Optional built-in skill root override.

Returns:

Agent Skills

Return type:

list[str]

scan_custom(skills_root, namespace='custom')[source]

Scan custom skills from a workspace directory.

Parameters:
  • skills_root (Path) – Directory containing skill subdirectories with SKILL.md files.

  • namespace (str) – Namespace assigned to discovered skills.

Returns:

Agent Skills

Return type:

list[str]

scan_env(skills_dir, env_name)[source]

Scan skills from an environment module’s skill directory.

Parameters:
  • skills_dir (Path) – Directory containing skill subdirectories with SKILL.md files.

  • env_name (str) – List of environment module types

Returns:

Agent Skills

Return type:

list[str]

list_all()[source]

List all registered skills.

Parameters:

None.

Returns:

Get standard status descriptions.

Return type:

list[SkillDescriptor]

get(skill_id)[source]

Return one skill descriptor by id.

Parameters:

skill_id (str) – Registry Module

Returns:

Matching descriptor, or None.

Return type:

SkillDescriptor | None

find_by_name(name)[source]

Find skill descriptors by display name.

Parameters:

name (str) – Skill display name.

Returns:

Matching descriptors.

Return type:

list[SkillDescriptor]

read_skill_doc(skill_id)[source]

Read one skill’s SKILL.md.

Parameters:

skill_id (str) – Registry Module

Returns:

Skill document text, or an empty string.

Return type:

str

read_skill_file(skill_id, relative_path)[source]

Read one file inside a skill directory.

Parameters:
  • skill_id (str) – Registry Module

  • relative_path (str) – Path relative to the skill root.

Returns:

File text, or an empty string.

Return type:

str

list_hooks(hook_type)[source]

List skills declaring one hook.

Parameters:

hook_type (str) – Lifecycle hook name.

Returns:

Skill descriptors that declare the hook.

Return type:

list[SkillDescriptor]

copy()[source]

source registry.

Parameters:

None.

Returns:

SkillRegistry

Return type:

SkillRegistry

SkillRegistry

class agentsociety2.agent.base.skill_registry.SkillDescriptor(skill_id, name, namespace, description, root, source, source_label, script, hooks)[source]

Tool metadata.

Parameters:
  • skill_id (str) – Stable registry skill id.

  • name (str) – Display name from SKILL.md.

  • namespace (str) – Skill namespace.

  • description (str) – Hypothesis description

  • root (Path) – Skill root directory.

  • source (str) – Source category.

  • source_label (str) – Human-readable source label.

  • script (str | None) – Optional default script path.

  • hooks (dict[str, str]) – Lifecycle hook script map.

skill_id: str
name: str
namespace: str
description: str
root: Path
source: str
source_label: str
script: str | None
hooks: dict[str, str]
resource_files()[source]

List files shipped under this skill root.

Parameters:

None.

Returns:

Relative resource file paths under the skill root.

Return type:

list[str]

__init__(skill_id, name, namespace, description, root, source, source_label, script, hooks)

Agent Skills

class agentsociety2.agent.base.skill_runtime.AgentSkillRuntime(agent_id, registry)[source]

Bases: object

Registry for skill discovery, management, and execution.

__init__(agent_id, registry)[source]

Initialize the skill runtime.

Parameters:
  • agent_id (int) – Experiment ID

  • registry (SkillRegistryLike) – Skill registry facade used by this runtime.

Returns:

None.

Return type:

None

bind_workspace(*, workspace_root, fs, trace_writer)[source]

Bind this runtime to an agent-owned workspace.

Parameters:
  • workspace_root (Path) – Agent workspace root created by the agent.

  • fs (WorkspaceFS) – Agent-owned workspace filesystem facade.

  • trace_writer (JsonlTraceWriter) – Agent-owned trace writer.

Returns:

None.

Return type:

None

workspace_root()[source]

Return the workspace root.

Parameters:

None.

Returns:

Absolute workspace root path.

Return type:

Path

property is_initialized: bool

Return whether the workspace is initialized.

Parameters:

None.

Returns:

True when the workspace has been initialized.

property fs: WorkspaceFS

Return the workspace filesystem facade.

Parameters:

None.

Returns:

Workspace filesystem facade.

set_visible_skills(tokens)[source]

Set visible skills for this agent.

Each entry may be a registry skill id (namespace@name) or a display name; both forms resolve against the whole registry.

Parameters:

tokens (Iterable[str]) – Candidate skill ids or display names.

Returns:

None.

Return type:

None

add_visible_skill(token)[source]

Add one visible skill by id or display name.

Parameters:

token (str) – Skill id (namespace@name) or display name.

Returns:

True when the skill exists and was made visible.

Return type:

bool

remove_visible_skill(token)[source]

Remove one visible skill by id or display name.

Parameters:

token (str) – Skill id (namespace@name) or display name.

Returns:

True when the skill was visible and removed.

Return type:

bool

visible_skill_ids()[source]

Return visible skill ids.

Parameters:

None.

Returns:

Copy of the visible skill id set.

Return type:

set[str]

visible_skill_count()[source]

Return the visible skill count.

Parameters:

None.

Returns:

Number of API calls made.

Return type:

int

list_visible_skills()[source]

List visible skill descriptors.

Parameters:

None.

Returns:

Visible skill descriptors.

Return type:

list[SkillDescriptor]

skill_catalog()[source]

Build a compact visible skill catalog.

Parameters:

None.

Returns:

Get the world description.

Return type:

list[dict[str, str]]

set_activated_skills(tokens)[source]

Set activated skills from visible skills.

Each entry may be a skill id (namespace@name) or a display name; both forms resolve against visible skills.

Parameters:

tokens (Iterable[str]) – Candidate skill ids or display names to activate.

Returns:

None.

Return type:

None

add_default_activated_skills(tokens)[source]

Activate configured default skills when they are visible.

Each entry may be a skill id or a display name.

Parameters:

tokens (Iterable[str]) – Skill ids or display names requested by outer agent config.

Returns:

None.

Return type:

None

activated_skill_ids()[source]

Return activated skill ids.

Parameters:

None.

Returns:

Copy of the activated skill id set.

Return type:

set[str]

activated_skill_count()[source]

Return activated skill count.

Parameters:

None.

Returns:

Number of API calls made.

Return type:

int

infer_single_script_skill_id()[source]

Infer a visible activated skill when exactly one has a default script.

Parameters:

None.

Returns:

Skill id for the only active scripted skill, or an empty string.

Return type:

str

resolve_skill_id(token, *, visible_only=True)[source]

Resolve a skill id or display name to a registry skill id.

Accepts either a registry skill id (namespace@name) or a bare display name — every public skill API in this runtime takes the same token and tolerates both forms. When visible_only is True (the default) resolution is restricted to visible skills; when False the whole registry is searched (use this for skills that are not yet visible, e.g. in add_visible_skill()).

Ambiguous display names (more than one match) resolve only when exactly one candidate is currently activated.

Parameters:
  • token (str) – Skill id (namespace@name) or display name from tool arguments / agent config.

  • visible_only (bool) – Restrict resolution to visible skills.

Returns:

Matching skill id, or an empty string when not found or ambiguous.

Return type:

str

resolve_skill_id_by_name(skill_name)[source]

Deprecated alias for resolve_skill_id().

Parameters:

skill_name (str) – Skill id or display name.

Returns:

Matching visible skill id, or an empty string.

Return type:

str

activate_skill(token)[source]

Activate a visible skill by id or display name.

Parameters:

token (str) – Skill id (namespace@name) or display name.

Returns:

Tuple of (activated, skill_id, skill_doc).

Return type:

tuple[bool, str, str]

activate_skill_by_name(skill_name)[source]

Deprecated alias for activate_skill().

Parameters:

skill_name (str) – Skill id or display name.

Returns:

Tuple of (activated, skill_id, skill_doc).

Return type:

tuple[bool, str, str]

deactivate_skill(token)[source]

Deactivate a visible skill by id or display name.

Parameters:

token (str) – Skill id (namespace@name) or display name.

Returns:

Tuple of (removed, skill_id).

Return type:

tuple[bool, str]

deactivate_skill_by_name(skill_name)[source]

Deprecated alias for deactivate_skill().

Parameters:

skill_name (str) – Skill id or display name.

Returns:

Tuple of (removed, skill_id).

Return type:

tuple[bool, str]

activated_skill_content_xml()[source]

Render docs and resource hints for activated skills.

Parameters:

None.

Returns:

XML-like skill content blocks for active skills.

Return type:

str

active_hook_skills(hook_type)[source]

List visible activated skills that declare one hook.

Parameters:

hook_type (str) – Lifecycle hook name.

Returns:

Skill descriptors eligible to run the hook.

Return type:

list[SkillDescriptor]

load_skill_doc(skill_id)[source]

Read a visible skill document.

Parameters:

skill_id (str) – Registry Module

Returns:

SKILL.md text, or an empty string.

Return type:

str

read_skill_file(skill_id, relative_path)[source]

Read one file inside a visible skill.

Parameters:
  • skill_id (str) – Registry Module

  • relative_path (str) – Path relative to the skill root.

Returns:

File text, or an empty string.

Return type:

str

resolve_skill_path(path)[source]

Map a path to a (skill_id, relative_path) inside a visible skill.

Used to recover when an agent tries to read a skill-bundled file (e.g. references/examples.md) via the generic workspace read tool, which only sees the agent workspace and rejects such paths as “escaping” it. Returning a mapping lets the caller transparently delegate to read_skill_file() instead of failing.

Two matching strategies, in order:

  1. Direct containment — the resolved absolute path is inside a visible skill root.

  2. Skill-name segment — some path component equals a visible skill’s skill_id or name (e.g. the model-emitted .../skills/daily-guidance/references/examples.md). The components after that segment are taken as the skill-relative path and must resolve to an existing file under the skill root.

Parameters:

path (str | Path) – Path to test (absolute, or relative to be matched by segment).

Returns:

(skill_id, posix_relative_path) if a visible skill file matches, else None.

Return type:

tuple[str, str] | None

async run_skill_script(skill_id, script_path, argv, *, timeout_sec=30)[source]

Run a script inside a visible skill.

Parameters:
  • skill_id (str) – Registry Module

  • script_path (str) – Path relative to the skill root, or empty to use the default script.

  • argv (list[str]) – Command-line arguments.

  • timeout_sec (int) – Execution timeout in seconds.

Returns:

Tool execution result.

Return type:

ScriptRunResult

async run_skill_hook(skill_id, hook_type, argv, *, timeout_sec=30)[source]

Run a lifecycle hook for a visible skill.

Parameters:
  • skill_id (str) – Registry Module

  • hook_type (str) – Lifecycle hook name.

  • argv (list[str]) – Command-line arguments.

  • timeout_sec (int) – Execution timeout in seconds.

Returns:

Tool execution result.

Return type:

ScriptRunResult

SkillScriptContext

class agentsociety2.agent.base.skill_runtime.SkillScriptContext(workspace_root, skill_dir, skill_id, skill_name, env=<factory>)[source]

Per-call context handed to an in-process skill entrypoint.

Replaces the process-global env vars (AGENT_WORK_DIR etc.) that the subprocess path relied on, so 50 agents can run their hooks in-process in parallel without racing on os.environ / cwd / sys.stdout.

Parameters:
  • workspace_root (Path) – This agent’s workspace root (was AGENT_WORK_DIR).

  • skill_dir (Path) – The skill package root (was SKILL_DIR).

  • skill_id (str) – Registry skill id (was SKILL_ID).

  • skill_name (str) – Display name (was SKILL_NAME).

  • env (dict[str, str]) – Snapshot of the env-var dict the subprocess path would have set.

workspace_root: Path
skill_dir: Path
skill_id: str
skill_name: str
env: dict[str, str]
__init__(workspace_root, skill_dir, skill_id, skill_name, env=<factory>)

SKILL.md Frontmatter

The SKILL.md file uses YAML frontmatter to declare skill metainformation:

---
name: my-skill
description: 触发条件 + 输出结果,选择阶段 LLM 唯一可见的文本
script: scripts/my_skill.py
hooks:
  pre_step: scripts/my_skill.py
---

Recognized frontmatter fields are name, description (the only text visible during selection and what determines activation), optional script (default relative script path), and hooks (lifecycle script mapping with keys such as pre_step / post_step). Skill registration ids look like namespace@name (built-in built-in@, custom custom@). Scripts execute by default in the agent process through entrypoint(argv, ctx) (see Agent Skills); skill ids starting with env: are redirected to ask_env and go through environment routing rather than script execution.