Skills 模块

本页分为两部分:

  • Research Skillsagentsociety2.skills 下的科研工作流模块。

  • Agent Skillsagentsociety2.agent.skills 下的 PersonAgent 技能注册与运行时机制。

Research Skills

总入口

AgentSociety2 技能模块。

本模块包含研究工作流和分析工具层入口,支持完整的科研流程:

技能列表

  • literature: 学术文献搜索与管理,支持检索、索引和格式化

  • experiment: 实验配置与执行,支持参数生成和配置验证

  • hypothesis: 假设生成与管理,支持创建、读取、列表和删除

  • analysis: 数据分析工具层,提供实验上下文读取、EDA 和工具注册能力

使用示例

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>)[源代码]

实验分析结果

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)[源代码]

Discover and normalize analysis assets.

__init__(workspace_path)[源代码]
discover_assets(experiment_id, hypothesis_id)[源代码]

Discover image assets under run/artifacts.

process_assets(assets, output_dir, *, include_embedded_data=True)[源代码]

Copy assets into assets/; optionally generate base64 payloads.

class agentsociety2.skills.analysis.ContextLoader(workspace_path)[源代码]

实验上下文加载

__init__(workspace_path)[源代码]
load_context(hypothesis_id, experiment_id)[源代码]

加载完整实验上下文

load_design(hypothesis_base, experiment_path)[源代码]

加载实验设计

class agentsociety2.skills.analysis.DataReader(db_path)[源代码]

Replay/数据库读取和理解

__init__(db_path)[源代码]
read_schema()[源代码]

读取数据库 Schema

read_sample_data(tables=None, limit=5)[源代码]

读取样本数据

compute_stats(schema)[源代码]

计算统计摘要

read_full_summary()[源代码]

读取完整数据摘要

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

数据统计摘要

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)[源代码]

完整数据摘要

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='')[源代码]

数据库 Schema 信息

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[源代码]

Generate exploratory data analysis artifacts.

__init__()[源代码]
resolve_table_selection(reader, tables)[源代码]

Return requested, selected, and invalid table names.

generate_quick_stats(db_path, max_rows=5000, tables=None)[源代码]
generate_missingno_report(db_path, output_dir, max_rows=50000, tables=None)[源代码]

Generate a missing-value report with missingno.

generate_correlation_report(db_path, output_dir, max_rows=50000, tables=None)[源代码]

Generate a correlation report.

generate_ydata_profile(db_path, output_dir, max_rows=10000, tables=None)[源代码]

Generate a ydata-profiling report.

generate_sweetviz_profile(db_path, output_dir, max_rows=10000, tables=None)[源代码]

Generate a Sweetviz report.

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

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>)[源代码]

完整实验状态

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)[源代码]

实验设计

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)[源代码]

单实验在 workspace 下的约定路径(只读,由 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)[源代码]

实验执行的状态

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>)[源代码]

跨多个实验的分析结果

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)[源代码]

单实验分析产物的输出路径。

这些路径按 hypothesis 聚合,位于 presentation/ 下,由 utils.presentation_paths 构建。

典型产物包括:

  • output_dir/ 下的双语报告、README.mddata/analysis_summary.json

  • charts/ 下的生成图表,以及复制到 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)[源代码]

报告所需要的其他资源

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)[源代码]

报告内容(支持中英双语)

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

中文优先,否则英文。

property full_content_html: 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.ReportPaths(markdown, html, markdown_zh=None, html_zh=None, markdown_en=None, html_en=None, assets_dir=None)[源代码]

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)[源代码]

综合报告输出路径(位于独立 synthesis 根目录下)。

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>)[源代码]

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)[源代码]

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)[源代码]

收集 run 目录下可供执行器使用的文件路径(含 replay/、同级文件、run/artifacts)。

agentsociety2.skills.analysis.experiment_paths(workspace_path, hypothesis_id, experiment_id)[源代码]

按约定聚合单实验路径;id 会做安全清洗。

