A powerful, TypeScript-first agent-based modeling framework with built-in p5.js visualization, designed for creating interactive simulations, social impact games, and educational experiences.
Live examples, a guide and the API reference: https://prayasabhinav.github.io/AgentJS/
AgentJS Core is a comprehensive framework for building agent-based models (ABMs) in the browser or Node.js. It provides a robust foundation for simulating complex systems through autonomous agents that interact within defined environments. Whether you're modeling social networks, ecological systems, economic markets, or creating educational games about social dynamics, AgentJS Core offers the tools you need.
npm install @prayas_abhinav/agentjs-core p5
Note: p5.js is a peer dependency and must be installed separately.
From 1.1.0, which adds NSMnum, the package is @prayas_abhinav/agentjs-core; version 1.0.1 stays on npm under the old name, agentjs-core. To build it from this repository instead:
git clone https://github.com/prayasabhinav/AgentJS.git
cd AgentJS
npm ci
npm run build
Walkers in a continuous space, run in Node.js. The environment holds the agents and answers questions about where they are; the scheduler calls each agent's step(); the agent moves itself, and moveAgent makes the space apply its boundary. In a clone, build first and import ./dist/index.es.js in place of @prayas_abhinav/agentjs-core.
import { MovingAgent, ContinuousSpace, RandomScheduler } from '@prayas_abhinav/agentjs-core';
class Walker extends MovingAgent {
constructor(id, space) {
super(id, {}, { x: 250, y: 250 }, { maxSpeed: 2 });
this.space = space;
}
step() {
this.wander(1); // a push in a random direction
super.step(); // apply friction and the top speed, then move
this.space.moveAgent(this, this.position); // the space wraps the walker at the edges
}
}
const space = new ContinuousSpace({
width: 500,
height: 500,
boundaryType: 'periodic',
enableSpatialIndex: true,
maxObjectsPerNode: 10,
maxTreeDepth: 6,
});
const scheduler = new RandomScheduler();
for (let i = 0; i < 100; i++) {
const walker = new Walker(`walker-${i}`, space);
space.addAgent(walker);
scheduler.addAgent(walker);
}
for (let step = 0; step < 200; step++) scheduler.step();
const away = space.getAllAgents().filter((walker) => space.distance(walker.position, { x: 250, y: 250 }) > 50);
console.log(`after ${scheduler.getCurrentStep()} steps, ${away.length} of ${space.getAgentCount()} walkers are more than 50 from the start`);
The same model, drawn with p5.js, is the first of the live examples.
Create interactive lessons about complex systems:
Build games that explore social issues:
Conduct computational experiments:
Create generative and responsive experiences:
import { MovingAgent, NetworkAgent } from '@prayas_abhinav/agentjs-core';
// An agent that moves: forces push it, and step() applies friction, the top speed and the move
class Seeker extends MovingAgent {
constructor(id, marker) {
super(id, { energy: 100 }, { x: 0, y: 0 }, { maxSpeed: 3 });
this.marker = marker;
}
step() {
if (this.distanceTo(this.marker) < 200) {
this.moveToward(this.marker, 0.5); // add a force towards the marker
} else {
this.wander(0.4); // add a force in a random direction
}
this.setProperty('energy', this.getProperty('energy') - 1);
super.step(); // friction, top speed, then the move
}
}
const seeker = new Seeker('seeker-1', { x: 100, y: 50 });
for (let i = 0; i < 100; i++) seeker.step();
console.log(`seeker is at ${seeker.position.x.toFixed(0)}, ${seeker.position.y.toFixed(0)} with energy ${seeker.getProperty('energy')}`);
// An agent with connections: connect() links it to another agent, getNeighbors() returns the agents it is linked to
class Talker extends NetworkAgent {
constructor(id, opinion) {
super(id, { opinion });
}
step() {
const neighbours = this.getNeighbors();
if (neighbours.length === 0) return;
const average = neighbours.reduce((sum, agent) => sum + agent.getProperty('opinion'), 0) / neighbours.length;
this.setProperty('opinion', this.getProperty('opinion') * 0.9 + average * 0.1);
}
}
const a = new Talker('a', 0);
const b = new Talker('b', 1);
a.connect(b, 'friend', 0.8);
for (let i = 0; i < 10; i++) a.step();
console.log(`a's opinion is now ${a.getProperty('opinion').toFixed(3)}; a has ${a.getConnectionCount()} connection`);
MovingAgent moves by forces: addForce, moveToward, moveAway and wander add to its velocity, and step() applies friction and the top speed and moves it. Agents that are in an environment should call environment.moveAgent(agent, agent.position) after super.step(), so the environment applies its boundary and updates its index. To ask the environment who is near, use environment.findNeighbors(position, radius, { filterFn }), which returns { items }.
import { Visualizer } from '@prayas_abhinav/agentjs-core';
// p5 must be loaded as a global (a script tag, or window.p5 = p5); the Visualizer creates the sketch itself.
const visualizer = new Visualizer({
canvas: { width: 800, height: 600, background: 240 },
agents: { defaultSize: 6, minSize: 3, maxSize: 12, colorProperty: 'energy' }, // colour agents by their 'energy' property
});
visualizer.setEnvironment(space); // the ContinuousSpace or Grid2D agents are in
visualizer.setAgents(new Map(space.getAllAgents().map((agent) => [agent.id, agent]))); // agents, by id
visualizer.initialize(document.getElementById('sketch')); // creates the canvas inside this element
// Step your model on your own timer or loop; the Visualizer draws what it finds.
// visualizer.setNetworkManager(network) draws connections; visualizer.toggleHeatMapLayer('density') and
// visualizer.toggleAgentTrails(true) switch on the heat map and trails; visualizer.getCameraState() and
// visualizer.setCameraState({ x, y, zoom }) move the camera.
Visualizer owns its camera, trails, heat maps and particle effects (getHeatMapSystem(), getTrailSystem(), getParticleSystem(), getAnimationEngine()). Camera and HeatMapSystem can also be made alone: new Camera(config) takes an optional configuration object, not a sketch, and new HeatMapSystem() takes no arguments. The live examples instead draw with p5.js directly, in instance mode, reading the model each frame.
An MLAgent asks a behaviour model what to do each step and runs the action it returns. A behaviour model is any object with these five methods; ModelRegistry.getInstance().registerModel(name, path) loads a TensorFlow.js model file into one.
import { MLAgent } from '@prayas_abhinav/agentjs-core';
// Any object with these five methods is a behaviour model. This one always answers "move right".
const alwaysRight = {
async predict(state) {
return { type: 'MOVE', parameters: { dx: 5, dy: 0 }, confidence: 1 };
},
async load() {},
getRequiredInputs: () => ['energy'],
getOutputActions: () => ['MOVE'],
dispose() {},
};
const agent = new MLAgent('thinker', { energy: 50 });
await agent.loadBehaviorModel(alwaysRight);
await agent.step(); // the model is asked, and the action it returns is run
console.log(`x is now ${agent.position.x}`);
An action is { type, parameters }, where type is 'MOVE' (dx, dy), 'CHANGE_PROPERTY' (property with either delta or absolute), 'INTERACT' or 'CUSTOM'. If the model throws, the agent runs a fallback action (a random move unless one is set).
An NSMnum, Narrow Small Model (numerating), said en-ess-em-num, is a small model that answers only with a number: the place of one action in a fixed list, or none. It writes no text and does not act: your code checks each answer and decides what runs. The method is called ungli (repository); the parts of an NSMnum are listed on its page on SYNTAX (NSMnum syntax).
In AgentJS each agent type can have its own NSMnum. A table in your code gives each type a row: its NSMnum, its list of actions, and the action it takes when the answer is none (its "don't know").
import { MLAgent, NSMnumTable, TensorFlowChooser } from '@prayas_abhinav/agentjs-core';
import type { AgentAction, MLAgentState } from '@prayas_abhinav/agentjs-core';
class Reader extends MLAgent {}
class Walker extends MLAgent {}
const actions: AgentAction[] = [
{ type: 'MOVE', parameters: { dx: 1, dy: 0 } }, // place 0: right
{ type: 'MOVE', parameters: { dx: -1, dy: 0 } }, // place 1: left
];
const wait: AgentAction = { type: 'CHANGE_PROPERTY', parameters: { property: 'waiting', absolute: 1 } };
const encode = (state: MLAgentState) => [state.properties.energy ?? 0]; // turns a state into the numbers the model reads
// an untrained chooser answers almost at random; train it on your keys (below)
const readerChooser = new TensorFlowChooser(TensorFlowChooser.create(1, actions.length), encode, 0.6);
const walkerChooser = new TensorFlowChooser(TensorFlowChooser.create(1, actions.length), encode, 0.6);
const table = new NSMnumTable([
{ agentType: Reader, model: readerChooser, actions, none: wait },
{ agentType: Walker, model: walkerChooser, actions, none: wait,
allowed: (state, place) => state.position.x > 0 || place === 0 }, // at x ≤ 0, only place 0 (right) is allowed
]);
const readers = [new Reader(), new Reader()], walkers = [new Walker()];
const uncovered = await table.assign([...readers, ...walkers]); // agents no row covers come back to you
In code, places count from 0: actions[0] is place 0. An answer counts as none when it is not a whole number from 0 to actions.length - 1, when allowed returns false, or when the model throws; on none, the agent runs the row's none action. Rows match with instanceof, and the first row an agent matches is its row, so put subclasses before the classes they extend.
TensorFlowChooser.create(inputs, actions.length) makes a small TensorFlow.js model with one output per action and a last one for none; new TensorFlowChooser(model, encode, threshold) wraps it as an NSMnum. An answer whose highest output (a softmax probability) is below the threshold counts as none; with a threshold of 0, the default, no answer is refused this way. Choose the threshold by checking the chooser's answers on keyed situations you left out of training.
The table in JSON. Rows can be written in a JSON file of your own, under nsmnum, and then match agents by their kind property instead of by class:
{
"nsmnum": [
{
"kind": "literal",
"model": "models/literal/model.json",
"reads": ["distance", "concreteness"],
"actions": [
{ "type": "MOVE", "parameters": { "dx": 1, "dy": 0 } },
{ "type": "MOVE", "parameters": { "dx": -1, "dy": 0 } }
],
"none": { "type": "CHANGE_PROPERTY", "parameters": { "property": "waiting", "absolute": 1 } },
"threshold": 0.6
}
]
}
import fs from 'node:fs';
import { tableFromJSON } from '@prayas_abhinav/agentjs-core';
const config = JSON.parse(fs.readFileSync('settings.json', 'utf8'));
const table = await tableFromJSON(config.nsmnum); // a browser fetches each model file
await table.assign(agents); // agents with properties like { kind: 'literal', distance: 0.2, concreteness: 0.8 }
reads names the numeric properties the model reads, in order; an agent missing one of them gets none. Every row is checked before anything loads, and each model must read as many numbers as reads names and give one output per action plus one for none; otherwise the table is not built and the error names the row. A row that needs an allowed check must be written in code, not JSON.
A model file is a trained chooser saved with TensorFlow.js: await chooser.model.save('downloads://literal') in a browser, or, in Node with @tensorflow/tfjs-node installed, await chooser.model.save('file://models/literal') and the loader (path) => tf.loadLayersModel('file://' + path) as tableFromJSON's second argument. To key and train for a JSON row, write the encode it uses: its reads, in order, (state) => row.reads.map((name) => state.properties[name]).
Train an NSMnum on your keys and nothing else. A key is your answer for one situation: the number of the action you would have the agent take, or 0 for none. You give keys on a blind sheet, which shows each situation with no model's answer on it. The package ships no keys: you key your own, and the keys stay in a file on your machine.
These steps use keyingItems, readKeys and keyedRows from @prayas_abhinav/agentjs-core, and Node's fs. Each agent type has its own NSMnum, so keep its situations, its sheet, its keys file and its training apart from every other type's.
{ id: `${agent.id}-${step}`, state: agent.getCurrentState() }. Each id must be unique: the keyer skips an id it has seen, and readKeys keeps only the latest key for it.fs.writeFileSync('sheet.json', JSON.stringify(keyingItems(situations, ['right', 'left']))). Each item shows the agent's position, each of its numeric properties (except the four MLAgent keeps about its own model: mlEnabled, predictionConfidence, fallbackMode, errorRate) and its number of neighbours, then the actions numbered from 1, with 0 for none.npx agentjs-key sheet.json my.keys.jsonl
Type the number of the action you would choose, 0 for none, s to skip, q to stop. Run it again later and it shows only the situations not yet keyed, skipped ones included. If your project is in git, add *.keys.jsonl to its .gitignore.
4. Read the keys back and train:
const { keys, unread } = readKeys(fs.readFileSync('my.keys.jsonl', 'utf8'), actions.length);
await readerChooser.train(keyedRows(situations, keys, encode), actions.length);
On the sheet, actions are numbered from 1 and 0 means none; readKeys turns them into places counted from 0. A key outside the list is not used, and its item's id comes back in unread. keyedRows needs the same situations you wrote the sheet from; if you key in a later session, save each id with encode(state) beside the sheet and pass { id, features, place } rows to train yourself. Train an NSMnum only on keys, never on its own answers or on a run's outcomes.
test-nsmnum.mjs checks this behaviour against the built package; after npm run build, npm test runs it.
ConfigurationManager holds a model's settings: numbers with limits, presets, and a JSON form you can save and load. It does not build a simulation from them; your code reads the settings and builds the model.
import { ConfigurationManager } from '@prayas_abhinav/agentjs-core';
const config = new ConfigurationManager();
config.on('config:validation-error', (message) => console.log('refused:', message));
config.setParameter('agents.initialCount', 80); // true: it is a number from 1 to 1000
config.setParameter('agents.initialCount', 5000); // false: out of range, and 'config:validation-error' is emitted
config.updateConfig({ environment: { width: 1000 } }); // merge a partial configuration
console.log(config.getParameter('agents.initialCount'), config.getParameter('environment.width'));
console.log(config.getAvailablePresets()); // [ 'educational', 'performance', 'research' ]
config.loadPreset('research');
const saved = config.exportConfig('json'); // a JSON string
const again = new ConfigurationManager();
again.importConfig(saved, 'json'); // true when the string is valid
console.log(again.getParameter('agents.initialCount') === config.getParameter('agents.initialCount'));
The sections of a configuration are simulation, agents, environment, network, visualization, dataCollection and export. getParameterDefinition(key) and getParametersByCategory() give each known parameter's type, range and description, for building a settings panel.
ParameterTuner exists, but it does not run your model: the step that should run a simulation for each setting is a placeholder that waits 100 milliseconds. A parameter sweep is a loop around a function that builds and runs a fresh model for each value:
import { MovingAgent, ContinuousSpace, RandomScheduler } from '@prayas_abhinav/agentjs-core';
// A parameter sweep is a loop: build a fresh model for each value, run it, and record what you measure
function run(maxSpeed) {
const space = new ContinuousSpace({ width: 500, height: 500, boundaryType: 'periodic', enableSpatialIndex: true, maxObjectsPerNode: 10, maxTreeDepth: 6 });
const scheduler = new RandomScheduler(42); // a seed makes a run repeatable
for (let i = 0; i < 50; i++) {
const walker = new MovingAgent(`walker-${i}`, {}, { x: 250, y: 250 }, { maxSpeed });
space.addAgent(walker);
scheduler.addAgent(walker);
}
for (let step = 0; step < 100; step++) {
for (const walker of space.getAllAgents()) walker.wander(1);
scheduler.step();
for (const walker of space.getAllAgents()) space.moveAgent(walker, walker.position);
}
const far = space.getAllAgents().reduce((sum, walker) => sum + space.distance(walker.position, { x: 250, y: 250 }), 0);
return far / space.getAgentCount();
}
for (const maxSpeed of [1, 2, 3, 4]) console.log(`maxSpeed ${maxSpeed}: mean distance from the start ${run(maxSpeed).toFixed(1)}`);
DataCollector, StatisticsEngine and ExportManager are built around a Simulation class that the package does not export, and DataCollector collects only when that object tells it a step has completed, so they cannot be driven from the exports alone. Collect the numbers you want in your own loop. TrajectoryExporter needs only an AgentManager:
import { AgentManager, MovingAgent, TrajectoryExporter } from '@prayas_abhinav/agentjs-core';
const manager = new AgentManager();
for (let i = 0; i < 5; i++) manager.addAgent(new MovingAgent(`agent-${i}`, { energy: 100 }, { x: i * 10, y: 0 }));
const exporter = new TrajectoryExporter({ fields: ['energy'], sampleRate: 1 });
const energy = []; // your own numbers, collected in your own loop
for (let step = 0; step < 20; step++) {
for (const agent of manager.getAllAgents()) agent.wander(1);
manager.stepAll(); // calls step() on every active agent
exporter.recordTrajectoryStep(manager, step);
energy.push(manager.getAllAgents().reduce((sum, agent) => sum + agent.getProperty('energy'), 0) / manager.getAgentCount());
}
const csv = exporter.exportTrajectoriesCSV(); // a string: write it to a file yourself
console.log(csv.split('\n').slice(0, 3).join('\n'));
console.log(`${csv.split('\n').length - 1} rows; mean energy at the end ${energy[energy.length - 1]}`);
stepAll() steps them, but it knows nothing about environments or schedulers)ConfigurationManager)Full API documentation, generated from the source, is at https://prayasabhinav.github.io/AgentJS/api/. A guide and live examples are at https://prayasabhinav.github.io/AgentJS/. To rebuild the API pages: npm run docs.
# Clone the repository
git clone https://github.com/prayasabhinav/AgentJS.git
cd AgentJS
# Install dependencies
npm install
# Run development server
npm run dev
# Run tests (after npm run build; they use the built package)
npm test
# Build for production
npm run build
src/
├── core/ # Agents, environments, schedulers, networks, behaviour trees
│ ├── agents/
│ ├── environment/
│ ├── scheduling/
│ ├── interactions/
│ ├── network/
│ ├── behaviors/
│ └── performance/
├── analysis/ # Data collection, statistics and export
├── controls/ # Control panel and parameter manager (not exported by the package)
├── ml/ # Machine learning and NSMnum
├── performance/ # Object pooling and viewport culling
├── types/ # Shared types
├── utils/ # Configuration, parameter tuning, maths
└── visualization/ # p5.js rendering components
docs/ # The site: examples, guide, API reference
examples/ # Demos and notes (see examples/README.md)
Contributions are welcome. To report a problem or suggest a change, open an issue or a pull request at https://github.com/prayasabhinav/AgentJS.
git checkout -b feature/AmazingFeature)git commit -m 'Add some AmazingFeature')git push origin feature/AmazingFeature)Live examples, each with its explanation and full source, are at https://prayasabhinav.github.io/AgentJS/: walkers in a continuous space, two kinds on a grid, opinions along connections, a behaviour tree, and NSMnum with untrained choosers. Their source is in docs/examples/<name>/example.js.
The /examples directory holds older demos and notes: foundation-features-demo.ts, ml-enhanced-simulation.ts, ml-models/, week5-working-demo.html and week5-advanced-visualization-demo.html. examples/README.md says what each does and which of them have known errors (remaining_errors.txt).
MIT License - see LICENSE file for details
AgentJS Core - Empowering developers to model complex systems and create impactful simulations 🚀