Stochastic domains with TransitionModel and StrategyRouter#

Classical GOAP assumes the world responds exactly the way an action’s declared effects say it will. That assumption breaks as soon as dynamics are noisy: API jitter, slippery tiles, tool outputs that are non-deterministic, learned models returning distributions.

LangGOAP models this with two opt-in APIs:

  • TransitionModel — user-supplied dynamics. expected(state, action) feeds A* / CSP / MCTS tree expansion; sample(state, action, rng) feeds MCTS rollouts and the graph executor and is free to diverge from expected.

  • StrategyRouter — a rule-based dispatcher that reads cheap ProblemFeatures at plan time and picks the right PlanningStrategy.

Users on the deterministic path need not wire either. This notebook walks the opt-in path end-to-end on a tiny slippery gridworld.

A minimal slippery gridworld#

A 4×4 grid with start at (0, 0) and goal at (3, 3). The four cardinal moves have declared effects that move the agent one cell in the intended direction, clamped to the grid, flipping done=True on goal entry. Slip is layered on via a TransitionModel, so the declared effects stay clean.

from collections.abc import Mapping
from dataclasses import dataclass
from random import Random
from typing import Any

from langgoap import ActionSpec, DivergencePolicy, GoalSpec

ROWS, COLS = 4, 4
START, GOAL = (0, 0), (3, 3)
DELTAS = {"north": (-1, 0), "south": (1, 0), "east": (0, 1), "west": (0, -1)}
PERP = {"north": ("west", "east"), "south": ("west", "east"),
        "east": ("north", "south"), "west": ("north", "south")}

def _clamp(r: int, c: int) -> tuple[int, int]:
    return max(0, min(ROWS - 1, r)), max(0, min(COLS - 1, c))

def _effect_for(r: int, c: int) -> dict[str, Any]:
    r, c = _clamp(r, c)
    return {"row": r, "col": c, "done": (r, c) == GOAL}

def _make_move(name: str) -> ActionSpec:
    dr, dc = DELTAS[name]
    def eff(state: Mapping[str, Any]) -> Mapping[str, Any]:
        return _effect_for(int(state.get("row", 0)) + dr, int(state.get("col", 0)) + dc)
    return ActionSpec(name=name, preconditions={}, effects=eff,
                      effect_keys=frozenset({"row", "col", "done"}))

actions = [_make_move(n) for n in DELTAS]
goal = GoalSpec(conditions={"done": True})
start_state = {"row": START[0], "col": START[1], "done": False}
/Users/brian.sam-bodden/Code/langgoap/.venv/lib/python3.12/site-packages/langgraph/checkpoint/serde/encrypted.py:5: LangChainPendingDeprecationWarning: The default value of `allowed_objects` will change in a future version. Pass an explicit value (e.g., allowed_objects='messages' or allowed_objects='core') to suppress this warning.
  from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer

A slippery TransitionModel#

expected returns the action’s declared effects — A* sees the unperturbed grid, as it should. sample implements the Gymnasium-style slip: with probability slip_prob the agent moves perpendicular to the intended direction (chosen uniformly between left and right).

The divergence_policy is set to "risk-averse" to signal the router that a risk-aware planner is appropriate — this is the structured opt-in that flips the default routing decision.

@dataclass
class SlipperyModel:
    slip_prob: float = 0.2
    divergence_policy: DivergencePolicy | None = DivergencePolicy(
        reason="perpendicular-slip MDP; risk-averse planning preferred",
        kind="risk-averse",
    )
    def expected(self, state: Mapping[str, Any], action: ActionSpec) -> Mapping[str, Any]:
        return action.get_effects(dict(state))
    def sample(self, state: Mapping[str, Any], action: ActionSpec, rng: Random) -> Mapping[str, Any]:
        intended = action.name
        if rng.random() >= self.slip_prob:
            direction = intended
        else:
            left, right = PERP[intended]
            direction = left if rng.random() < 0.5 else right
        dr, dc = DELTAS[direction]
        return _effect_for(int(state.get("row", 0)) + dr, int(state.get("col", 0)) + dc)

model = SlipperyModel(slip_prob=0.2)

Routing with StrategyRouter#

The router reads ProblemFeatures and picks a strategy from the registered mapping. The default RuleBasedClassifier promotes MCTS when the transition model’s DivergencePolicy.kind == "risk-averse" — exactly the signal we just set.

from langgoap import (
    AStarStrategy, RuleBasedClassifier, StrategyRouter,
    extract_features,
)
from langgoap.planner.mcts import MCTSExploration, MCTSReuseConfig, MCTSStrategy
from langgoap.state import PlanningState

start = PlanningState.from_dict(start_state)
features = extract_features(start, goal, actions, transition_model=model)
print("is_stochastic =", features.is_stochastic)
print("risk_profile  =", features.risk_profile)
print("classifier -> ", RuleBasedClassifier()(features))
is_stochastic = True
risk_profile  = risk-averse
classifier ->  mcts
router = StrategyRouter(
    strategies={
        "astar": AStarStrategy(),
        "mcts": MCTSStrategy(
            exploration=MCTSExploration(
                iterations=256, rollout_depth=12, wall_clock_ms=500.0, seed=7,
            ),
            reuse=MCTSReuseConfig(anytime_fallback=True),
            transition_model=model,
        ),
    },
    classifier=RuleBasedClassifier(),
    transition_model=model,
)
plan = router.plan(start, goal, actions)
print([a.name for a in plan.actions])
['east', 'west', 'south', 'north']

Takeaways#

  • TransitionModel is the seam for stochastic dynamics; declared action effects stay clean, noise lives in sample.

  • DivergencePolicy(kind="risk-averse") is the structured opt-in that signals “route me to a risk-aware planner.”

  • StrategyRouter is additive — deterministic-path users never see it unless they wire it.

  • The same TransitionModel passed to GoapGraph(transition_model=...) is threaded into the executor, so action outcomes at runtime come from model.sample(...) whenever an action has no execute callable (or its callable returns None). Plan-time and runtime share one noise model.

A note on the plan above#

The printed plan is an MCTS anytime-fallback plan: under the small budget used here (iterations=256, wall_clock_ms=500), the tree often cannot reach the goal in one search, and anytime_fallback=True returns the most-visited root action as a one-step robust descent. In practice MCTS lives inside a replanning loop (see GoapGraph): it emits one robust action, the executor samples the environment, and the planner is invoked again on the new state. Raising iterations, rollout_depth, or the wall-clock budget reduces the reliance on the fallback at the cost of planning latency.

The gating of MCTS for generic is_stochastic=True is intentional: the benchmark in tests/benchmarks/stochastic_gridworld_bench.py (and the mcts_vs_astar_stochastic notebook) shows where MCTS pays off, and the gate will be lifted as that evidence grows.for the research roadmap that aims to lift it.