A modern, LLM-native agent simulation platform for social science research
Project description
AgentSociety 2
AgentSociety 2 is a modern, LLM-native agent simulation platform designed for social science research and experimentation.
Features
- LLM-Native Design: Built from the ground up for LLM-driven agents
- Flexible Environment System: Modular environment components with hot-pluggable tools
- Multiple Reasoning Patterns: CodeGen (default), ReAct, Plan-Execute, Two-Tier, and Search routers
- Scalable Execution: Agents are workspace-bound stateless records driven by Ray Tasks;
env / LLM clients / trace / replay handles are passed behind a single
ServiceProxy - Developer-Friendly: Pythonic API with type hints and comprehensive documentation
- Experiment Replay: Catalog-driven JSONL replay with DuckDB-powered reads and distributed tracing
- MCP Support: Model Context Protocol integration for tool extensibility
Installation
pip install agentsociety2
Requirements
- Python >= 3.11
- An LLM API key (OpenAI, Anthropic, or any provider supported by LiteLLM)
Quick Start
Before running the examples, set the LLM environment variables described in
Configuration. The package validates them when agentsociety2
is imported.
Create Your First Agent
import asyncio
from datetime import datetime
from pathlib import Path
from agentsociety2.env import CodeGenRouter
from agentsociety2.contrib.env import SimpleSocialSpace
from agentsociety2.society import AgentSociety
async def main():
# Declare agent metadata (id / profile / config); agents are NOT instantiated here.
# AgentSociety batch-creates their workspaces during init().
agent_specs = [
{
"id": 1,
"profile": {
"name": "Alice",
"age": 28,
"personality": "friendly and curious",
"bio": "A software engineer who loves hiking and reading.",
},
"config": {},
}
]
names = [(s["id"], s["profile"]["name"]) for s in agent_specs]
# Create environment module with agent info
social_env = SimpleSocialSpace(agent_id_name_pairs=names)
# Create environment router (in-process CodeGenRouter; production uses an EnvRouterProxy Ray actor)
env_router = CodeGenRouter(env_modules=[social_env])
# Create the society
society = AgentSociety(
agent_specs=agent_specs,
agent_class_name="PersonAgent",
env_router=env_router,
start_t=datetime.now(),
run_dir=Path("run"),
)
# Initialize (batch-creates agent workspaces, binds the 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())
Create a Custom Environment Module
from agentsociety2.env import EnvBase, tool
class MyCustomEnvironment(EnvBase):
"""A custom environment module."""
@tool(readonly=True, kind="observe")
def get_weather(self, agent_id: int) -> str:
"""Get the current weather for an agent."""
return "The weather is sunny and 25°C."
@tool(readonly=False)
def set_mood(self, agent_id: int, mood: str) -> str:
"""Change the mood of an agent."""
return f"Agent {agent_id}'s mood is now {mood}."
# Use the custom module
from agentsociety2.env import CodeGenRouter
env_router = CodeGenRouter(env_modules=[MyCustomEnvironment()])
Run a Complete Experiment
import asyncio
from datetime import datetime
from pathlib import Path
from agentsociety2.env import CodeGenRouter
from agentsociety2.contrib.env import SimpleSocialSpace
from agentsociety2.society import AgentSociety
async def main():
# Declare agent metadata
agent_specs = [
{"id": i, "profile": {"name": f"Player{i}", "personality": "friendly"}, "config": {}}
for i in range(1, 4)
]
names = [(s["id"], s["profile"]["name"]) for s in agent_specs]
# Create environment router (replay is enabled by default -> run/replay/)
env_router = CodeGenRouter(env_modules=[SimpleSocialSpace(agent_id_name_pairs=names)])
# Create the society
society = AgentSociety(
agent_specs=agent_specs,
agent_class_name="PersonAgent",
env_router=env_router,
start_t=datetime.now(),
run_dir=Path("run"),
)
await society.init()
# Query (read-only)
answer = await society.ask("What are the names of all agents?")
print(f"Answer: {answer}")
# Intervene (read-write)
result = await society.intervene("Set all agents' happiness to 0.8")
print(f"Result: {result}")
await society.close()
if __name__ == "__main__":
asyncio.run(main())
Core Concepts
Agents
Agents are autonomous entities that interact with environments through LLM-powered reasoning:
- AgentBase: Abstract base class for all agents
- PersonAgent: Skills-based agent — a lightweight orchestrator whose capabilities are provided by a pluggable skill pipeline
- Agents support two interaction modes:
ask(question, readonly=True): Query without side effectsintervene(instruction): Make changes to the environment
Agent Skills
PersonAgent follows a metadata-first, selected-only model. Skills are self-contained
directories; the only built-in skill is daily-guidance (daily behavior / needs-decay
guidance). The old observation / cognition / plan / memory skills have been removed —
those capabilities are now expressed via custom skills + workspace state files + ask_env.
agent/skills/
└── daily-guidance/ # SKILL.md + scripts/daily_guidance.py (pre_step hook)
Each skill has:
SKILL.md— YAML frontmatter (name,description, optionalscript/hooks) + behavior docsscripts/*.py— optional scripts. By default these run in-process via anentrypoint(argv, ctx)contract (millisecond, concurrency-safe), with dynamic-wrapper and subprocess fallbacks.
Skills follow metadata-first selection:
- the catalog exposes only name/description until activation
- execution is tool-loop driven (
activate_skill/read_skill_file/execute_skill_script) pre_step/post_steplifecycle hooks are rendered into a dedicated<skill_hooks>block
Custom skills can be placed in <workspace>/custom/skills/ and hot-loaded at runtime.
Environment Modules
Environment modules encapsulate specific functionality through tools:
- EnvBase: Base class for creating custom modules
- @tool decorator: Register methods as discoverable tools
- Tool kinds:
observe: Single-parameter observation functionsstatistics: No-parameter aggregation functions- Regular tools: Full read/write operations
Routers
Routers mediate agent-environment interactions using different reasoning patterns:
- ReActRouter: Reasoning + Acting loop
- PlanExecuteRouter: Plan-first, then execute
- CodeGenRouter: Code generation based tool use
- TwoTierReActRouter: Two-level reasoning hierarchy
- TwoTierPlanExecuteRouter: Two-level planning hierarchy
Storage
AgentSociety 2 currently has two persistence paths:
from agentsociety2.storage import ReplayReader, ReplayWriter
from pathlib import Path
writer = ReplayWriter(Path("run/replay"))
await writer.init()
# Replay schema sidecar: run/replay/_schema.json
# Environment modules can register and write their own replay tables.
from agentsociety2.storage import ColumnDef, TableSchema
schema = TableSchema(
name="custom_metrics",
columns=[
ColumnDef("metric_id", "INTEGER", nullable=False),
ColumnDef("value", "REAL"),
],
primary_key=["metric_id"],
)
await writer.register_table(schema)
reader = ReplayReader(Path("run/replay"))
print(reader.load_dataset_catalog())
reader.close()
- ReplayWriter / ReplayReader: write sharded JSONL replay datasets plus
_schema.jsonmetadata, then read them through DuckDB-backed views. - PersonAgent workspace: stores per-agent local files under
run/agents/agent_xxxx/, such asconfig.json,AGENT.json,AGENT_MEMORY.md,state/*.json, and.runtime/logs/*.jsonl. - Trace: the
agentsociety2.tracemodule writes distributed tracing spans (sharded writer + background-thread actor) for profiling steps and LLM calls.
Legacy SQLite tables like agent_profile, agent_status, and agent_dialog are kept only for compatibility when reading old experiment databases; new runs write run/replay/ instead.
Configuration
Set your LLM API credentials via environment variables. The examples below use the OpenAI API endpoint and gpt-5.5; other LiteLLM-supported providers can be used by changing the base URL and model id.
Required Configuration
# Default LLM (required - used for most operations)
export AGENTSOCIETY_LLM_API_KEY="your-api-key"
export AGENTSOCIETY_LLM_API_BASE="https://api.openai.com/v1"
export AGENTSOCIETY_LLM_MODEL="gpt-5.5"
Optional Configuration
For specialized tasks, you can configure separate LLM instances:
# Code Generation LLM (for code-related tasks)
# Falls back to default LLM if not set
export AGENTSOCIETY_CODER_LLM_API_KEY="your-coder-api-key"
export AGENTSOCIETY_CODER_LLM_API_BASE="https://api.openai.com/v1"
export AGENTSOCIETY_CODER_LLM_MODEL="gpt-5.5"
# Nano LLM (for high-frequency, low-latency operations)
# Falls back to default LLM if not set
export AGENTSOCIETY_NANO_LLM_API_KEY="your-nano-api-key"
export AGENTSOCIETY_NANO_LLM_API_BASE="https://api.openai.com/v1"
export AGENTSOCIETY_NANO_LLM_MODEL="gpt-5.5"
# Embedding Model (for text embeddings and semantic search)
# Falls back to default LLM if not set
export AGENTSOCIETY_EMBEDDING_API_KEY="your-embedding-api-key"
export AGENTSOCIETY_EMBEDDING_API_BASE="https://api.openai.com/v1"
export AGENTSOCIETY_EMBEDDING_MODEL="text-embedding-3-large"
export AGENTSOCIETY_EMBEDDING_DIMS="1024"
# Data directory (optional, default: ./agentsociety_data)
export AGENTSOCIETY_HOME_DIR="/path/to/your/data"
Or use a .env file:
# From the repository root:
cp .env.example .env
# Edit .env with your credentials before importing agentsociety2
Note AgentSociety 2 validates
AGENTSOCIETY_LLM_API_KEYat import time. Make sure it is set before importingagentsociety2, or load.envearly in your entrypoint.
Examples
The examples/ directory contains ready-to-run examples:
basics/: Basic agent and environment usagegames/: Classic game theory simulations- Prisoner's Dilemma
- Public Goods Game
- Trust Game
- Volunteer's Dilemma
- Commons Tragedy
advanced/: Advanced usage patterns- Custom environment modules
- Multi-router setups
- Experiment replay and analysis
Documentation
Development
For development guidelines, see docs/development.rst.
Contributing
We welcome contributions! Please see CONTRIBUTING.md for details.
Citation
If you use AgentSociety 2 in your research, please cite:
@software{agentsociety2,
title = {AgentSociety 2: A Modern LLM-Native Agent Simulation Platform},
author = {Zhang, Jun and others},
year = {2025},
url = {https://github.com/tsinghua-fib-lab/agentsociety}
}
License
Apache License 2.0 - see LICENSE for details.
Acknowledgments
AgentSociety 2 builds upon excellent open-source projects:
Contact
- Issues: GitHub Issues
- Discussions: GitHub Discussions
For the original AgentSociety (v1.x) focused on city simulation, see the agentsociety package.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file agentsociety2-2.7.0.tar.gz.
File metadata
- Download URL: agentsociety2-2.7.0.tar.gz
- Upload date:
- Size: 557.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8b43e6c852d590222927219002aa8d4c3b136dee7d0894d5e0a92b78eacc08ee
|
|
| MD5 |
8fa1c7d528f9d6819b7256425ab8b2cd
|
|
| BLAKE2b-256 |
6e1b8294c52b44bc4dd0bbd5b5ab5dec4f3cbd10c47f48ed2ff30244e8b794d8
|
Provenance
The following attestation bundles were made for agentsociety2-2.7.0.tar.gz:
Publisher:
agentsociety2-publish.yml on tsinghua-fib-lab/AgentSociety
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
agentsociety2-2.7.0.tar.gz -
Subject digest:
8b43e6c852d590222927219002aa8d4c3b136dee7d0894d5e0a92b78eacc08ee - Sigstore transparency entry: 1922257081
- Sigstore integration time:
-
Permalink:
tsinghua-fib-lab/AgentSociety@5dfdec4cde5bd5f1faa23df33bbfc66f6028c621 -
Branch / Tag:
refs/tags/agentsociety2-v2.7.0 - Owner: https://github.com/tsinghua-fib-lab
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
agentsociety2-publish.yml@5dfdec4cde5bd5f1faa23df33bbfc66f6028c621 -
Trigger Event:
push
-
Statement type:
File details
Details for the file agentsociety2-2.7.0-py3-none-any.whl.
File metadata
- Download URL: agentsociety2-2.7.0-py3-none-any.whl
- Upload date:
- Size: 713.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3703cbfd54eff27273034c09e12b3d05744640b82295423ff4c44be57c64aa81
|
|
| MD5 |
a09018959fed7f52f3cd214c4d0917bb
|
|
| BLAKE2b-256 |
e314872f4086ec4438e28ccf7302c5009dc87feb9fc178273517610fbd6077c2
|
Provenance
The following attestation bundles were made for agentsociety2-2.7.0-py3-none-any.whl:
Publisher:
agentsociety2-publish.yml on tsinghua-fib-lab/AgentSociety
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
agentsociety2-2.7.0-py3-none-any.whl -
Subject digest:
3703cbfd54eff27273034c09e12b3d05744640b82295423ff4c44be57c64aa81 - Sigstore transparency entry: 1922257234
- Sigstore integration time:
-
Permalink:
tsinghua-fib-lab/AgentSociety@5dfdec4cde5bd5f1faa23df33bbfc66f6028c621 -
Branch / Tag:
refs/tags/agentsociety2-v2.7.0 - Owner: https://github.com/tsinghua-fib-lab
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
agentsociety2-publish.yml@5dfdec4cde5bd5f1faa23df33bbfc66f6028c621 -
Trigger Event:
push
-
Statement type: