Examples¶
This section contains example code demonstrating AgentSociety 2’s capabilities.
Running Examples¶
All examples are located in the packages/agentsociety2/examples/ directory.
Prerequisites:
Install AgentSociety 2:
pip install agentsociety2Configure LLM API credentials (see Installation)
Navigate to the examples directory
cd packages/agentsociety2/examples
python basics/01_hello_agent.py
Basic Examples¶
These examples demonstrate basic AgentSociety 2 concepts:
Hello Agent (basics/01_hello_agent.py)
A minimal example showing:
Creating a single agent with personality profile
Setting up a SimpleSocialSpace environment
Using AgentSociety to coordinate agent-environment interactions
# Declare agent metadata (agents are created from specs during init)
agent_specs = [
{
"id": 1,
"profile": {
"name": "Alice",
"age": 28,
"personality": "friendly, curious, optimistic",
"bio": "A software engineer who loves hiking and reading.",
},
"config": {},
}
]
# Create environment and 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()
# Interact
response = await society.ask("What's your favorite activity?")
print(f"Agent: {response}")
Custom Environment Module (basics/02_custom_env_module.py)
Demonstrates creating custom environment modules:
Using @tool decorator to define custom environment
Implement step() and tool methods, and provide readonly
kind="observe"tools when neededRegistering module with CodeGenRouter
Replay System (basics/03_replay_system.py)
Shows comprehensive data tracking:
Enabling ReplayWriter for environment modules
Generating replay catalog and environment replay dataset
Inspecting local threads and tool logs alongside agent workspace files
Game Theory Examples¶
Prisoner’s Dilemma (games/01_prisoners_dilemma.py)
A classic game theory scenario:
Two agents with different personalities
Sequential decision-making with payoffs
Reflection on outcomes
Public Goods Game (games/02_public_goods.py)
Multi-round collective action experiment:
Four agents with different personality traits
Multi-round contribution decisions
Group outcome calculation
Advanced Examples¶
Custom Agent (advanced/01_custom_agent.py)
Extend AgentSociety 2 with custom agent types:
Implement required abstract methods (ask, step, dump, load)
Create specialized agents for research needs
Multi-Router Comparison (advanced/02_multi_router.py)
Compare different reasoning strategies:
ReActRouter: Iterative reasoning and action
PlanExecuteRouter: Plan-first execution
CodeGenRouter: Generate code to execute (recommended)