### Quick Start Analysis Setup Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/agentsociety2/skills/analysis/README.md Demonstrates how to initialize and use core analysis components like ContextLoader, DataReader, and EDAGenerator to load experiment data and generate quick statistics. ```python from pathlib import Path from agentsociety2.skills.analysis import ContextLoader, DataReader, EDAGenerator workspace = Path("./workspace") db_path = workspace / "hypothesis_1" / "experiment_1" / "run" / "sqlite.db" context = ContextLoader(workspace).load_context("1", "1") summary = DataReader(db_path).read_full_summary() quick_stats = EDAGenerator().generate_quick_stats( db_path, tables=["core_agent_profile"], ) ``` -------------------------------- ### Frontend Development Setup and Commands Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/CONTRIBUTING.md Sets up the frontend's Node.js dependencies and provides commands for linting and building. Run 'npm ci' to install dependencies. ```bash cd frontend npm ci npm run lint npm run build npm audit --audit-level=high ``` -------------------------------- ### Setup docx-js for Document Creation Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/skills/docx/SKILL.md Imports necessary components from the 'docx' library and initializes a new Document object. Install with 'npm install -g docx'. ```javascript const { Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell, ImageRun, Header, Footer, AlignmentType, PageOrientation, LevelFormat, ExternalHyperlink, InternalHyperlink, Bookmark, FootnoteReferenceRun, PositionalTab, PositionalTabAlignment, PositionalTabRelativeTo, PositionalTabLeader, TabStopType, TabStopPosition, Column, SectionType, TableOfContents, HeadingLevel, BorderStyle, WidthType, ShadingType, VerticalAlign, PageNumber, PageBreak } = require('docx'); const doc = new Document({ sections: [{ children: [/* content */] }] }); Packer.toBuffer(doc).then(buffer => fs.writeFileSync("doc.docx", buffer)); ``` -------------------------------- ### Python and Extension Setup Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/AGENTS.md Commands to synchronize Python dependencies using uv and install Node.js dependencies for the extension. ```bash # Python (workspace root) uv sync cd packages/agentsociety2 && uv sync --extra dev # Extension cd extension && npm ci && npm run lint && npm run build # Frontend cd frontend && npm ci && npm run lint && npm run build ``` -------------------------------- ### AgentSociety 2 Quick Start Example Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/README.md A basic example demonstrating the initialization and usage of AgentSociety 2 with a PersonAgent and a SimpleSocialSpace environment. ```python import asyncio from datetime import datetime from agentsociety2 import PersonAgent from agentsociety2.env import CodeGenRouter from agentsociety2.contrib.env import SimpleSocialSpace from agentsociety2.society import AgentSociety async def main(): agent = PersonAgent( id=1, profile={"name": "Alice", "personality": "friendly and curious"}, ) env = CodeGenRouter( env_modules=[SimpleSocialSpace(agent_id_name_pairs=[(agent.id, agent.name)])] ) society = AgentSociety(agents=[agent], env_router=env, start_t=datetime.now()) await society.init() response = await society.ask("What's your name?") print(response) await society.close() asyncio.run(main()) ``` -------------------------------- ### Extension Development Setup and Commands Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/CONTRIBUTING.md Sets up the extension's Node.js dependencies and provides commands for development, linting, building, and auditing. Run 'npm ci' to install dependencies. ```bash cd extension npm ci npm run dev # watch TypeScript + webview npm run lint npm run build npm audit --audit-level=high ``` -------------------------------- ### Install Dependencies Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/DEVELOPMENT.md Navigate to the extension directory and install Node.js dependencies using npm. ```bash cd extension npm install ``` -------------------------------- ### Configuration File Example Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety-benchmark/agentsociety_benchmark/benchmarks/BehaviorModeling/README.md Example YAML configuration file for setting up the agent, including LLM provider, model, and API key. ```yaml # config.yml llm: provider: openai model: gpt-4 api_key: your-api-key # Other configuration items... ``` -------------------------------- ### Complete Workflow Example Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/cli.md A comprehensive example demonstrating the full workflow of preparing configurations, running experiments in foreground and background, monitoring logs, and analyzing results. ```bash # 1. 准备配置文件 mkdir -p my_experiment/init my_experiment/run # ... 创建 init_config.json 和 steps.yaml ... # 2. 前台测试运行 python -m agentsociety2.society.cli \ --config my_experiment/init/init_config.json \ --steps my_experiment/init/steps.yaml \ --run-dir my_experiment/run \ --log-level DEBUG # 3. 后台生产运行 python -m agentsociety2.society.cli \ --config my_experiment/init/init_config.json \ --steps my_experiment/init/steps.yaml \ --run-dir my_experiment/run \ --experiment-id "exp_001" \ --log-level INFO \ --log-file my_experiment/run/output.log & # 4. 监控运行 tail -f my_experiment/run/output.log # 5. 完成后分析结果 sqlite3 my_experiment/run/sqlite.db "SELECT dataset_id, table_name FROM replay_dataset_catalog;" ``` -------------------------------- ### Run Full Example (Bash) Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/agentsociety2/contrib/env/social_media/recommendation/README.md Command to navigate to the project directory and run the complete example script, which covers simple usage, incremental updates, batch recommendations, and model persistence. ```bash cd packages/agentsociety2 python example_new_architecture.py ``` -------------------------------- ### Install EasyPaper with uv Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/plugins/easypaper/skills/easypaper-setup-environment/SKILL.md Use `uv` to create a virtual environment and install the EasyPaper package. This is the preferred method if `uv` is available. ```bash uv venv .easypaper-env source .easypaper-env/bin/activate # or .easypaper-env/Scripts/activate on Windows uv pip install -e . # if in repo root # OR uv pip install easypaper[server] # if installing from PyPI ``` -------------------------------- ### Complete Benchmark Configuration Example Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety-benchmark/README.md A comprehensive YAML example for benchmark configuration, including LLM details and environment settings. Adjust 'api_key', 'model', and 'provider' as needed. ```yaml # config.yaml llm: - api_key: YOUR-API-KEY # LLM API key model: YOUR-MODEL # LLM model provider: PROVIDER # LLM provider semaphore: 200 # Semaphore for LLM requests, control the max number of concurrent requests env: db: enabled: true # Whether to enable database home_dir: .agentsociety-benchmark/agentsociety_data ``` -------------------------------- ### Install AgentSociety 2 with All Dependencies Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/installation.md Install AgentSociety 2 including all available dependencies, such as development and documentation packages. This provides a complete setup. ```bash pip install "agentsociety2[all]" ``` -------------------------------- ### Install AgentSociety Benchmark from Source Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety-benchmark/README.md Install the benchmark toolkit by cloning the repository and using pip. This method is suitable for development or when using the latest unreleased code. ```bash git clone cd packages/agentsociety-benchmark pip install -e . ``` -------------------------------- ### Start Backend Service Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/DEVELOPMENT.md Navigate to the project directory and use the provided command to start the backend FastAPI service. This command assumes you are in the 'packages/agentsociety2' directory. ```bash cd packages/agentsociety2 uv run python -m agentsociety2.backend.run ``` -------------------------------- ### SKILL.md Structure Example Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/skill_guide.md Example of a basic SKILL.md file defining a skill's name, description, usage, input/output, and execution steps. ```markdown --- name: my-skill description: 一句话描述功能。什么时候使用。产生什么输出。 --- # My Skill ## 何时使用 描述触发条件。 ## 输入文件 - `state/observation.txt`:当前观察(如果存在) - `state/needs.json`:需求状态(如果存在) ## 执行步骤 1. 首先,用 `workspace_read` 读取需要的文件 2. 然后,分析内容并做出决策 3. 最后,用 `workspace_write` 写入输出文件 ## 输出格式 ```json { "field1": "描述", "field2": 0.5 } ``` ## 示例 **输入**: ``` state/observation.txt: "在公园遇到了Alice" ``` **输出**: ```json { "event": "met Alice at park", "emotion": "happy" } ``` ``` -------------------------------- ### Install Python Dependencies with uv Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/CLAUDE.md Installs all project dependencies using uv. Run this in the workspace root. ```bash uv sync ``` -------------------------------- ### Example Stage Transition Commit Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/skills/agentsociety-research-pipeline/v1.0.0/SKILL.md An example of committing a transition from the 'literature_search' stage to a 'completed' status. ```bash $PYTHON_PATH .agentsociety/bin/ags.py research-pipeline update-stage literature_search completed git add -A && git commit -m "pipeline: literature_search → completed" ``` -------------------------------- ### Install AgentSociety Benchmark via Pip Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety-benchmark/README.md Install the benchmark toolkit directly using pip. This is the recommended method for general usage if the package is published. ```bash pip install agentsociety-benchmark ``` -------------------------------- ### Full dataset.json Schema Example Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/skills/agentsociety-create-dataset/v1.0.0/references/dataset-schema.md This is an example of a complete dataset.json file, illustrating all the fields and their expected formats. ```json { "id": "lowercase-slug-with-dashes", "name": "Human-readable name", "description": "What this dataset contains", "category": "surveys", "version": "1.0.0", "tags": ["tag1", "tag2"], "author": "Author Name", "license": "CC BY 4.0" } ``` -------------------------------- ### Example .env File Configuration Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/installation.md An example of a .env file showing how to configure LLM API keys, agent behavior, specialized LLM instances, and the data directory. This file allows for centralized configuration management. ```dotenv # Required - LLM API Configuration AGENTSOCIETY_LLM_API_KEY=your-api-key AGENTSOCIETY_LLM_API_BASE=https://api.openai.com/v1 AGENTSOCIETY_LLM_MODEL=gpt-5.5 # Optional - Agent Behavior Configuration AGENT_MODEL=gpt-5.5 # Override model for agents AGENT_CONTEXT_WINDOW=200000 # Model context window AGENT_MAX_TOOL_ROUNDS=24 # Max tool loop rounds # Optional - Specialized LLM instances (fallback to default) AGENTSOCIETY_CODER_LLM_MODEL=gpt-5.5 AGENTSOCIETY_NANO_LLM_MODEL=gpt-5.5 AGENTSOCIETY_EMBEDDING_MODEL=text-embedding-3-large AGENTSOCIETY_EMBEDDING_DIMS=1024 AGENTSOCIETY_HOME_DIR=./agentsociety_data ``` -------------------------------- ### Start Frontend Development Server Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/CLAUDE.md Starts the Vite development server for the React frontend. The application will be available at http://localhost:5173. ```bash cd frontend npm run dev ``` -------------------------------- ### RecommendationService fit() API Example Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/agentsociety2/contrib/env/social_media/recommendation/README.md Example demonstrating how to use the `fit` method of the RecommendationService to train the recommendation model with provided rating data. ```python data = RatingMatrix.from_ratings(ratings) await service.fit(data) ``` -------------------------------- ### Install AgentSociety 2 with Documentation Dependencies Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/installation.md Install AgentSociety 2 with dependencies required for building documentation. Use this if you need to generate or modify documentation. ```bash pip install "agentsociety2[docs]" ``` -------------------------------- ### Complete Weather Environment Example Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/env_modules.md A full example demonstrating a custom environment module 'WeatherEnvironment' with tools for observing weather and changing conditions. It's integrated into an AgentSociety simulation. ```python from typing import Dict from datetime import datetime from agentsociety2.env import EnvBase, tool, CodeGenRouter from agentsociety2 import PersonAgent from agentsociety2.society import AgentSociety class WeatherEnvironment(EnvBase): """A simple weather environment module.""" def __init__(self): super().__init__() self._weather = "sunny" self._temperature = 25 self._agent_locations: Dict[int, str] = {} @tool(readonly=True, kind="observe") def get_weather(self, agent_id: int) -> str: """Get the current weather for an agent's location.""" location = self._agent_locations.get(agent_id, "unknown") return f"The weather in {location} is {self._weather} with {self._temperature}°C." @tool(readonly=False) def change_weather(self, weather: str, temperature: int) -> str: """Change the weather conditions.""" self._weather = weather self._temperature = temperature return f"Weather changed to {weather} at {temperature}°C." async def step(self, tick: int, t: datetime) -> None: """Update environment state for one simulation step.""" self.t = t # Update time-dependent state here if needed # Use the custom module env_router = CodeGenRouter(env_modules=[WeatherEnvironment()]) agent = PersonAgent(id=1, profile={"name": "Bob"}) society = AgentSociety( agents=[agent], env_router=env_router, start_t=datetime.now(), ) await society.init() ``` -------------------------------- ### Skill Metadata Example Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/agentsociety2/agent/README.md Provides an example of skill metadata in YAML format, including its name and description, which are used by the system for skill cataloging and execution. ```yaml --- name: cognition description: 从观察与记忆更新 emotion.json 和 intention.json(LLM 驱动,无默认子进程脚本)。 --- ``` -------------------------------- ### Complete Hurricane Mobility Agent Example Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety-benchmark/agentsociety_benchmark/benchmarks/HurricaneMobility/README.md A comprehensive example demonstrating a hurricane-aware agent's implementation. It includes fetching agent status, environment details, and implementing mobility logic based on time and weather conditions. ```python from agentsociety_benchmark.benchmarks import HurricaneMobilityAgent from pycityproto.city.person.v2.motion_pb2 import Status import random class MyHurricaneMobilityAgent(HurricaneMobilityAgent): """ A complete example agent for the Hurricane Mobility Generation benchmark. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) async def forward(self): # Get agent's home and workplace home = await self.status.get("home") home_aoi_id = home["aoi_position"]["aoi_id"] workplace = await self.status.get("work") workplace_aoi_id = workplace["aoi_position"]["aoi_id"] # Get current agent status citizen_status = await self.status.get("status") if citizen_status in self.movement_status: # Agent is moving, let it continue return # Get current position and time agent_position = await self.status.get("position") x = agent_position["xy_position"]["x"] y = agent_position["xy_position"]["y"] day, time = self.environment.get_datetime() # Get environment information all_aois = self.environment.map.get_all_aois() all_pois = self.environment.map.get_all_pois() # Get current weather information weather_info = self.get_current_weather() # Hurricane-aware decision logic if "is the weather is not good": # Hurricane is active - implement evacuation behavior else: # Normal weather conditions - regular mobility patterns if 6 <= time // 3600 <= 8: # 6:00-8:00 AM # Morning: go to work if workplace_aoi_id: await self.go_to_aoi(workplace_aoi_id) elif 12 <= time // 3600 <= 13: # 12:00-1:00 PM # Lunch time: eating out await self.go_to_aoi(random.choice(list(all_aois.keys()))) elif 18 <= time // 3600 <= 20: # 6:00-8:00 PM # Evening: leisure or shopping await self.go_to_aoi(random.choice(list(all_aois.keys()))) elif 22 <= time // 3600 or time // 3600 <= 6: # 10:00 PM - 6:00 AM # Night: go home to sleep if home_aoi_id: await self.go_to_aoi(home_aoi_id) else: # Other times: random activity await self.go_to_aoi(random.choice(list(all_aois.keys()))) ``` -------------------------------- ### Install EasyPaper with standard Python venv Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/plugins/easypaper/skills/easypaper-setup-environment/SKILL.md Use standard Python `venv` to create a virtual environment and install EasyPaper. This method is used if `uv` is not available. ```bash python -m venv .easypaper-env source .easypaper-env/bin/activate pip install -e . # or pip install easypaper[server] ``` -------------------------------- ### Complete Daily Mobility Agent Example Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety-benchmark/agentsociety_benchmark/benchmarks/DailyMobility/README.md A comprehensive example of a Daily Mobility Agent, demonstrating initialization, movement status checks, environment data retrieval, and decision-making logic for daily activities like going to work, lunch, leisure, and sleep. ```python from agentsociety_benchmark.benchmarks import DailyMobilityAgent from pycityproto.city.person.v2.motion_pb2 import Status import random class MyDailyMobilityAgent(DailyMobilityAgent): """ A complete example agent for the Daily Mobility Generation benchmark. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) async def forward(self): # Get agent's home and workplace home = await self.status.get("home") home_aoi_id = home["aoi_position"]["aoi_id"] workplace = await self.status.get("work") work_aoi_id = workplace["aoi_position"]["aoi_id"] # Get current agent status citizen_status = await self.status.get("status") if citizen_status in self.movement_status: # Agent is moving, let it continue return # Get current position and time agent_position = await self.status.get("position") x = agent_position["xy_position"]["x"] y = agent_position["xy_position"]["y"] day, time = self.environment.get_datetime() # Get environment information all_aois = self.environment.map.get_all_aois() all_pois = self.environment.map.get_all_pois() # Simple decision logic based on time if 6 <= time // 3600 <= 8: # 6:00-8:00 AM # Morning: go to work if workplace_aoi_id: await self.go_to_aoi(workplace_aoi_id) await self.log_intention("work") elif 12 <= time // 3600 <= 13: # 12:00-1:00 PM # Lunch time: eating out await self.go_to_aoi(random.choice(list(all_aois.keys()))) await self.log_intention("eating out") elif 18 <= time // 3600 <= 20: # 6:00-8:00 PM # Evening: leisure or shopping await self.go_to_aoi(random.choice(list(all_aois.keys()))) await self.log_intention(random.choice(["leisure and entertainment", "shopping"])) elif 22 <= time // 3600 or time // 3600 <= 6: # 10:00 PM - 6:00 AM # Night: go home to sleep if home_aoi_id: await self.go_to_aoi(home_aoi_id) await self.log_intention("sleep") else: # Other times: random activity await self.go_to_aoi(random.choice(list(all_aois.keys()))) await self.log_intention(random.choice(self.intention_list)) ``` -------------------------------- ### Install Specific Version of AgentSociety Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/01-get-started/02-installation.md Install a specific version of AgentSociety, for example, version 1.3.7, by specifying the version number in the pip install command. ```bash pip install "agentsociety==1.3.7" ``` -------------------------------- ### RecommendationService predict() API Example Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/agentsociety2/contrib/env/social_media/recommendation/README.md Example showing how to use the `predict` method of the RecommendationService to get a predicted rating for a specific user and item. ```python score = await service.predict(user_id=1, item_id=100) # 返回: 4.2 ``` -------------------------------- ### Setup and Basic Presentation Structure Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/skills/pptx/pptxgenjs.md Initializes a new presentation, sets layout and metadata, adds a slide with text, and saves the presentation to a file. ```javascript const pptxgen = require("pptxgenjs"); let pres = new pptxgen(); pres.layout = 'LAYOUT_16x9'; // or 'LAYOUT_16x10', 'LAYOUT_4x3', 'LAYOUT_WIDE' pres.author = 'Your Name'; pres.title = 'Presentation Title'; let slide = pres.addSlide(); slide.addText("Hello World!", { x: 0.5, y: 0.5, fontSize: 36, color: "363636" }); pres.writeFile({ fileName: "Presentation.pptx" }); ``` -------------------------------- ### Install AgentSociety 2 from Source Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/installation.md Install AgentSociety 2 directly from its source code repository. This method is useful for getting the latest unreleased changes. ```bash git clone https://github.com/tsinghua-fib-lab/agentsociety.git cd agentsociety/packages/agentsociety2 pip install -e . ``` -------------------------------- ### Accessing Map and POI Information Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety-benchmark/agentsociety_benchmark/benchmarks/DailyMobility/README.md Examples for retrieving all AOIs and POIs from the environment's map, and how to get specific AOI details. ```python # Get all AOIs (Areas of Interest) all_aois = self.environment.map.get_all_aois() """ AOI collection contains the following attributes: - id (int): AOI ID - positions (list[XYPosition]): Polygon shape coordinates - area (float): Area in square meters - driving_positions (list[LanePosition]): Connection points to driving lanes - walking_positions (list[LanePosition]): Connection points to pedestrian lanes - driving_gates (list[XYPosition]): AOI boundary positions for driving connections - walking_gates (list[XYPosition]): AOI boundary positions for walking connections - urban_land_use (Optional[str]): Urban land use classification (GB 50137-2011) - poi_ids (list[int]): List of contained POI IDs - shapely_xy (shapely.geometry.Polygon): AOI shape in xy coordinates - shapely_lnglat (shapely.geometry.Polygon): AOI shape in lat/lng coordinates """ # Get all POIs (Points of Interest) all_pois = self.environment.map.get_all_pois() """ POI collection contains the following attributes: - id (int): POI ID - name (string): POI name - category (string): POI category code - position (XYPosition): POI position - aoi_id (int): AOI ID to which the POI belongs """ # Get specific AOI information aoi_info = self.environment.map.get_aoi(aoi_id=1) ``` -------------------------------- ### Start Experiment Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/01-get-started/04-webui.md Initiates an experiment by selecting pre-configured LLM, map, agent, and workflow settings. The experiment runs as a separate process on the machine hosting the web UI. ```N/A 完成所有四个配置项的选择后,点击`开始实验`按钮来启动实验。 ``` -------------------------------- ### Get Recommended Next Action as JSON Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/skills/agentsociety-research-pipeline/v1.0.0/SKILL.md Retrieves the recommended next action for the research pipeline in JSON format. Use this to guide the next steps in the research process. ```bash $PYTHON_PATH .agentsociety/bin/ags.py research-pipeline next-action --json ``` -------------------------------- ### Benchmark Configuration Example Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety-benchmark/README.md Define LLM and environment settings for your benchmark using this YAML configuration. Replace placeholders like YOUR-API-KEY with actual values. ```yaml llm: - api_key: YOUR-API-KEY model: gpt-4 provider: openai semaphore: 200 env: db: enabled: true home_dir: .agentsociety-benchmark/agentsociety_data ``` -------------------------------- ### Get Dataset Info with Version Comparison Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/skills/agentsociety-use-dataset/v1.0.0/references/listing-guide.md This command retrieves detailed information about a specific dataset, identified by its ID. By default, it shows remote metadata. If the dataset is installed locally and is outdated, it will also display a warning and suggest the update command. ```bash $PYTHON_PATH .agentsociety/bin/ags.py use-dataset info ``` -------------------------------- ### Verify AgentSociety 2 Installation Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/installation.md Run this Python code to verify that AgentSociety 2 has been installed correctly. It prints the installed version number. ```python import agentsociety2 print(agentsociety2.__version__) ``` -------------------------------- ### Verify AgentSociety Installation Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/01-get-started/02-installation.md Run the 'agentsociety' command in the terminal to verify that the installation was successful. A successful installation will display the command's usage information. ```bash Usage: agentsociety [OPTIONS] COMMAND [ARGS]... AgentSociety CLI tool Options: --version Show the version and exit. -h, --help Show this message and exit. Commands: check Pre-check the config run Run the simulation ui Launch AgentSociety GUI ``` -------------------------------- ### Install NumPy Dependency Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety-benchmark/agentsociety_benchmark/benchmarks/HurricaneMobility/README.md Ensure you have NumPy version 1.26.4 or higher installed for the benchmark. ```python numpy >= 1.26.4 ``` -------------------------------- ### Skill Example with Input and Output Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/skill_guide.md Illustrates how to provide a concrete input and its corresponding expected output for a skill, aiding the LLM in understanding the desired behavior. ```markdown ## Example **Input**: ``` state/observation.txt: "You see a café across the street." ``` **Output** (intention.json): ```json { "intention": "Visit the café for lunch", "priority": 2, "reasoning": "I'm feeling hungry and there's a café nearby." } ``` ``` -------------------------------- ### Install and Sync Project Dependencies with uv Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/CONTRIBUTING.md Installs the uv package manager and synchronizes project dependencies. Ensure Python 3.11+ is installed. The UV_INDEX_URL environment variable can be set for a preferred PyPI mirror. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh # Workspace root (optional: set UV_INDEX_URL to your preferred PyPI mirror) uv sync cd packages/agentsociety2 uv sync --extra dev ``` -------------------------------- ### Prepare Experiment Configuration Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/skills/agentsociety-experiment-config/v1.0.0/SKILL.md Creates the init/ directory and template files for the experiment. Requires hypothesis and experiment IDs. ```bash $PYTHON_PATH .agentsociety/bin/ags.py experiment-config prepare --hypothesis-id ID --experiment-id ID ``` -------------------------------- ### AgentConfig Initialization Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/skills/agentsociety-create-agent/v1.0.0/references/agent-base-interface.md Demonstrates creating an AgentConfig instance with default settings or from environment variables. ```python from agentsociety2.agent.config import AgentConfig # Create with defaults config = AgentConfig() # From environment variables config = AgentConfig.from_env() ``` -------------------------------- ### Create First Agent with AgentSociety 2 Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/README.md Demonstrates creating a PersonAgent, setting up a SimpleSocialSpace environment, and initializing an AgentSociety. Requires LLM API keys to be configured. ```python import asyncio from datetime import datetime from agentsociety2 import PersonAgent from agentsociety2.env import CodeGenRouter from agentsociety2.contrib.env import SimpleSocialSpace from agentsociety2.society import AgentSociety async def main(): # Create an agent with a profile agent = PersonAgent( id=1, profile={ "name": "Alice", "age": 28, "personality": "friendly and curious", "bio": "A software engineer who loves hiking and reading." } ) # Create environment module with agent info social_env = SimpleSocialSpace( agent_id_name_pairs=[(agent.id, agent.name)] ) # Create environment router env_router = CodeGenRouter(env_modules=[social_env]) # Create the society society = AgentSociety( agents=[agent], env_router=env_router, start_t=datetime.now(), ) # Initialize (sets up agents with environment) await society.init() # Query (read-only) response = await society.ask("What's your favorite activity?") print(f"Agent: {response}") # Close the society await society.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install Frontend Dependencies Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/CLAUDE.md Installs dependencies for the React frontend application using npm ci, which pins versions based on the lockfile. ```bash cd frontend npm ci ``` -------------------------------- ### Initialize Research Pipeline Workspace Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/skills/agentsociety-research-pipeline/v1.0.0/SKILL.md Bootstrap a new research workspace by initializing git, creating the progress tracking file, and making the initial commit. ```bash # 1. Init the workspace directory if not already a git repo git init # 2. Create progress tracking $PYTHON_PATH .agentsociety/bin/ags.py research-pipeline init --topic "TOPIC" # 3. Initial commit git add -A && git commit -m "init: bootstrap research pipeline" ``` -------------------------------- ### Install Dev Dependencies for agentsociety2 Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/CLAUDE.md Installs dependencies including development tools for the agentsociety2 package. Navigate to the package directory first. ```bash cd packages/agentsociety2 && uv sync --extra dev ``` -------------------------------- ### Create Your First Agent Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/quickstart.md Instantiate a PersonAgent, set up a SimpleSocialSpace environment, and interact with the agent using AgentSociety. Ensure LLM environment variables are configured. ```python import asyncio from datetime import datetime from agentsociety2 import PersonAgent from agentsociety2.env import CodeGenRouter from agentsociety2.contrib.env import SimpleSocialSpace from agentsociety2.society import AgentSociety async def main(): # Create agent with profile agent = PersonAgent( id=1, profile={ "name": "Alice", "age": 28, "personality": "friendly and curious", "bio": "A software engineer who loves hiking." } ) # Create environment module with agent info social_env = SimpleSocialSpace( agent_id_name_pairs=[(agent.id, agent.name)] ) # Create environment router env_router = CodeGenRouter(env_modules=[social_env]) # Create society society = AgentSociety( agents=[agent], env_router=env_router, start_t=datetime.now(), ) # Initialize (set up environment for agents) await society.init() # Query (read-only) response = await society.ask("What's your favorite activity?") print(f"Agent: {response}") # Close society await society.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Start AgentSociety Web UI Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/01-get-started/04-webui.md Launches the AgentSociety web UI using a specified configuration file. Access the UI via a web browser at the configured address. ```bash agentsociety ui -c ./ui.yaml ``` -------------------------------- ### Start FastAPI Backend Service Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/CLAUDE.md Starts the FastAPI backend service from the packages/agentsociety2 directory. The API documentation is accessible at http://localhost:8001/docs. ```bash cd packages/agentsociety2 python -m agentsociety2.backend.run ``` -------------------------------- ### AgentConfig Initialization and Access Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/agentsociety2/agent/README.md Demonstrates how to initialize AgentConfig and access its various configuration parameters for model, loop, and persistence settings. ```python from agentsociety2.agent import AgentConfig config = AgentConfig() config.model.context_window # 200000 config.loop.max_rounds # 24 config.persistence.checkpoint_interval # 10 ``` -------------------------------- ### Install AgentSociety 2 with Development Dependencies Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/installation.md Install AgentSociety 2 along with development dependencies using pip. This is useful for contributing to the project. ```bash pip install "agentsociety2[dev]" ``` -------------------------------- ### Run Hurricane Mobility Benchmark Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety-benchmark/agentsociety_benchmark/benchmarks/HurricaneMobility/README.md Execute the benchmark in inference mode using the 'asbench run' command. Specify your configuration and agent files. The output will be a result file for scoring. ```shell asbench run --config .yml --agent .py --mode inference HurricaneMobility ``` -------------------------------- ### List All Datasets (Local and Remote) Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/skills/agentsociety-use-dataset/v1.0.0/references/listing-guide.md Use this command to see all available datasets, including those installed locally and those available remotely. The output displays the ID, Name, Category, Version, and Status of each dataset. ```bash $PYTHON_PATH .agentsociety/bin/ags.py use-dataset list --all ``` -------------------------------- ### Configure Multi-Column Layouts Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/skills/docx/SKILL.md Demonstrates setting up both equal-width and custom-width columns for document content. ```javascript // Equal-width columns sections: [{ properties: { column: { count: 2, space: 720, equalWidth: true, separate: true, }, }, children: [/* content flows naturally across columns */] }] // Custom-width columns (equalWidth must be false) sections: [{ properties: { column: { equalWidth: false, children: [ new Column({ width: 5400, space: 720 }), new Column({ width: 3240 }), ], }, }, children: [/* content */] }] ``` -------------------------------- ### Install AgentSociety 1.x Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/README.md Install the legacy AgentSociety 1.x package using pip. This version is a city simulation framework with gRPC-based environment integration. ```bash pip install agentsociety ``` -------------------------------- ### SKILL.md Frontmatter Example Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/agent_skills.md Demonstrates the YAML frontmatter structure for a SKILL.md file, including name, description, and optional script declaration. ```markdown --- name: cognition description: Update emotions and form intentions from current context --- # Cognition Skill You should analyze the current context and update your emotional state... ``` -------------------------------- ### Response Structure - Observation Example Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/skills/agentsociety-create-agent/v1.0.0/references/environment-interaction.md Example of a typical observation response structure from `ask_env`. The format of the response string depends on the specific environment module. ```python # Observation response updated_ctx, observation_text = await self.ask_env( {"id": self.id}, "Please describe what is observable to me right now.", readonly=True, ) ``` -------------------------------- ### Build Frontend for Production Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/CLAUDE.md Creates a production-ready build of the React frontend application. ```bash cd frontend npm run build ``` -------------------------------- ### agentsociety.environment.utils.map_utils.point_on_line_given_distance Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/apidocs/agentsociety/agentsociety.environment.utils.map_utils.md Determines a point on a line segment defined by a start and end node, at a specified distance from the start node. This is useful for path planning and interpolation. ```APIDOC ## agentsociety.environment.utils.map_utils.point_on_line_given_distance(start_node, end_node, distance) ### Description Calculates a point on a line segment at a given distance from the start node. ### Parameters - **start_node** (dict[str, float]) - The starting node of the line segment. - **end_node** (dict[str, float]) - The ending node of the line segment. - **distance** (float) - The distance from the start node along the line. ``` -------------------------------- ### Configure Document Headers and Footers Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/skills/docx/SKILL.md Demonstrates setting up default headers and footers, including page numbers. ```javascript sections: [{ properties: { page: { margin: { top: 1440, right: 1440, bottom: 1440, left: 1440 } } }, headers: { default: new Header({ children: [new Paragraph({ children: [new TextRun("Header")] })] }) }, footers: { default: new Footer({ children: [new Paragraph({ children: [new TextRun("Page "), new TextRun({ children: [PageNumber.CURRENT] })] })] }) }, children: [/* content */] }] ``` -------------------------------- ### Interactive Mode Selection Prompt Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/plugins/easypaper/skills/easypaper-interactive-metadata-build/SKILL.md Presents the user with options for building metadata: 'cold' (manual, transparent), 'warm-start' (SDK pre-generation followed by refinement), or 'refine' (editing existing metadata). This is the first interaction in the skill's workflow. ```text Choose how you want to build the metadata: [1] cold — Claude walks the folder alone, no Python SDK call. Best for small folders or when full transparency is required. [2] warm-start — (recommended) Run ep.generate_metadata_from_folder() once to get a draft, then refine each field with Claude. Best signal-to-effort ratio. [3] refine — Load an existing metadata JSON and walk through fixing validation failures and warnings. Reply with 1 / 2 / 3, or the mode name. ``` -------------------------------- ### Install AgentSociety 2 Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/README.md Install the recommended AgentSociety 2 package using pip. This version is designed for LLM-native agent simulations and social science research. ```bash pip install agentsociety2 ``` -------------------------------- ### List Available Benchmark Tasks Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety-benchmark/README.md Use the command-line interface to view all benchmark tasks supported by the toolkit. This helps in identifying which benchmarks can be run or managed. ```bash asbench list-tasks ``` -------------------------------- ### Memory Entry Format Example Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/agentsociety2/agent/skills/memory/SKILL.md An example of a JSON object representing a memory entry. This format includes tick, time, type, summary, tags, and importance. ```json {"tick":42,"time":"2024-01-15T10:30:00","type":"event","summary":"Met Alice at the park; she mentioned a library job.","tags":["social","alice","job"],"importance":"medium"} ``` -------------------------------- ### Programmatic Benchmark Execution with Convenience Functions Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety-benchmark/README.md Utilize convenience functions like `run_benchmark` and `evaluate_results` for simpler programmatic access to benchmark functionalities. This example also shows how to list available tasks. ```python import asyncio from agentsociety_benchmark import run_benchmark, evaluate_results, list_available_tasks async def simple_benchmark(): # List available tasks tasks = list_available_tasks() print(f"Available tasks: {tasks}") # Run benchmark using convenience function result = await run_benchmark( task_name="BehaviorModeling", benchmark_config="config.yaml", agent_config="agent_config.yaml", mode="inference" # Run without evaluation ) # Evaluate results separately if needed if result['results']: evaluation = await evaluate_results( task_name="BehaviorModeling", results_file="results.pkl", benchmark_config="config.yaml" ) print(f"Evaluation result: {evaluation['evaluation_result']}") asyncio.run(simple_benchmark()) ``` -------------------------------- ### Run pre-promotion review Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/skills/agentsociety-analysis/v1.0.0/references/experience-memory.md Execute a pre-promotion review of a reflection. This command requires the workspace and hypothesis ID. ```bash $PYTHON_PATH .agentsociety/bin/ags.py analysis review-reflection \ --workspace . \ --hypothesis-id 1 ``` -------------------------------- ### Custom Dispatcher Prompt Example Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/02-development-guide/04-agent.md An example of a custom dispatcher prompt that includes agent mood, activity, task priority, and available time for more context-aware task selection. ```python CUSTOM_DISPATCHER_PROMPT = """ Based on the current situation and agent state, select the most appropriate block to handle the task. Current situation: - Agent mood: ${context.current_mood} - Current activity: ${context.current_activity} - Task priority: ${context.task_priority} - Available time: ${context.available_time} Task information: ${context.current_intention} Select the block that best matches the current situation and task requirements. """ ``` -------------------------------- ### Simple Recommendation Scenario (No Incremental Updates) Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/agentsociety2/contrib/env/social_media/recommendation/README.md Demonstrates the basic usage of the recommendation system for generating recommendations without real-time data updates. Requires creating an algorithm, a service, preparing data, training the model, and then requesting recommendations. ```python from agentsociety2.contrib.env.social_media.recommendation import ( MFRecommender, MFConfig, RecommendationService, RatingMatrix, Rating, ) # 1. 创建算法 config = MFConfig(n_latent_factors=50, n_iterations=100) algorithm = MFRecommender(config) # 2. 创建服务 service = RecommendationService(algorithm) # 3. 准备数据并训练 ratings = [ Rating(user_id=1, item_id=1, rating=5.0), Rating(user_id=1, item_id=2, rating=4.0), # ... ] data = RatingMatrix.from_ratings(ratings) await service.fit(data) # 4. 生成推荐 recommendations = await service.recommend(user_id=1, n=10) # 返回: [(item_id, score), ...] ``` -------------------------------- ### Start Experiment Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/skills/agentsociety-run-experiment/v1.0.0/references/programmatic-api.md Starts a new experiment. This function is asynchronous and requires a workspace path, hypothesis ID, and experiment ID. An optional run ID can also be provided. ```APIDOC ## start_experiment ### Description Starts a new experiment with the specified parameters. ### Method async function call ### Parameters #### Path Parameters - **workspace_path** (string) - Required - The path to the workspace directory. - **hypothesis_id** (integer) - Required - The ID of the hypothesis. - **experiment_id** (integer) - Required - The ID of the experiment. - **run_id** (string) - Optional - The ID for the run, defaults to "run". ### Request Example ```python await start_experiment( workspace_path="/path/to/workspace", hypothesis_id=1, experiment_id=1, run_id="run" ) ``` ``` -------------------------------- ### EconomyClient Initialization Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety2/docs/apidocs/agentsociety/agentsociety.environment.economy.econ_client.md Initializes the EconomyClient with the server address for the economy simulation. ```APIDOC ## EconomyClient(server_address: str) ### Description Initializes the EconomyClient with the server address for the economy simulation. ### Parameters #### Path Parameters - **server_address** (str) - Required - The network address of the economy server. ``` -------------------------------- ### Download Datasets for Benchmarks Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/packages/agentsociety-benchmark/README.md Download datasets for specific benchmarks using the CLI. Ensure git lfs is installed first. Options include forcing a re-download or only installing dependencies. ```bash asbench clone BehaviorModeling asbench clone DailyMobility asbench clone HarricaneMobility asbench list-installed asbench clone BehaviorModeling --force asbench clone BehaviorModeling --only-install-deps ``` -------------------------------- ### Resolve Runtime Module Paths Source: https://github.com/tsinghua-fib-lab/agentsociety/blob/main/extension/skills/agentsociety-create-env-module/v1.0.0/references/runtime-sources.md Use this command to resolve installed file locations for skill dependencies without importing them. This is crucial before reading reference code in installed environments. ```bash $PYTHON_PATH .agentsociety/bin/ags.py create-env-module-resolve-sources ``` ```bash $PYTHON_PATH .agentsociety/bin/ags.py create-env-module-resolve-sources --json ``` ```bash $PYTHON_PATH .agentsociety/bin/ags.py create-env-module-resolve-sources --module agentsociety2.env.base ```