LLMAgent#
LLMAgent is the core agent class in Mesa-LLM that extends Mesa’s base Agent class with Large Language Model capabilities. It provides a complete framework for creating intelligent agents that can reason, remember, communicate, and act in simulations using natural language processing.
Basic Agent Implementation#
from mesa_llm.llm_agent import LLMAgent
from mesa_llm.reasoning.cot import CoTReasoning
class MyAgent(LLMAgent):
def __init__(self, model, **kwargs):
super().__init__(
model=model,
reasoning=CoTReasoning,
llm_model="openai/gpt-4o",
system_prompt="You are a helpful agent in a simulation.",
vision=2, # See 2 cells in each direction
internal_state=["curious", "cooperative"],
step_prompt="Decide what to do next based on your observations.",
api_base=None, # Set to a custom URL for self-hosted LLMs (e.g., "http://192.168.1.100:11434")
)
# You can override default memory with EpisodicMemory (default is STLTMemory)
self.memory = EpisodicMemory(
agent=self,
llm_model="openai/gpt-4o-mini",
max_memory=20
)
def step(self):
# Generate current observation
obs = self.generate_obs()
# Use reasoning to create plan
plan = self.reasoning.plan(obs=obs)
# Execute the plan
self.apply_plan(plan)
Parallel Execution Example#
class ParallelAgent(LLMAgent):
async def astep(self): # Use 'async' with astep method to enable parallel execution
"""Asynchronous step for parallel execution"""
obs = self.generate_obs()
plan = await self.reasoning.aplan( # Use 'await' with aplan method to enable parallel execution
prompt=self.step_prompt,
obs=obs
)
self.apply_plan(plan)
Agent Communication Example#
def step(self):
obs = self.generate_obs()
# Find nearby agents
neighbors = [agent for agent in obs.local_state.keys()]
if neighbors:
# Send message to neighbors
neighbor_ids = [int(name.split()[-1]) for name in neighbors]
self.send_message("Hello neighbors!",
[agent for agent in self.model.agents
if agent.unique_id in neighbor_ids])
plan = self.reasoning.plan(obs=obs)
self.apply_plan(plan)
API Reference#
- class LLMAgent(model: Model, reasoning: type[Reasoning], llm_model: str = 'gemini/gemini-2.0-flash', system_prompt: str | None = None, vision: float | None = None, internal_state: list[str] | str | None = None, step_prompt: str | None = None, api_base: str | None = None)[source]#
Bases:
AgentLLMAgent manages an LLM backend and optionally connects to a memory module.
- Parameters:
model (Model): The Mesa model the agent belongs to. reasoning (type[Reasoning]): The reasoning strategy used by the agent. llm_model (str): The model to use for the LLM in the format
provider/model. Defaults togemini/gemini-2.0-flash.system_prompt (str | None): Optional system prompt for the LLM. vision (float | None): Observation radius for nearby agents. Use
-1to observe all agents in the simulation.
- internal_state (list[str] | str | None): Optional internal state facts
exposed to the reasoning module.
- step_prompt (str | None): Optional task-specific prompt used to guide
the agent each step.
- api_base (str | None): Optional custom LiteLLM-compatible base URL for
self-hosted or remote inference endpoints.
- Attributes:
llm (ModuleLLM): The internal LLM interface used by the agent. memory (Memory | None): The memory module attached to this agent, if any. tool_manager (ToolManager): The tool registry available to the agent.
Create a new agent.
- Args:
model (Model): The model instance in which the agent exists. args: Passed on to super. kwargs: Passed on to super.
- Notes:
to make proper use of python’s super, in each class remove the arguments and keyword arguments you need and pass on the rest to super
- async agenerate_obs() Observation[source]#
This method builds the agent’s observation using the shared observation construction logic, stores it in the agent’s memory module using async memory operations, and returns it as an Observation instance.
- generate_obs() Observation[source]#
This method delegates observation construction to the shared observation builder, stores the resulting observation in the agent’s memory module, and returns it as an Observation instance.
- async asend_message(message: str, recipients: list[Agent]) str[source]#
Asynchronous version of send_message.
- pre_step()[source]#
This is some code that is executed before the step method of the child agent is called.