1How do I see how a behaviour spreads when it depends on who is next to whom?
Lay out a grid where each cell is a small agent: a customer, a store, a road segment. Every cell reads only its neighbours and one rule written in plain language, and all cells update together at each step. Running the steps shows how adoption, churn or congestion spreads.
You may need it if
- You ask "what if" about spread, such as word of mouth, churn contagion or traffic build-up.
- Each actor reacts mostly to those closest to it, not to a central signal.
- The rule is easy to state for one actor but the overall result is hard to guess.
2When is a grid of agents the wrong way to model a question?
Use it when
- Influence is local, such as neighbouring shops, teams on the same floor or adjacent regions.
- The rule can be written in a few plain sentences, but involves judgement a formula cannot capture.
- You want to compare scenarios, such as different starting points or rules, more than predict one exact number.
Avoid it when
- The rule is exact, like "adopt if three or more neighbours adopted". Write it as ten lines of code; no model is needed.
- You need to foresee the outcome of one decision before taking it, not watch many actors interact.
Use Mental Simulation instead - A few actors with distinct goals argue a position, rather than many similar actors reacting locally.
Use Debate instead - Anyone can influence anyone, such as a viral post. A neighbour grid misrepresents the network.
What it costs
- Model calls
- cells × steps, or blocks × steps if batched (100 × 10 = 1,000)
- Latency
- high
- Complexity
- medium
3How does one step of the grid work?
A setup stage builds the grid and the rule. Then a loop: every cell reads its neighbours from the current grid and proposes its next state, a plain function writes all new states at once, and a rule decides whether to run another step. An observer finally describes the pattern.
- Step 1 of 5
Scenario becomes grid and rule
The builder turns "how would a referral programme spread across our 100 partner shops?" into a 10 by 10 grid of states, such as unaware, aware or joined, and a rule of two or three sentences. A given grid is used as is.
- Step 2 of 5
Every cell looks around
Each cell reads its own state and the states of its eight neighbours from the current step, and nothing else. It applies the rule and proposes its next state with a one-line reason.
- Step 3 of 5
Everyone moves at once
Plain code collects all proposals and writes them in one go. No cell ever sees a neighbour's new state in the same step, so the order in which cells were asked does not change the result.
- Step 4 of 5
Another step, or stop
The gate counts steps and checks for change. If cells changed and steps remain, the cells run again on the new grid. A grid that stopped changing, or the step limit, ends the run.
- Step 5 of 5
Name what emerged
The observer reads every snapshot and reports what happened: how many cells were in each state per step, where clusters formed, where spread stopped. It describes; it does not change the grid.
What each part does
- Scenario
- An initial grid and a rule, or a scenario in plain language to turn into them.
- Grid builder
- Turns the scenario into a grid of cell states and a short rule. Passes a given grid through.
- Cells
- Each cell reads its own state and its neighbours' states, applies the rule and proposes its next state.
- Grid
- The current state of every cell, plus one snapshot per completed step.
- Synchronous update
- Plain code. Waits for every cell, then writes all new states at once as the next step.
- Steps left?
- Counts steps and checks whether the grid changed in the last step.
- Observer
- Reads the step history and describes the pattern that emerged, with numbers per step.
- Final world
- The final grid, the per-step history and the observed pattern.
- Grid builder → Grid: initial grid
- Grid builder → Cells: the rule
- Grid → Cells: own state and neighbours
- Cells → Synchronous update: proposed next states
- Synchronous update → Grid: next step, all at once
- Steps left? → Cells: grid changed and steps left
- Steps left? → Observer: stable or step limit reached
- Grid → Observer: step history
Where it connects
Either an initial grid of cell states with a plain-language rule, or a scenario description from which the stage builds both.
When: The grid stopped changing, or the step limit is reached.
The final grid, one snapshot per step, the count of cells in each state per step, the rule used and a short description of the observed pattern.
The grid at the current step and every earlier snapshot. Cells read only their neighbourhood from the last completed step. Only the update function writes.
4What do I ask my assistant to set up?
The agents to launch
Grid builder
Turn the scenario into a grid no larger than 12 by 12, a short list of possible cell states and a rule of at most three sentences that a cell can apply using only its own state and its neighbours'. State your assumptions.
Sees: The scenario, or the given grid and rule to check and pass through.
Cell, one per cell, or one per block of cells with each cell judged separately
You are one cell. Apply the rule to your own state and your neighbours' states and return your next state with a one-line reason. Use nothing else. If you decide a block, decide each cell only from its own neighbours.
Sees: The rule, its own state and its neighbours' states from the last completed step. Never the rest of the grid, the history or the goal of the simulation.
Observer
Read the step history. Report the count of cells in each state per step, where clusters or fronts formed, and when change stopped. Describe only what the snapshots show; flag anything that looks caused by the rule's wording.
Sees: The rule, the scenario and every grid snapshot.
A prompt you can paste
Works with any assistant that can launch sub-agents. It contains the agents, the procedure and the stop rule above.
You are the orchestrator of a multi-agent workflow that follows the "Cellular Automata" architecture. Launch every agent listed below as a separate sub-agent with its own context. Give each agent only the context stated for it. Do not do an agent's work yourself. If you cannot launch sub-agents, play each agent in a clearly separated turn and never let it use what is withheld from it. # Task [Describe your task here] # Cellular Automata Many small agents follow a local rule and a global pattern appears. Input: the task above. It must provide: Either an initial grid of cell states with a plain-language rule, or a scenario description from which the stage builds both. If something essential is missing, ask for it before starting. Agents to launch: - Grid builder: Turn the scenario into a grid no larger than 12 by 12, a short list of possible cell states and a rule of at most three sentences that a cell can apply using only its own state and its neighbours'. State your assumptions. Context for this agent: The scenario, or the given grid and rule to check and pass through. - Cell (one per cell, or one per block of cells with each cell judged separately): You are one cell. Apply the rule to your own state and your neighbours' states and return your next state with a one-line reason. Use nothing else. If you decide a block, decide each cell only from its own neighbours. Context for this agent: The rule, its own state and its neighbours' states from the last completed step. Never the rest of the grid, the history or the goal of the simulation. - Observer: Read the step history. Report the count of cells in each state per step, where clusters or fronts formed, and when change stopped. Describe only what the snapshots show; flag anything that looks caused by the rule's wording. Context for this agent: The rule, the scenario and every grid snapshot. Procedure: 1. Launch the builder on the scenario. If the input already holds a grid and a rule, have it only check that the rule uses neighbours alone. 2. Store the grid as step 0. Use the eight surrounding cells as neighbours, and treat the edges as having fewer neighbours. 3. Run a step: give every cell, or every block, the rule and its neighbourhood from the last step. Collect all proposals before writing anything. 4. Write all new states at once as the next snapshot. Turn any proposal that is not a valid state into the cell's current state, and note it. 5. If at least one cell changed and fewer than 20 steps were run, run the next step. Otherwise launch the observer on the history. Stop rule: Stop when no cell changes in a step, or after 20 steps, whichever comes first. Exit: - `final`, when: The grid stopped changing, or the step limit is reached. Deliver: The final grid, one snapshot per step, the count of cells in each state per step, the rule used and a short description of the observed pattern. # Final deliverable The final grid, a table of cell counts per state per step, the rule and assumptions used, and the observer's description of the pattern, with a note that this is a scenario, not a forecast.
The same thing in code
import asyncio
from typing import TypedDict, cast
from langchain.chat_models import init_chat_model
from langgraph.graph import END, START, StateGraph
from pydantic import BaseModel
MAX_STEPS = 20
model = init_chat_model("anthropic:claude-sonnet-5-5")
Grid = list[list[str]]
class World(BaseModel):
states: list[str]
rule: str
grid: Grid
class Move(BaseModel):
next_state: str
reason: str
class Input(TypedDict):
scenario: str
class State(TypedDict):
scenario: str
rule: str
states: list[str]
history: list[Grid] # the grid store: one snapshot per completed step
changed: bool
report: str
def neighbours(grid: Grid, r: int, c: int) -> list[str]:
return [grid[i][j] for i in range(r - 1, r + 2) for j in range(c - 1, c + 2)
if (i, j) != (r, c) and 0 <= i < len(grid) and 0 <= j < len(grid[0])]
async def builder(state: State) -> dict:
w = cast(World, await model.with_structured_output(World).ainvoke(
"Turn the scenario into a grid of at most 12x12, a short list of cell states and a "
"rule of at most three sentences that uses only a cell's own state and its "
f"neighbours'. State your assumptions in the rule.\n\nScenario: {state['scenario']}"))
return {"rule": w.rule, "states": w.states, "history": [w.grid], "changed": True}
async def cell(rule: str, own: str, around: list[str]) -> Move:
# a cell sees the rule and its neighbourhood only, never the grid or the goal
return cast(Move, await model.with_structured_output(Move).ainvoke(
f"You are one cell. Rule: {rule}\nYour state: {own}\nNeighbours: {around}\n"
"Apply the rule and return your next state with a one-line reason. Use nothing else."))
async def step(state: State) -> dict:
grid = state["history"][-1]
coords = [(r, c) for r in range(len(grid)) for c in range(len(grid[0]))]
moves = await asyncio.gather(*(cell(state["rule"], grid[r][c], neighbours(grid, r, c))
for r, c in coords))
# synchronous update: every proposal is collected before the next grid is written
nxt = [row[:] for row in grid]
for (r, c), m in zip(coords, moves):
nxt[r][c] = m.next_state if m.next_state in state["states"] else grid[r][c]
return {"history": state["history"] + [nxt], "changed": nxt != grid}
def steps_left(state: State) -> str:
# the gate: stop when nothing changed or after 20 steps
return "step" if state["changed"] and len(state["history"]) - 1 < MAX_STEPS else "observer"
async def observer(state: State) -> dict:
msg = await model.ainvoke(
"Read the step history. Report the count of cells in each state per step, where "
"clusters or fronts formed and when change stopped. Describe only what the snapshots "
"show; flag anything that looks caused by the rule's wording.\n"
f"Scenario: {state['scenario']}\nRule: {state['rule']}\nSnapshots: {state['history']}")
return {"report": msg.text}
graph = StateGraph(State, input_schema=Input)
graph.add_node("builder", builder)
graph.add_node("step", step)
graph.add_node("observer", observer)
graph.add_edge(START, "builder")
graph.add_edge("builder", "step")
graph.add_conditional_edges("step", steps_left, ["step", "observer"])
graph.add_edge("observer", END)
app = graph.compile()
async def run(task: str):
return await app.ainvoke({"scenario": task}, {"recursion_limit": MAX_STEPS + 10})
One call per cell per step reaches 2,880 calls on a 12 by 12 grid over 20 steps; batch cells into blocks and code any exact part of the rule before real use.
import json
from typing import Any
from claude_agent_sdk import AgentDefinition, ClaudeAgentOptions, ResultMessage, query
MAX_STEPS = 20
AGENTS = {
"builder": AgentDefinition(
description="Turns a scenario into a grid, cell states and a local rule.",
prompt="Turn the scenario into a grid of at most 12x12, a short list of cell states and a "
"rule of at most three sentences using only a cell's own state and its neighbours'. "
"State your assumptions."),
"cell": AgentDefinition(
description="Decides the next state of a block of cells from their neighbourhoods.",
prompt="You decide a block of cells. For each entry, apply the rule to that cell's own "
"state and its neighbours' states only, and return its next state with a "
"one-line reason. Use nothing else."),
"observer": AgentDefinition(
description="Describes the pattern that emerged across grid snapshots.",
prompt="Read the step history. Report the count of cells in each state per step, where "
"clusters or fronts formed and when change stopped. Describe only what the "
"snapshots show; flag effects that look caused by the rule's wording."),
}
async def ask(prompt: str, schema: dict[str, Any] | None = None) -> ResultMessage:
options = ClaudeAgentOptions(
agents=AGENTS, allowed_tools=["Agent"],
output_format={"type": "json_schema", "schema": schema} if schema else None)
async for msg in query(prompt=prompt, options=options):
if isinstance(msg, ResultMessage):
return msg
raise RuntimeError("no result")
def neighbours(grid: list[list[str]], r: int, c: int) -> list[str]:
return [grid[i][j] for i in range(r - 1, r + 2) for j in range(c - 1, c + 2)
if (i, j) != (r, c) and 0 <= i < len(grid) and 0 <= j < len(grid[0])]
WORLD = {"type": "object", "required": ["states", "rule", "grid"], "properties": {
"states": {"type": "array", "items": {"type": "string"}}, "rule": {"type": "string"},
"grid": {"type": "array", "items": {"type": "array", "items": {"type": "string"}}}}}
ROWS = {"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array",
"items": {"type": "array", "items": {"type": "string"}}}}}
async def run(task: str):
world = (await ask(f"Use the builder agent on this scenario: {task}", WORLD)).structured_output
rule, states, history = world["rule"], world["states"], [world["grid"]]
for _ in range(MAX_STEPS): # the gate: at most 20 steps
grid = history[-1]
blocks = [[{"own": cell, "neighbours": neighbours(grid, r, c)} for c, cell in enumerate(row)]
for r, row in enumerate(grid)]
# one cell sub-agent per row block, each given only its own neighbourhoods
res = await ask(
f"Rule: {rule}\nFor each block below, launch a separate cell agent with the rule and "
"that block only, then return every block's next states in order.\n"
+ "\n".join(f"Block {i}: {json.dumps(b)}" for i, b in enumerate(blocks)), ROWS)
proposed = res.structured_output["rows"]
# synchronous update: invalid proposals keep the current state
nxt = [[p if p in states else grid[r][c] for c, p in enumerate(row)]
for r, row in enumerate(proposed)]
history.append(nxt)
if nxt == grid:
break
report = await ask(f"Use the observer agent.\nScenario: {task}\nRule: {rule}\n"
f"Snapshots: {json.dumps(history)}")
return {"final": history[-1], "history": history, "rule": rule, "pattern": report.result}
The orchestrator sees every block to dispatch it; if the rule is exact, compute the step in Python and keep sub-agents for judgement calls only.
import asyncio
from agents import Agent, Runner
from pydantic import BaseModel
MAX_STEPS = 20
Grid = list[list[str]]
class World(BaseModel):
states: list[str]
rule: str
grid: Grid
class Move(BaseModel):
next_state: str
reason: str
builder = Agent(
name="Grid builder", output_type=World,
instructions="Turn the scenario into a grid of at most 12x12, a short list of cell states and "
"a rule of at most three sentences that a cell can apply using only its own "
"state and its neighbours'. State your assumptions.")
cell = Agent(
name="Cell", output_type=Move,
instructions="You are one cell. Apply the rule to your own state and your neighbours' states "
"and return your next state with a one-line reason. Use nothing else.")
observer = Agent(
name="Observer",
instructions="Read the step history. Report the count of cells in each state per step, where "
"clusters or fronts formed and when change stopped. Describe only what the "
"snapshots show; flag anything that looks caused by the rule's wording.")
def neighbours(grid: Grid, r: int, c: int) -> list[str]:
return [grid[i][j] for i in range(r - 1, r + 2) for j in range(c - 1, c + 2)
if (i, j) != (r, c) and 0 <= i < len(grid) and 0 <= j < len(grid[0])]
async def decide(rule: str, own: str, around: list[str]) -> str:
# the cell's whole context: the rule and its neighbourhood from the last step
res = await Runner.run(cell, f"Rule: {rule}\nYour state: {own}\nNeighbours: {around}")
return res.final_output_as(Move).next_state
async def run(task: str):
world = (await Runner.run(builder, task)).final_output_as(World)
history: list[Grid] = [world.grid] # the grid store
for _ in range(MAX_STEPS): # the gate: at most 20 steps
grid = history[-1]
coords = [(r, c) for r in range(len(grid)) for c in range(len(grid[0]))]
proposals = await asyncio.gather(
*(decide(world.rule, grid[r][c], neighbours(grid, r, c)) for r, c in coords))
# synchronous update: write all new states at once, invalid ones keep the old state
nxt = [row[:] for row in grid]
for (r, c), p in zip(coords, proposals):
nxt[r][c] = p if p in world.states else grid[r][c]
history.append(nxt)
if nxt == grid:
break
report = await Runner.run(
observer, f"Scenario: {task}\nRule: {world.rule}\nSnapshots: {history}")
return {"final": history[-1], "history": history, "rule": world.rule,
"pattern": report.final_output}
One call per cell per step reaches 2,880 calls on a 12 by 12 grid over 20 steps; batch cells into blocks and code any exact part of the rule before real use.
import { generateText, Output } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
import { z } from 'zod';
const model = anthropic('claude-sonnet-5-5');
const MAX_STEPS = 20;
type Grid = string[][];
const World = z.object({
states: z.array(z.string()),
rule: z.string(),
grid: z.array(z.array(z.string())),
});
const Move = z.object({ nextState: z.string(), reason: z.string() });
function neighbours(grid: Grid, r: number, c: number): string[] {
const out: string[] = [];
for (let i = r - 1; i <= r + 1; i++)
for (let j = c - 1; j <= c + 1; j++)
if ((i !== r || j !== c) && grid[i]?.[j] !== undefined) out.push(grid[i][j]);
return out;
}
async function cell(rule: string, own: string, around: string[]) {
// a cell sees the rule and its neighbourhood only
const { output } = await generateText({
model,
instructions:
'You are one cell. Apply the rule to your own state and your neighbours\' states and ' +
'return your next state with a one-line reason. Use nothing else.',
prompt: `Rule: ${rule}\nYour state: ${own}\nNeighbours: ${around.join(', ')}`,
output: Output.object({ schema: Move }),
});
return output.nextState;
}
export async function run(task: string) {
const { output: world } = await generateText({
model,
instructions:
'Turn the scenario into a grid of at most 12x12, a short list of cell states and a rule ' +
'of at most three sentences that uses only a cell\'s own state and its neighbours\'. ' +
'State your assumptions.',
prompt: task,
output: Output.object({ schema: World }),
});
const history: Grid[] = [world.grid]; // the grid store
for (let step = 0; step < MAX_STEPS; step++) { // the gate: at most 20 steps
const grid = history[history.length - 1];
const next = await Promise.all(
grid.map((row, r) => Promise.all(row.map((own, c) => cell(world.rule, own, neighbours(grid, r, c))))),
);
// synchronous update: all proposals are in before the snapshot is written
const committed = next.map((row, r) => row.map((p, c) => (world.states.includes(p) ? p : grid[r][c])));
history.push(committed);
if (JSON.stringify(committed) === JSON.stringify(grid)) break;
}
const { text: pattern } = await generateText({
model,
instructions:
'Read the step history. Report the count of cells in each state per step, where clusters ' +
'or fronts formed and when change stopped. Describe only what the snapshots show; flag ' +
'anything that looks caused by the rule\'s wording.',
prompt: `Scenario: ${task}\nRule: ${world.rule}\nSnapshots: ${JSON.stringify(history)}`,
});
return { final: history[history.length - 1], history, rule: world.rule, pattern };
}
One call per cell per step reaches 2,880 calls on a 12 by 12 grid over 20 steps; batch cells into blocks and code any exact part of the rule before real use.
Snippets are generated when the site is built and type-checked against the SDK versions listed in the repository. Treat them as a starting skeleton.
What goes wrong
- Writing states as soon as each cell decides makes the outcome depend on call order. Collect first, then write all at once.
- A cell that sees the whole grid or the simulation's goal stops acting locally. Give it its neighbourhood only.
- A vague rule makes cells disagree on the same situation, which looks like an emergent effect. Test the rule on a few cells first.
- Results depend heavily on the starting grid. Run two or three starting layouts before drawing a conclusion.
Chain it
This architecture stands alone: the compatibility matrix allows no link into or out of it.