Code Usage

This document mainly introduces how to run AgentSociety using command line or code.


This assumes that installation has been completed and the map file is ready. The storage path for the map file is ./agentsociety_data/beijing.pb.

Command Line Execution

A simple configuration file is as follows, which includes LLM settings, database configuration, map file, agent parameters, and experiment configuration:

llm:
  - model: qwen2.5-14b-instruct
    api_key: sk-123456
    base_url: https://cloud.infini-ai.com/maas/v1
    provider: vllm
env:
  db:
    enabled: true
    db_type: sqlite
  home_dir: ./agentsociety_data
map:
  file_path: ./agentsociety_data/beijing.pb
agents:
  citizens:
    - agent_class: SocietyAgent
      number: 10
exp:
  name: simplest_exp
  workflow:
    - type: run
      days: 1
      ticks_per_step: 300
  environment:
    start_tick: 28800

LLM Configuration Section: Set large language model related parameters, supporting configuration of multiple LLM instances

  • model: The model name to be used, needs to be set according to the model provider’s instructions

  • api_key: API key of the model provider

  • base_url: API address of the model provider (here it is Qwen)

  • provider: Model provider type, here vllm is used to access OpenAI API compatible large models

Environment Configuration Section: Set data storage and database related configuration

  • db.enabled: Whether to enable database storage of experiment results

  • db.db_type: Database type, here SQLite is used

  • home_dir: AgentSociety data storage path, including sqlite database files, HuggingFace model files, various data managed through the visual interface, etc., stored by default in the agentsociety_data folder under the current directory

Map Configuration Section: Specify the map file used by the simulation environment

  • file_path: Storage path of the map file

Agent Configuration Section: Define the agent types and quantities in the simulation

  • citizens: List of citizen agent configurations

  • agent_class: Agent class name, here using the built-in SocietyAgent class of AgentSociety

  • number: Number of agent instances

Experiment Configuration Section: Define the execution process and environment parameters of the experiment

  • name: Experiment name identifier

  • workflow: Experiment process configuration list, AgentSociety will execute each step in the list in order

  • type: Experiment step type, here using run type to execute simulation

  • days: Simulation duration (unit: days)

  • ticks_per_step: Time interval between two steps in simulation (unit: seconds), here 300 seconds i.e. 5 minutes, indicating that agents perform actions every 5 minutes

  • environment.start_tick: Simulation start time (unit: seconds), here 28800 seconds i.e. 8:00 AM

Tip

The configuration data format uses pydantic for parsing and validation. For detailed explanations of all fields, please refer to Configuration.

Assuming the configuration file is stored as ./config.yaml, the configuration pre-check provided by the AgentSociety command line tool can be run with the following command (pre-check is an optional step):

agentsociety check -c ./config.yaml

If the configuration file is correct, the output content will be as follows:

Config format check. Passed.
Database connection check. Passed.
Map file. Passed.

Otherwise, error messages will be output, and the configuration file can be modified according to the prompt instructions.

After the configuration pre-check passes, AgentSociety can be run with the following command:

agentsociety run -c ./config.yaml

Afterwards, AgentSociety starts simulation and continuously outputs logs during the simulation process. The simulation process starts from the start_tick time of the virtual world and ends at 24:00 of the same day. During the simulation, data such as agent positions, states, and dialogues will be stored in the database, which can be viewed through the visual interface or further processed by writing code to access the database.

Code Execution

Besides running AgentSociety using the command line, it can also be used directly in Python code. Below is a minimal code example:

import asyncio
from agentsociety.cityagent import default
from agentsociety.configs import (
    AgentsConfig,
    Config,
    EnvConfig,
    ExpConfig,
    LLMConfig,
    MapConfig,
)
from agentsociety.configs.agent import AgentConfig
from agentsociety.configs.exp import WorkflowStepConfig, WorkflowType
from agentsociety.environment import EnvironmentConfig
from agentsociety.llm import LLMProviderType
from agentsociety.simulation import AgentSociety
from agentsociety.storage import DatabaseConfig

llm_config = LLMConfig(
    provider=LLMProviderType.VLLM,
    base_url="https://cloud.infini-ai.com/maas/v1",
    api_key="sk-123456",
    model="qwen2.5-14b-instruct",
    concurrency=200,
    timeout=60,
)

env_config = EnvConfig(
    db=DatabaseConfig(
        enabled=True,
        db_type="sqlite",
    ),
    home_dir="./agentsociety_data",
)

map_config = MapConfig(
    file_path="./agentsociety_data/beijing.pb",
)

agents_config = AgentsConfig(
    citizens=[
        AgentConfig(
            agent_class="citizen",
            number=10,
        )
    ],
)

exp_config = ExpConfig(
    name="simplest_code_exp",
    workflow=[
        WorkflowStepConfig(
            type=WorkflowType.RUN,
            days=1,
            ticks_per_step=300,
        ),
    ],
    environment=EnvironmentConfig(
        start_tick=8 * 60 * 60,
    ),
)

config = Config(
    llm=[llm_config],
    env=env_config,
    map=map_config,
    agents=agents_config,
    exp=exp_config,
)

config = default(config)

async def main():
    society = AgentSociety.create(config)

    try:
        await society.init()
        await society.run()
    finally:
        await society.close()


if __name__ == "__main__":
    asyncio.run(main())

This example has the same effect as command line execution, mainly including the following steps:

  1. Import necessary modules: Import configuration classes, agent classes, and simulation classes from the agentsociety package

  2. Create configuration object: Set LLM, database, map, agent, and experiment configuration

  3. Apply default configuration: Use the default() function to apply AgentSociety.cityagent default settings, which will decorate the agent configuration to add default values and the default agent_class string to type mapping to make the configuration meet initialization requirements

  4. Create and run simulation:

    • Use AgentSociety.create() to create a simulation instance

    • Call init() to initialize the environment

    • Call run() to start the simulation

    • Call close() in the finally block to clean up resources

Tip

  • Ensure that AgentSociety installation and map file preparation are completed before running the code

  • Remember to replace API keys, model names, and other parameters in the configuration with actual values

  • Logs will be output to the console during simulation, and data will be saved to the specified database

Advanced Usage

For more complex experimental scenarios, you can refer to the example code in the examples/ directory of the GitHub repository to learn how to configure questionnaire surveys, message interventions, custom agent classes, and other advanced features.