> ## Documentation Index
> Fetch the complete documentation index at: https://salesforce-ai-economist.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# BaseAgent

> Base class for all Foundation agent types

`BaseAgent` is the base class for all agent implementations in Foundation. Agent instances are stateful objects that capture location, inventory, escrow, endogenous variables, and any extra state fields added by components. They also provide a simple API for getting and setting actions across registered action subspaces.

## Constructor

```python theme={null}
BaseAgent(idx=None, multi_action_mode=None)
```

**idx** `int | str` (default: 0)

Index that uniquely identifies this agent within its environment. Integer indices are used for mobile agents; the planner always uses `"p"`.

**multi\_action\_mode** `bool` (default: False)

If `True`, the agent takes one action per registered action subspace each timestep. If `False`, the agent takes a single action from the combined action space each timestep.

## Class attribute

**name** `str` *required*

Unique string identifier for the agent class. Must be set on each concrete subclass and registered in `agent_registry`.

```python theme={null}
name = "BasicMobileAgent"
```

## Properties

### `idx`

```python theme={null}
agent.idx  # int or "p"
```

The unique index for this agent within its environment. Mobile agents use integer indices (`0`, `1`, `2`, ...); the planner uses the string `"p"`.

### `state`

```python theme={null}
agent.state  # dict
```

The agent's full state dictionary. Initialized with the following keys:

**loc** `list[int, int]`

`[row, col]` position in the 2D world grid. Present on `BasicMobileAgent`; removed on `BasicPlanner`.

**inventory** `dict`

Resource quantities held by the agent, keyed by resource name. E.g. `{"Wood": 3, "Stone": 20, "Coin": 1002.83}`.

**escrow** `dict`

Resource quantities reserved for pending obligations, keyed by resource name. Shares the same keys as `inventory`.

**endogenous** `dict`

Internal state quantities (e.g. `{"Labor": 30.25}`). Only observable by the agent itself.

Components extend `agent.state` with additional fields via `BaseComponent.get_additional_state_fields`.

### `loc`

```python theme={null}
agent.loc  # [row, col]
```

Shorthand for `agent.state["loc"]`. The agent's `[row, col]` position in the world.

> [!NOTE]
>
> `BasicPlanner.loc` raises `AttributeError` because planner agents have no physical location.

### `inventory`

```python theme={null}
agent.inventory  # {"Wood": 3, "Stone": 20, "Coin": 1002.83}
```

Shorthand for `agent.state["inventory"]`. A dictionary mapping resource names to quantities.

### `escrow`

```python theme={null}
agent.escrow  # {"Wood": 0, "Stone": 1, "Coin": 3}
```

Shorthand for `agent.state["escrow"]`. Resources placed into escrow are reserved and cannot be used for other purposes until released. Shares keys with `inventory`.

See the `ContinuousDoubleAuction` component for an example of escrow usage: when an agent lists a sell order, the resource moves from `inventory` to `escrow`; on a match it transfers to the buyer.

### `endogenous`

```python theme={null}
agent.endogenous  # {"Labor": 30.25}
```

Shorthand for `agent.state["endogenous"]`. Quantities that represent the agent's internal state, such as accumulated labor effort.

### `action_spaces`

```python theme={null}
agent.action_spaces  # int  (single-action mode)
agent.action_spaces  # np.ndarray[int32]  (multi-action mode)
```

* **Single-action mode** (`multi_action_mode=False`): returns a single integer equal to the total number of available actions (including the universal NO-OP).
* **Multi-action mode** (`multi_action_mode=True`): returns an integer array whose i-th element is the size of the i-th action subspace (each subspace includes its own NO-OP).

```python theme={null}
# multi_action_mode=False
agent.action_spaces   # 6  (1 NO-OP + 1 Build + 4 Gather)
agent._action_names   # ["Build", "Gather"]

# multi_action_mode=True
agent.action_spaces   # array([2, 5])  (Build NO-OP+1, Gather NO-OP+4)
agent._action_names   # ["Build", "Gather"]
```

## Inventory management

Agents track resources across two pools — `inventory` and `escrow` — which share the same set of resource keys.

### `inventory_to_escrow`

```python theme={null}
agent.inventory_to_escrow(resource, amount) -> float
```

Moves up to `amount` of `resource` from inventory into escrow. The transfer is capped at the available inventory quantity.

**resource** `str` *required*

Resource name, e.g. `"Wood"` or `"Coin"`.

**amount** `float` *required*

Amount to move. Must be non-negative.

**transferred** `float`

Actual amount transferred: `min(inventory[resource], amount)`.

### `escrow_to_inventory`

```python theme={null}
agent.escrow_to_inventory(resource, amount) -> float
```

Moves up to `amount` of `resource` from escrow back into inventory. Capped at the available escrow quantity.

