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: Agent

LLMAgent 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 to gemini/gemini-2.0-flash.

system_prompt (str | None): Optional system prompt for the LLM. vision (float | None): Observation radius for nearby agents. Use -1

to 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

property system_prompt: str | None#
async aapply_plan(plan: Plan) list[dict][source]#

Asynchronous version of apply_plan.

apply_plan(plan: Plan) list[dict][source]#

Execute the plan in the simulation.

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.

send_message(message: str, recipients: list[Agent]) str[source]#

Send a message to the recipients.

async apre_step()[source]#

Asynchronous version of pre_step.

async apost_step()[source]#

Asynchronous version of post_step.

pre_step()[source]#

This is some code that is executed before the step method of the child agent is called.

post_step()[source]#

This is some code that is executed after the step method of the child agent is called. It functions because of the __init_subclass__ method that creates a wrapper around the step method of the child agent.

async astep()[source]#

Default asynchronous step method for parallel agent execution. Subclasses should override this method for custom async behavior. If not overridden, falls back to calling the synchronous step() method.