Skip to content

aws-samples/sample-spatial-simulation-agentcore

Spatial Simulation Agentcore

Deploying the geospatial agent-based simulation to AWS using Bedrock AgentCore, Lambda, DynamoDB, and S3.

Architecture

Architecture

  • AgentCore Runtime - Simulation runner container (Strands Agents)
  • AgentCore Gateway - MCP hub exposing 7 world-service tools
  • Lambda - World service (initialize, spawn, move, terminate, save)
  • DynamoDB - World state, agent state, simulation history
  • S3 - Scenario configs, simulation results

See design/ for detailed architecture documents.

Security Hardening

This project is a sample demonstrating architecture patterns -- it is not production-hardened. Before deploying into your own environment, review SECURITY-HARDENING.md for known risks and required mitigations. The document covers a prompt injection attack chain where tampered DynamoDB data can flow through Jinja2 templates into LLM prompts and back into simulation state.

Prerequisites

  • Python 3.12+ and uv
  • Node.js / npm (for CDK)
  • AWS CLI with credentials configured (aws configure or environment variables)
  • Bedrock model access enabled in the target region (Claude Sonnet)

Available Scenarios

Scenario Flag Description
Sugarscape --scenario sugarscape Classic agent-based model with sugar resource gathering
Predator-Prey --scenario predator_prey Lotka-Volterra inspired predator-prey ecosystem simulation

Differences from Canonical Implementations

This project is a demonstration of LLM-driven agent-based simulation, not a faithful reproduction of the original models. The core difference across both scenarios is that agent decisions are made by an LLM rather than deterministic rules or random walks. The mechanics (resource harvesting, metabolism, death) remain rule-based, but movement strategy emerges from the model's reasoning over each agent's local view.

Sugarscape (vs. Epstein & Axtell, Growing Artificial Societies, 1996):

Aspect Canonical Ours
Movement rule Deterministic: move to the nearest cell with the most sugar within vision range LLM chooses target cell given a view of nearby resources and agents
Grid topology Toroidal (edges wrap) Bounded (agents cannot move off-grid)
Conflict resolution Varies by implementation; often allows cell sharing First-come-first-served: only one agent per cell
Reproduction Not in the base model (added as later "rules") Not implemented
Resource regrowth +1 per cell per turn up to capacity Same
Agent attributes Vision, metabolism, initial sugar Same (vision 1-6, metabolism 1-4, sugar 5-25)