**resource** `str` *required*

Resource name.

**amount** `float` *required*

Amount to move. Must be non-negative.

**transferred** `float`

Actual amount transferred: `min(escrow[resource], amount)`.

### `total_endowment`

```python theme={null}
agent.total_endowment(resource) -> float
```

Returns the combined `inventory[resource] + escrow[resource]`.

**resource** `str` *required*

Resource name.

## Action API

### `get_component_action`

```python theme={null}
agent.get_component_action(component_name, sub_action_name=None)
```

Returns the action taken for the named component, or `None` if the agent does not use that component.

**component\_name** `str` *required*

The component name, e.g. `"Build"` or `"ContinuousDoubleAuction"`.

**sub\_action\_name** `str`

For components with multiple action subspaces, the subspace name.

### `set_component_action`

```python theme={null}
agent.set_component_action(component_name, action)
```

Sets the action buffer for `component_name` to `action`.

**component\_name** `str` *required*

Component name. Must be registered as a subaction for this agent.

**action** `int | np.ndarray` *required*

Action index or array of action indices.

### `reset_actions`

```python theme={null}
agent.reset_actions(component=None)
```

Resets all action buffers to NO-OP (index `0`). If `component` is given, resets only that component's action(s).

### `parse_actions`

```python theme={null}
agent.parse_actions(actions)
```

Parses an actions array or dict and fills each component's action buffer. Used by the environment to apply actions each step.

* **Multi-action mode**: `actions` is an array of length `n_unique_actions`.
* **Single-action mode**: `actions` is an integer index into the combined action space, or a `{component_name: action}` dict.

### `has_component`

```python theme={null}
agent.has_component(component_name) -> bool
```

Returns `True` if `component_name` is registered as an action subspace for this agent.

### `flatten_masks`

```python theme={null}
agent.flatten_masks(mask_dict) -> np.ndarray[float32]
```

Converts a `{component_name: mask_array}` dictionary into a single flat mask vector compatible with `action_spaces`.

### `get_random_action`

```python theme={null}
agent.get_random_action() -> dict
```

Selects a random component and returns a random non-NO-OP action for it. Useful for testing.

### `populate_random_actions`

```python theme={null}
agent.populate_random_actions()
```

Fills all action buffers with random values. Useful for testing.

## Registration methods

These methods are called by the environment during construction and should not be called directly.

| Method | Purpose |
| - | - |
| `register_inventory(resources)` | Initializes `inventory` and `escrow` keys for all resource names. |
| `register_endogenous(endogenous)` | Initializes `endogenous` keys for all endogenous entity names. |
| `register_components(components)` | Sets up action subspaces and merges component state fields into `agent.state`. |

## Concrete subclasses

### `BasicMobileAgent`

```python theme={null}
from ai_economist.foundation.agents import agent_registry
MobileAgent = agent_registry.get("BasicMobileAgent")
```

Represents an individual actor in the economic simulation. Mobile agents can move around the 2D world grid. Their `state` includes `loc`, `inventory`, `escrow`, and `endogenous`. Indexed with integers starting at `0`.

```python theme={null}
# BasicMobileAgent state structure
agent.state = {
    "loc": [3, 7],                  # [row, col] in the world
    "inventory": {"Wood": 3, "Coin": 100},
    "escrow": {"Wood": 0, "Coin": 0},
    "endogenous": {"Labor": 12.5},
    # ...plus any fields added by components
}
```

### `BasicPlanner`

```python theme={null}
from ai_economist.foundation.agents import agent_registry
Planner = agent_registry.get("BasicPlanner")
```

Represents a social planner that sets macroeconomic policy. Differs from `BasicMobileAgent` in two ways:

1. **No location**: `state["loc"]` is deleted on construction. Accessing `planner.loc` raises `AttributeError`.
2. **Fixed index**: Always indexed as `"p"` regardless of the `idx` argument passed to the constructor.

There is expected to be exactly one planner per environment. To support multiple planners, create a separate subclass.

```python theme={null}
# BasicPlanner state structure
planner.state = {
    "inventory": {"Coin": 0},
    "escrow": {"Coin": 0},
    "endogenous": {"Labor": 0},
    # No "loc" key
    # ...plus any fields added by components
}
planner.idx  # "p"
```

## Defining a custom agent

```python theme={null}
from ai_economist.foundation.base.base_agent import BaseAgent, agent_registry

@agent_registry.add
class MyAgent(BaseAgent):
    name = "MyAgent"
    # Inherits all BaseAgent behavior.
    # Override __init__ to customize initial state.
```

> [!NOTE]
>
> An agent class registered with `@agent_registry.add` is only visible in `foundation.agents` if the file defining it is imported in `ai_economist/foundation/agents/__init__.py`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.