mesa icon indicating copy to clipboard operation
mesa copied to clipboard

Add agent-level action lifecycle hooks

Open EwoutH opened this issue 8 months ago • 7 comments

Summary

Adds three hooks to Agent that fire after the corresponding Action hooks, giving agents a centralized place for behavioral decision logic.

Quick prototype to see how https://github.com/mesa/mesa/discussions/3304#discussioncomment-16242923 would look. No tests etc. yet.

Motive

Currently, every Action.on_complete and Action.on_interrupt must include "what next?" logic, leading to duplicated decision code across actions. This couples action effects with agent-level behavioral decisions.

With agent-level hooks, actions stay single-purpose (defining their own effects), while the agent handles decisions in one place:

class Forage(Action):
    def on_complete(self):
        self.agent.energy += 30  # Just the effect

class Sheep(Agent):
    def on_action_complete(self, action):
        if self.energy < 30:
            self.start_action(Rest(self))
        else:
            self.start_action(Forage(self))

Implementation

agent.py — Three new no-op methods on Agent:

  • on_action_start(action) — called after Action.on_start/on_resume
  • on_action_complete(action) — called after Action.on_complete
  • on_action_interrupt(action, progress) — called after Action.on_interrupt

actions.py — One line added in each of:

  • Action.start() — calls agent.on_action_start (skipped for instantaneous actions, which go through _do_complete instead)
  • Action._do_complete() — calls agent.on_action_complete
  • Action.interrupt() and Action.cancel() — call agent.on_action_interrupt

Usage Examples

Before: decision logic duplicated in every action:

class Forage(Action):
    def on_complete(self):
        self.agent.energy += 30
        # decision logic here...
        if self.agent.sees_predator():
            self.agent.start_action(Flee(self.agent))
        elif self.agent.energy > 80:
            self.agent.start_action(Rest(self.agent))
        else:
            self.agent.start_action(Forage(self.agent))

class Rest(Action):
    def on_complete(self):
        self.agent.energy = min(100, self.agent.energy + 20)
        # ...duplicated here
        if self.agent.sees_predator():
            self.agent.start_action(Flee(self.agent))
        elif self.agent.energy > 80:
            self.agent.start_action(Rest(self.agent))
        else:
            self.agent.start_action(Forage(self.agent))

class Flee(Action):
    def on_complete(self):
        self.agent.move_away_from_predator()
        # ...and here
        if self.agent.sees_predator():
            self.agent.start_action(Flee(self.agent))
        elif self.agent.energy > 80:
            self.agent.start_action(Rest(self.agent))
        else:
            self.agent.start_action(Forage(self.agent))

After: actions are single-purpose, decisions live in one place:

class Forage(Action):
    def on_complete(self):
        self.agent.energy += 30

class Rest(Action):
    def on_complete(self):
        self.agent.energy = min(100, self.agent.energy + 20)

class Flee(Action):
    def on_complete(self):
        self.agent.move_away_from_predator()

class Sheep(Agent):
    def on_action_complete(self, action):
        self.decide_next()

    def on_action_interrupt(self, action, progress):
        self.decide_next()

    def decide_next(self):
        if self.sees_predator():
            self.start_action(Flee(self))
        elif self.energy < 30:
            self.start_action(Rest(self))
        else:
            self.start_action(Forage(self))

Adding a fourth action (e.g. Drink) requires zero changes to decision logic. Changing the decision logic requires updating only one method.

All hooks default to pass, so existing code is unaffected.

Additional Notes

  • Hooks fire after the Action's own hooks, so Action.on_complete runs before Agent.on_action_complete.
  • Zero-duration actions fire on_action_complete but not on_action_start, avoiding double-firing in the same instant.
  • This is purely additive, you can still put all logic in Action.on_complete if you want.
  • Ref: https://github.com/mesa/mesa/discussions/3304#discussioncomment-16242923

EwoutH avatar Mar 21 '26 19:03 EwoutH

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 -4.0% [-5.7%, -2.0%] 🔵 -1.3% [-1.6%, -0.9%]
BoltzmannWealth large 🔵 -0.7% [-1.7%, +0.3%] 🔵 +6.2% [+1.9%, +11.4%]
Schelling small 🔵 -1.1% [-2.0%, -0.3%] 🔵 +1.0% [-0.2%, +2.5%]
Schelling large 🔵 -1.1% [-1.6%, -0.7%] 🔵 +0.9% [-0.0%, +1.9%]
WolfSheep small 🔵 -1.6% [-2.5%, -0.7%] 🔵 +1.9% [-2.8%, +6.8%]
WolfSheep large 🔵 +0.9% [+0.3%, +1.4%] 🔵 +0.7% [-1.0%, +2.3%]
SugarscapeG1mt small 🔵 -1.3% [-2.6%, +0.1%] 🔵 +0.9% [-0.7%, +2.6%]
SugarscapeG1mt large 🔴 +11.5% [+7.1%, +16.7%] 🔴 +7.6% [+5.7%, +9.7%]
BoidFlockers small 🔵 -0.5% [-2.0%, +1.0%] 🔵 -1.4% [-2.1%, -0.7%]
BoidFlockers large 🔵 +2.6% [+1.7%, +3.7%] 🔵 -0.7% [-0.9%, -0.6%]

github-actions[bot] avatar Mar 21 '26 19:03 github-actions[bot]

I find it confusing that you speak of firing. Signals are emitted or fired, but here the methods are simply called directly.

This couples action effects with agent-level behavioral decisions|.

Yes, this is a very important and useful distinction.

I don't fully agree, however, with your example where you put all agent decision logic in your actions. I can easily envision using the current actions merely as a way of scheduling an activity that lasts for a given duration and has a fixed effect while ending with a callback to the owning agent (see below). This PR mainly formalizes this.

class Forage(Action):
    def on_complete(self):
        self.agent.energy += 30
        self.agent.action_completed()

I am, however, a bit concerned about the api design. We now have Action.on_x and Agent.on_action_x. Namewise, these are quite close together, which might cause confusion. It also suggests we might have to move the agent action stuff into a HasActions class as discussed before.

quaquel avatar Mar 22 '26 09:03 quaquel

@quaquel On the naming confusion between Action.on_x and Agent.on_action_x — one option would be a HasActions mixin that groups on_action_complete, on_action_interrupt, on_action_start together, making the agent-side hooks clearly separate from the action-side hooks. This also keeps the base Agent class clean for agents that don't use Actions at all.

Vanya-kapoor avatar Mar 22 '26 10:03 Vanya-kapoor

Great work on Actions @EwoutH

I’ve been tackling this exact problem, separating an action's physical effect from the agent's decision of "what to do next", while prototyping a Behavioral Framework proposal.

While I agree with @EwoutH’s goal of removing decision boilerplate from Action.on_complete, I share @quaquel's concerns about the API design. Adding direct method calls to the base Agent class creates a few architectural friction points: It keeps the Action tightly coupled to the Agent's API. If an agent wants to react to an action completing, it is forced to implement a specific method name.

To solve this without cluttering the agent, I actually leaned exactly into the HasActions(In my case I called it TaskManager) concept that @quaquel mentioned, combined with signals

Instead of putting hooks on the Agent, I built a TaskManager (which essentially acts as a HasActions component). Here is the data flow:

  1. The Action (Task) handles its own physical effect in on_complete (e.g., self.agent.energy += 30).
  2. The Action notifies the TaskManager that it is done.
  3. The TaskManager emits a signal (TaskSignals.COMPLETED).
  4. A DecisionSystem(which is agent's brain in my proposal) simply observes that signal to trigger the next decision.

Here is what that looks like in practice.

class BehavioralAgent(Agent, HasEmitters):
    def __init__(self, model):
        ...
        self.task_manager = TaskManager(self) 
        self.decision_system = DecisionSystem(self, self.task_manager)
        self.observe("task_manager", TaskSignals.COMPLETED, self._on_action_done)

    def _on_action_done(self, **kwargs):
        # Action is done. Evaluate the environment and do the next thing!
        self.decision_system.evaluate() 

Instead of adding on_action_complete, on_action_interrupt, etc., to the base Agent class, what if the Action class simply utilize the Signals to emit ActionSignals.COMPLETED?Curious to hear your thoughts!

codebreaker32 avatar Mar 22 '26 17:03 codebreaker32

@quaquel what do you think about Aman’s approach?

EwoutH avatar Mar 23 '26 05:03 EwoutH

I like the richer conceptual design. I am less sure about the specific use of signals.

For me, signals are used for asynchronous communication. But if an agent starts an action, and it then completes, to me the agent's response to this is synchronous not asynchronous. Would have to see a more worked out conceptual diagram or so to provide more feedback.

This does not mean that actions should/could not fire signals on start, interupt and completion. But these would be for, for example, statistics gathering.

quaquel avatar Mar 23 '26 10:03 quaquel

Would have to see a more worked out conceptual diagram or so to provide more feedback.

I have discussed a preliminary design here https://github.com/mesa/mesa/discussions/3428 However I need to update it with some of my later findings, new Action arch and your current feedbacks.

codebreaker32 avatar Mar 23 '26 14:03 codebreaker32