agentsociety2.skills.analysis.extract_database_schema(db_path)[源代码]

Extract replay schema from metadata catalog tables.

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

将 replay metadata schema 格式化为 Markdown,可选行数。

agentsociety2.skills.analysis.presentation_paths(presentation_root, hypothesis_id, experiment_id)[源代码]

单实验分析产物路径:按 hypothesis 聚合,实验 id 仅保留接口兼容。

agentsociety2.skills.analysis.synthesis_paths(workspace_path)[源代码]

综合报告路径:写入独立的 synthesis/ 根目录。

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)[源代码]

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='')[源代码]

Tool for initializing and validating experiment configurations

__init__(workspace_path, progress_callback=None, tool_id='')[源代码]

Initialize the experiment config tool

参数:
  • workspace_path (str | Path) -- Path to 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()[源代码]
async execute(arguments)[源代码]

Execute the experiment configuration

参数:

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

返回:

ToolResult-like object with success, content, error fields

返回类型:

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)[源代码]

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)[源代码]

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)[源代码]

Format module suggestions into a helpful message

参数:

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

返回:

Formatted message string

返回类型:

str

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

Generate a complete hypothesis configuration

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

参数:
  • 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)

返回:

Complete hypothesis configuration dictionary

返回类型:

Dict[str, Any]

agentsociety2.skills.experiment.get_available_agent_modules()[源代码]

Get available agent modules with their descriptions

返回:

Dictionary mapping agent_type to description

返回类型:

Dict[str, str]

agentsociety2.skills.experiment.get_available_env_modules()[源代码]

Get available environment modules with their descriptions

返回:

Dictionary mapping module_type to description

返回类型:

Dict[str, str]

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

Get experiment status

参数:
  • workspace_path (Path) -- Path to workspace directory

  • hypothesis_id (str) -- Hypothesis ID

  • experiment_id (str) -- Experiment ID

  • run_id (str) -- Run ID (default: 'run')

返回:

ExperimentStatus object

返回类型:

ExperimentStatus

agentsociety2.skills.experiment.get_experiment_template(workspace_path, hypothesis_id, experiment_id)[源代码]

Get a template for experiment configuration

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

参数:
  • workspace_path (Path) -- Path to workspace directory

  • hypothesis_id (str) -- Hypothesis ID

  • experiment_id (str) -- Experiment ID

返回:

Template dictionary with structure to fill in

返回类型:

Dict[str, Any]

agentsociety2.skills.experiment.get_module_selection_guidance(topic, agent_classes=None, env_modules=None)[源代码]

Generate guidance text for module selection

参数:
  • topic (str) -- Research topic for context

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

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

返回:

Guidance text for helping with module selection

返回类型:

str

agentsociety2.skills.experiment.get_modules_summary()[源代码]

Get a formatted summary of available modules for LLM prompts

返回:

Formatted string with available modules

返回类型:

str

async agentsociety2.skills.experiment.list_experiments(workspace_path, hypothesis_id=None)[源代码]

List experiments

参数:
  • workspace_path (Path) -- Path to workspace directory

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

返回:

List of ExperimentInfo objects

返回类型:

List[ExperimentInfo]

备注

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)[源代码]

Start an experiment

参数:
  • workspace_path (Path) -- Path to 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)

返回:

Result dictionary with status and info

返回类型:

Dict[str, Any]

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

Stop a running experiment

参数:
  • workspace_path (Path) -- Path to workspace directory

  • hypothesis_id (str) -- Hypothesis ID

  • experiment_id (str) -- Experiment ID

  • run_id (str) -- Run ID (default: 'run')

返回:

Result dictionary with status

返回类型:

Dict[str, Any]

agentsociety2.skills.experiment.suggest_modules_for_topic(topic)[源代码]

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.

参数:

topic (str) -- Research topic or description

返回:

Dictionary with suggested modules and rationale

返回类型:

Dict[str, Any]

agentsociety2.skills.experiment.validate_experiment_ready(workspace_path, hypothesis_id, experiment_id)[源代码]