Predator-Prey (vs. Wilensky's NetLogo Wolf-Sheep Predation):

Aspect Canonical Ours
Movement rule Random walk LLM chooses target cell given views of prey, predators, and grass
Reproduction trigger Fixed probability per turn (stochastic) Energy threshold: reproduce when energy >= threshold, split energy 50/50 with offspring
Hunting Same-cell overlap kills prey Manhattan distance <= 1 (adjacent cells count)
Terrain No obstacles Random rock placement (default 5%) blocks movement
Conflict resolution None needed (random movement) Cross-type cell sharing allowed; same-type blocked (first-come-first-served)
Grass regrowth Stochastic per patch per turn Same (probability-based regrowth per cell)
Agent attributes Energy only Energy, vision, metabolism, reproduction threshold

Quick Start

# 1. Install all workspace dependencies
uv sync

# 2. Deploy infrastructure (writes cdk-outputs.json to repo root)
uv run geosim deploy --region us-east-1

# 3. Run a simulation (sugarscape or predator_prey)
uv run geosim run --scenario sugarscape --region us-east-1

# 4. Fetch results and generate an animation
uv run geosim analyze <SIMULATION_ID>

# 5. Tear down infrastructure when finished
uv run geosim destroy

Directory Layout

cloud/
  agentcore/
    shared/          # Pydantic models, DynamoDB utils, logging, prompts
    runner/          # Simulation runner (AgentCore Runtime container)
    lambda/
      world_server/  # Lambda MCP tool server
    cli/             # CLI tools (geosim command)
  cdk/               # CDK infrastructure (TypeScript)
  design/            # Architecture documentation

CLI Command Reference

All commands are run via uv run geosim <command>.

geosim deploy

Deploy the simulation infrastructure to AWS.

Usage: geosim deploy [OPTIONS]

Options:
  --region TEXT         AWS region (default: us-east-1)
  --cdk-outputs TEXT   Path for CDK outputs file (default: cdk-outputs.json)
  --skip-bootstrap     Skip CDK bootstrap check

Examples:

uv run geosim deploy
uv run geosim deploy --region us-west-2

geosim destroy

Tear down the deployed simulation infrastructure.

Usage: geosim destroy [OPTIONS]

Options:
  --region TEXT   AWS region (default: us-east-1)

Example:

uv run geosim destroy --region us-west-2

geosim test

Run an end-to-end test simulation against deployed AgentCore.

Usage: geosim test [OPTIONS]

Options:
  --cdk-outputs TEXT    Path to CDK outputs file (default: cdk-outputs.json)
  --region TEXT         AWS region (default: us-east-1)
  --agents INTEGER      Number of agents (default: 10)
  --max-turns INTEGER   Maximum turns (default: 20)

Example:

uv run geosim test --agents 5 --max-turns 10

geosim run

Launch a simulation via deployed AgentCore.

Usage: geosim run [OPTIONS]

Options:
  -s, --scenario TEXT           Scenario name (default: sugarscape)
                                Available: sugarscape, predator_prey
  -r, --run-id TEXT             Custom run identifier
  -t, --max-timesteps INTEGER   Maximum timesteps
  --region TEXT                 AWS region (default: us-east-1)
  --agents INTEGER              Number of agents (default: 50)
  -v, --verbose                 Verbose output
  --cdk-outputs TEXT            Path to CDK outputs file (default: cdk-outputs.json)

Examples:

# Run sugarscape
uv run geosim run --scenario sugarscape --region us-east-1

# Run predator-prey
uv run geosim run --scenario predator_prey --region us-east-1

geosim analyze

Fetch results, compute stats, and generate plots for a simulation.

Usage: geosim analyze [OPTIONS] [SIMULATION_ID]

Options:
  --output-dir TEXT    Output directory (default: output/<sim_id>)
  --format [gif|mp4]   Animation format (default: gif)
  --fps INTEGER        Frames per second (default: 3)
  --cdk-outputs TEXT   Path to CDK outputs file
  --region TEXT        AWS region (default: us-east-1)

Example:

uv run geosim analyze abc123 --format mp4 --fps 5

geosim viz render

Render a single turn state to an image.

Usage: geosim viz render [OPTIONS] INPUT_FILE

Options:
  -o, --output PATH          Output image file [required]
  -s, --style [sugarscape|predator_prey]   Visualization style (default: sugarscape)
  -w, --width INTEGER                      Image width in pixels (default: 800)
  --img-height INTEGER                     Image height in pixels (default: 800)
  --dpi INTEGER                            DPI for output image (default: 100)

Example:

uv run geosim viz render turn_001.json -o frame_001.png

geosim viz render-batch

Render multiple turn states to images.

Usage: geosim viz render-batch [OPTIONS] INPUT_DIR

Options:
  -o, --output-dir PATH      Output directory for frames [required]
  -s, --style [sugarscape]   Visualization style (default: sugarscape)
  -w, --width INTEGER        Image width in pixels (default: 800)
  --img-height INTEGER       Image height in pixels (default: 800)
  --dpi INTEGER              DPI for output images (default: 100)
  -p, --parallel INTEGER     Number of parallel workers (default: 1)
  --pattern TEXT             File pattern to match (default: turn_*.json)

Example:

uv run geosim viz render-batch ./turns -o ./frames -p 4

geosim viz animate

Create video or GIF from rendered frames.

Usage: geosim viz animate [OPTIONS] FRAMES_DIR

Options:
  -o, --output PATH             Output video/GIF file [required]
  -f, --fps INTEGER             Frames per second (default: 5)
  --format [mp4|gif]            Output format (auto-detected from extension)
  --codec [libx264|libx265]     Video codec for mp4 (default: libx264)
  --quality [low|medium|high]   Video quality (default: high)
  --pattern TEXT                Frame file pattern (default: *.png)

Example:

uv run geosim viz animate ./frames -o simulation.gif --fps 3

How It Works

The deploy-test-analyze pipeline:

  1. geosim deploy provisions all AWS resources (Lambda, DynamoDB, S3, AgentCore) and writes connection details to cdk-outputs.json at the repo root.
  2. geosim test and geosim run read cdk-outputs.json (via --cdk-outputs) to locate the deployed stack, then launch simulations through AgentCore.
  3. Simulation results (turn states, agent decisions) are stored in S3 and DynamoDB.
  4. geosim analyze fetches the results from S3/DynamoDB, computes statistics, and generates plots and animations locally.
  5. geosim viz subcommands operate on local JSON turn-state files and rendered frames for fine-grained visualization control.

Troubleshooting

Missing AWS credentials Ensure aws configure has been run or AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY environment variables are set. Verify with aws sts get-caller-identity.

CDK bootstrap failure If geosim deploy fails during bootstrap, run npx cdk bootstrap aws://<ACCOUNT_ID>/<REGION> manually. Use --skip-bootstrap on subsequent deploys once bootstrapping succeeds.

Missing node_modules CDK requires Node dependencies. Run npm install inside cloud/cdk/ before deploying.

cdk-outputs.json not found geosim test, run, and analyze expect cdk-outputs.json at the repo root (produced by geosim deploy). If you moved or deleted it, redeploy or point to the file with --cdk-outputs path/to/file.json.

Security

See CONTRIBUTING for more information.

License

This library is licensed under the MIT-0 License. See the LICENSE file.

About

No description, website, or topics provided.

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors