Skip to content

Commit e7422b2

Browse files
fix: guard against non-LLM recipients in speak_to tool(#158)
1 parent 4ea91ed commit e7422b2

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

mesa_llm/tools/inbuilt_tools.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import logging
12
from typing import TYPE_CHECKING, Any
23

34
from mesa.discrete_space import (
@@ -15,6 +16,8 @@
1516
if TYPE_CHECKING:
1617
from mesa_llm.llm_agent import LLMAgent
1718

19+
logger = logging.getLogger(__name__)
20+
1821
# Mapping directions to (dx, dy) for Cartesian-style spaces.
1922
direction_map_xy = {
2023
"North": (0, 1),
@@ -208,6 +211,12 @@ def speak_to(
208211
]
209212

210213
for recipient in listener_agents:
214+
if not hasattr(recipient, "memory"):
215+
logger.warning(
216+
"Agent %s has no memory attribute; skipping speak_to.",
217+
recipient.unique_id,
218+
)
219+
continue
211220
recipient.memory.add_to_memory(
212221
type="message",
213222
content={

tests/test_tools/test_inbuilt_tools.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,3 +582,30 @@ class _DummyOrthogonalGrid(OrthogonalMooreGrid):
582582

583583
assert agent.cell is wrapped_cell
584584
assert result == "agent 29 moved to (2, 2)."
585+
586+
587+
def test_speak_to_skips_non_llm_recipient(mocker):
588+
"""
589+
speak_to must not crash when a recipient has no memory attribute.
590+
591+
This covers the case where a non-LLM (rule-based) agent is listed as a
592+
recipient.
593+
"""
594+
model = DummyModel()
595+
596+
sender = DummyAgent(unique_id=1, model=model)
597+
llm_recipient = DummyAgent(unique_id=2, model=model)
598+
rule_recipient = DummyAgent(unique_id=3, model=model)
599+
600+
llm_recipient.memory = SimpleNamespace(add_to_memory=mocker.Mock())
601+
602+
model.agents = [sender, llm_recipient, rule_recipient]
603+
604+
ret = speak_to(sender, [2, 3], "Hello both")
605+
606+
llm_recipient.memory.add_to_memory.assert_called_once()
607+
call_kwargs = llm_recipient.memory.add_to_memory.call_args[1]
608+
assert call_kwargs["type"] == "message"
609+
assert call_kwargs["content"]["message"] == "Hello both"
610+
611+
assert "2" in ret and "3" in ret

0 commit comments

Comments
 (0)