Check if an experiment is ready to run

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

参数:
  • workspace_path (Path) -- Path to workspace directory

  • hypothesis_id (str) -- Hypothesis ID

  • experiment_id (str) -- Experiment ID

返回:

Tuple of (is_ready, missing_items, context)

返回类型:

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

agentsociety2.skills.experiment.validate_hypothesis_modules(hypothesis_data)[源代码]

Validate that a hypothesis has required modules

参数:

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

返回:

Tuple of (is_valid, error_messages, guidance_dict)

返回类型:

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

agentsociety2.skills.experiment.validate_module_selection(agent_classes=None, env_modules=None)[源代码]

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

参数:
  • agent_classes (List[str] | None) -- List of agent class types

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

返回:

Tuple of (is_valid, list of error messages)

返回类型:

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)[源代码]

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)[源代码]

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)[源代码]

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)[源代码]

Add a new hypothesis

参数:
  • workspace_path (Path) -- Path to workspace directory

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

返回:

Result dictionary with success status and info

返回类型:

Dict[str, Any]

agentsociety2.skills.hypothesis.add_hypothesis_with_validation(workspace_path, hypothesis_data, validate_modules=True)[源代码]

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)

参数:
  • workspace_path (Path) -- Path to workspace directory

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

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

返回:

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

返回类型:

Dict[str, Any]

agentsociety2.skills.hypothesis.create_hypothesis_structure(workspace_path, hypothesis_id, hypothesis_model)[源代码]

Create hypothesis directory structure

参数:
  • workspace_path (Path) -- Path to workspace directory

  • hypothesis_id (str) -- Hypothesis ID

  • hypothesis_model (HypothesisDataModel) -- Validated hypothesis data model

返回:

Path to created hypothesis directory

返回类型:

Path

agentsociety2.skills.hypothesis.delete_hypothesis(workspace_path, hypothesis_id=None, hypothesis_path=None)[源代码]

Delete a hypothesis folder

参数:
  • workspace_path (Path) -- Path to workspace directory

  • hypothesis_id (str | None) -- Hypothesis ID (e.g., '1', '2')

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

返回:

Result dictionary with deletion status

返回类型:

Dict[str, Any]

agentsociety2.skills.hypothesis.find_existing_hypotheses(workspace_path)[源代码]

Find existing hypothesis directories

参数:

workspace_path (Path) -- Path to workspace directory

返回:

Sorted list of hypothesis directory paths

返回类型:

List[Path]

agentsociety2.skills.hypothesis.generate_experiment_markdown(group, exp_idx)[源代码]

Generate EXPERIMENT.md content

参数:
返回:

Markdown content for EXPERIMENT.md

返回类型:

str

agentsociety2.skills.hypothesis.generate_hypothesis_markdown(hypothesis_model)[源代码]

Generate HYPOTHESIS.md content

参数:

hypothesis_model (HypothesisDataModel) -- Validated hypothesis data model

返回:

Markdown content for HYPOTHESIS.md

返回类型:

str

agentsociety2.skills.hypothesis.generate_sim_settings(hypothesis_model)[源代码]

Generate SIM_SETTINGS.json content

参数:

hypothesis_model (HypothesisDataModel) -- Validated hypothesis data model

返回:

SIM_SETTINGS dictionary

返回类型:

Dict[str, Any]

agentsociety2.skills.hypothesis.get_hypothesis(workspace_path, hypothesis_id=None, hypothesis_path=None)[源代码]

Get hypothesis details

参数:
  • workspace_path (Path) -- Path to workspace directory

  • hypothesis_id (str | None) -- Hypothesis ID (e.g., '1', '2')

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

返回:

Result dictionary with hypothesis details

返回类型:

Dict[str, Any]

agentsociety2.skills.hypothesis.get_next_hypothesis_id(workspace_path)[源代码]

Get the next hypothesis ID

参数:

workspace_path (Path) -- Path to workspace directory

返回:

Next hypothesis ID as string

返回类型:

str

agentsociety2.skills.hypothesis.list_hypotheses(workspace_path)[源代码]

List all hypotheses

参数:

workspace_path (Path) -- Path to workspace directory

返回:

Result dictionary with list of hypotheses

返回类型:

Dict[str, Any]

agentsociety2.skills.hypothesis.validate_hypothesis_schema(hypothesis_data)[源代码]

Validate hypothesis data against schema

参数:

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

返回:

Tuple of (is_valid, error_message, validated_model)

返回类型:

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

literature

Literature search and management.

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)[源代码]

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)[源代码]

Validate save time format

classmethod validate_doi(v)[源代码]

Validate DOI format (basic check)

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

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)[源代码]

Format a single literature article as markdown

参数:
  • article (Dict[str, Any]) -- Article data dictionary

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

返回:

Markdown formatted string

返回类型:

str

agentsociety2.skills.literature.format_search_results(articles, total, query)[源代码]

Format search results for display

参数:
  • articles (list) -- List of article dictionaries

  • total (int) -- Total number of articles

  • query (str) -- Search query

返回:

Formatted string for display

返回类型:

str

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

Generate a summary using LLM to guide users on next steps

参数:
  • 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.

返回:

Generated summary text

返回类型:

str

agentsociety2.skills.literature.is_chinese_text(text)[源代码]

检测文本是否包含中文字符

参数:

text (str) -- 待检测的文本

返回:

如果包含中文字符返回True,否则返回False

返回类型:

bool

agentsociety2.skills.literature.load_literature_index(workspace_path)[源代码]

Load literature index from workspace

参数:

workspace_path (Path) -- Path to workspace directory

返回:

LiteratureIndex object or None if file doesn't exist

返回类型:

LiteratureIndex | None

agentsociety2.skills.literature.sanitize_filename(filename)[源代码]

Clean filename by removing illegal characters

参数:

filename (str) -- Original filename

返回:

Sanitized filename safe for filesystem

返回类型:

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)[源代码]

Search academic literature through the MCP gateway.

参数:
  • query (str) -- Search query; Chinese text is translated to English when detected.

  • limit (int) -- Maximum number of articles per sub-query (default 10).

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

  • year_from (int | None) -- Optional start publication year filter.

  • year_to (int | None) -- Optional end publication year filter.

  • 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) -- Split complex queries into subtopics and merge results.

  • 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.

返回:

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

返回类型:

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)[源代码]

Search for literature and save results to workspace

参数:
  • query (str) -- Search query (supports Chinese, will be translated to English)

  • workspace_path (Path) -- Path to 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

返回:

Dictionary with search results and saved file information

返回类型:

Dict[str, Any]

备注

当前仓库中可公开使用的 research skills 模块为 analysisexperimenthypothesisliteratureweb_research 目录当前没有保留 可读源码,因此未列为文档 API 表面。

Agent Skills

技能基础设施(发现、可见性/激活、脚本执行、生命周期 hook)已从 agent/skills/ 下沉到 agentsociety2.agent.baseagent/skills/ 目录现在只承载技能**内容**(如内置的 daily-guidance/)。设计说明见 Agent Skills(智能体技能)

SkillRegistry

class agentsociety2.agent.base.skill_registry.SkillRegistry[源代码]

基类:object

Registry for Skill metadata.

参数:

None.

__init__()[源代码]

Initialize an empty registry.

参数:

None.

返回:

None.

返回类型:

None

scan_builtin(root=None)[源代码]

Scan built-in skills once.

参数:

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

返回:

Added skill ids.

返回类型:

list[str]

scan_custom(skills_root, namespace='custom')[源代码]

Scan a custom skill root.

参数:
  • skills_root (Path) -- Directory containing skill subdirectories.

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

返回:

Added skill ids.

返回类型:

list[str]

scan_env(skills_dir, env_name)[源代码]

Scan skills provided by an environment module.

参数:
  • skills_dir (Path) -- Directory containing skill subdirectories.

  • env_name (str) -- Environment module name.

返回:

Added skill ids.

返回类型:

list[str]

list_all()[源代码]

List all registered skills.

参数:

None.

返回:

Registered skill descriptors.

返回类型:

list[SkillDescriptor]

get(skill_id)[源代码]

Return one skill descriptor by id.

参数:

skill_id (str) -- Registry skill id.

返回:

Matching descriptor, or None.

返回类型:

SkillDescriptor | None

find_by_name(name)[源代码]

Find skill descriptors by display name.

参数:

name (str) -- Skill display name.

返回:

Matching descriptors.

返回类型:

list[SkillDescriptor]

read_skill_doc(skill_id)[源代码]

Read one skill's SKILL.md.

参数:

skill_id (str) -- Registry skill id.

返回:

Skill document text, or an empty string.

返回类型:

str

read_skill_file(skill_id, relative_path)[源代码]

Read one file inside a skill directory.

参数:
  • skill_id (str) -- Registry skill id.

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

返回:

File text, or an empty string.

返回类型:

str

list_hooks(hook_type)[源代码]

List skills declaring one hook.

参数:

hook_type (str) -- Lifecycle hook name.

返回:

Skill descriptors that declare the hook.

返回类型:

list[SkillDescriptor]

copy()[源代码]

Copy this registry.

参数:

None.

返回:

Shallow registry copy.

返回类型:

SkillRegistry

SkillDescriptor

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

Skill metadata.

参数:
  • skill_id (str) -- Stable registry skill id.

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

  • namespace (str) -- Skill namespace.

  • description (str) -- Catalog 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()[源代码]

List files shipped under this skill root.

参数:

None.

返回:

Relative resource file paths under the skill root.

返回类型:

list[str]

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

AgentSkillRuntime

class agentsociety2.agent.base.skill_runtime.AgentSkillRuntime(agent_id, registry)[源代码]

基类:object

Runtime for skill visibility, activation, and execution.

__init__(agent_id, registry)[源代码]

Initialize the skill runtime.

参数:
  • agent_id (int) -- Numeric agent id.

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

返回:

None.

返回类型:

None

bind_workspace(*, workspace_root, fs, trace_writer)[源代码]

Bind this runtime to an agent-owned workspace.

参数:
  • workspace_root (Path) -- Agent workspace root created by the agent.

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

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

返回:

None.

返回类型:

None

workspace_root()[源代码]

Return the workspace root.

参数:

None.

返回:

Absolute workspace root path.

返回类型:

Path

property is_initialized: bool

Return whether the workspace is initialized.

参数:

None.

返回:

True when the workspace has been initialized.

property fs: WorkspaceFS

Return the workspace filesystem facade.

参数:

None.

返回:

Workspace filesystem facade.

set_visible_skills(tokens)[源代码]

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.

参数:

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

返回:

None.

返回类型:

None

add_visible_skill(token)[源代码]

Add one visible skill by id or display name.

参数:

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

返回:

True when the skill exists and was made visible.

返回类型:

bool

remove_visible_skill(token)[源代码]

Remove one visible skill by id or display name.

参数:

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

返回:

True when the skill was visible and removed.

返回类型:

bool

visible_skill_ids()[源代码]

Return visible skill ids.

参数:

None.

返回:

Copy of the visible skill id set.

返回类型:

set[str]

visible_skill_count()[源代码]

Return the visible skill count.

参数:

None.

返回:

Number of visible skills.

返回类型:

int

list_visible_skills()[源代码]

List visible skill descriptors.

参数:

None.

返回:

Visible skill descriptors.

返回类型:

list[SkillDescriptor]

skill_catalog()[源代码]

Build a compact visible skill catalog.

参数:

None.

返回:

Catalog entries with name and description.

返回类型:

list[dict[str, str]]

set_activated_skills(tokens)[源代码]

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.

参数:

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

返回:

None.

返回类型:

None

add_default_activated_skills(tokens)[源代码]

Activate configured default skills when they are visible.

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

参数:

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

返回:

None.

返回类型:

None

activated_skill_ids()[源代码]

Return activated skill ids.

参数:

None.

返回:

Copy of the activated skill id set.

返回类型:

set[str]

activated_skill_count()[源代码]

Return activated skill count.

参数:

None.

返回:

Number of activated skills.

返回类型:

int

infer_single_script_skill_id()[源代码]

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

参数:

None.

返回:

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

返回类型:

str

resolve_skill_id(token, *, visible_only=True)[源代码]

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.

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

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

返回:

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

返回类型:

str

resolve_skill_id_by_name(skill_name)[源代码]

Deprecated alias for resolve_skill_id().

参数:

skill_name (str) -- Skill id or display name.

返回:

Matching visible skill id, or an empty string.

返回类型:

str

activate_skill(token)[源代码]

Activate a visible skill by id or display name.

参数:

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

返回:

Tuple of (activated, skill_id, skill_doc).

返回类型:

tuple[bool, str, str]

activate_skill_by_name(skill_name)[源代码]

Deprecated alias for activate_skill().

参数:

skill_name (str) -- Skill id or display name.

返回:

Tuple of (activated, skill_id, skill_doc).

返回类型:

tuple[bool, str, str]

deactivate_skill(token)[源代码]

Deactivate a visible skill by id or display name.

参数:

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

返回:

Tuple of (removed, skill_id).

返回类型:

tuple[bool, str]

deactivate_skill_by_name(skill_name)[源代码]

Deprecated alias for deactivate_skill().

参数:

skill_name (str) -- Skill id or display name.

返回:

Tuple of (removed, skill_id).

返回类型:

tuple[bool, str]

activated_skill_content_xml()[源代码]

Render docs and resource hints for activated skills.

参数:

None.

返回:

XML-like skill content blocks for active skills.

返回类型:

str

active_hook_skills(hook_type)[源代码]

List visible activated skills that declare one hook.

参数:

hook_type (str) -- Lifecycle hook name.

返回:

Skill descriptors eligible to run the hook.

返回类型:

list[SkillDescriptor]

load_skill_doc(skill_id)[源代码]

Read a visible skill document.

参数:

skill_id (str) -- Registry skill id.

返回:

SKILL.md text, or an empty string.

返回类型:

str

read_skill_file(skill_id, relative_path)[源代码]

Read one file inside a visible skill.

参数:
  • skill_id (str) -- Registry skill id.

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

返回:

File text, or an empty string.

返回类型:

str

resolve_skill_path(path)[源代码]

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.

参数:

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

返回:

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

返回类型:

tuple[str, str] | None

async run_skill_script(skill_id, script_path, argv, *, timeout_sec=30)[源代码]

Run a script inside a visible skill.

参数:
  • skill_id (str) -- Registry skill id.

  • 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.

返回:

Script run result.

返回类型:

ScriptRunResult

async run_skill_hook(skill_id, hook_type, argv, *, timeout_sec=30)[源代码]

Run a lifecycle hook for a visible skill.

参数:
  • skill_id (str) -- Registry skill id.

  • hook_type (str) -- Lifecycle hook name.

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

  • timeout_sec (int) -- Execution timeout in seconds.

返回:

Script run result.

返回类型:

ScriptRunResult

SkillScriptContext

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

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.

参数:
  • 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

SKILL.md 文件使用 YAML frontmatter 声明 skill 元信息:

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

frontmatter 之后识别的字段:namedescription``(选择阶段唯一可见,决定是否激活)、 可选的 ``script``(默认脚本相对路径)与 ``hooks``(生命周期脚本映射,键如 ``pre_step / post_step)。Skill 注册 id 形如 namespace@name``(内置 ``built-in@、自定义 custom@)。 脚本默认在 agent 进程内经 entrypoint(argv, ctx) 执行(详见 Agent Skills(智能体技能));以 env: 开头的 skill id 会被重定向到 ask_env,走环境路由而非脚本。