langgoap.GoapGraph

langgoap.GoapGraph#

class GoapGraph(actions, *, strategy=None, tracer=None, history=None, sensors=None, guards=None, resolvers=None, record_expansions=False, transition_model=None, rng=None, stuck_handlers=None, max_stuck_iterations=3, termination_policies=None, executor='sequential', history_state='full', goal=None, effects='declared', always_observe=(), max_actions=None, checkpointer=None, on_stop=None)[source]#

Builder that produces a compiled LangGraph for GOAP execution.

Supports two usage styles:

Explicit compile + invoke (for power users who need the compiled graph):

graph = GoapGraph(actions=[action1, action2, ...])
compiled = graph.compile(checkpointer=saver)
result = compiled.invoke({
    "goal": GoalSpec(conditions={"done": True}),
    "world_state": {"a": True},
})

Convenience invoke (single-shot, no persistence):

graph = GoapGraph(actions=[action1, action2, ...])
result = graph.invoke(
    goal=GoalSpec(conditions={"done": True}),
    world_state={"a": True},
)

Custom planning strategy:

from langgoap.planner.strategy import LazyDecompositionStrategy
graph = GoapGraph(
    actions=[action1, action2, ...],
    strategy=LazyDecompositionStrategy(lookahead=2),
)
result = graph.invoke(goal=goal, world_state={})

The graph structure is:

START → planner → executor → observer ──→ END
          ↑                     │
          └─────────────────────┘
Parameters:
  • actions (list[ActionSpec]) – The action library available to the planner and executor.

  • strategy (PlanningStrategy | None) – Optional PlanningStrategy. Defaults to the A* strategy wired inside GoapPlanner.

  • tracer (PlanningTracer | None) – Optional PlanningTracer for planning/execution observability.

  • history (StoreExecutionHistory | None) – Optional StoreExecutionHistory for persisting execution traces.

  • sensors (Sequence[Sensor | AsyncSensor | Callable[[dict[str, Any]], dict[str, Any]]] | None) – Optional list of Sensor / AsyncSensor run before every planning round, the first included. A plain function (world_state) -> updates is accepted and named after itself.

  • guards (list[ActionGuard | AsyncActionGuard] | None) – Optional list of ActionGuard / AsyncActionGuard evaluated before each action executes.

  • resolvers (list[ConditionResolver | AsyncConditionResolver] | None) – Optional list of dynamic condition resolvers applied to precondition evaluation.

  • record_expansions (bool) – Forwarded to GoapPlanner; enables node expansion trace recording for post-hoc analysis.

  • transition_model (TransitionModel | None) – Optional TransitionModel threaded into GoapExecutor. When provided, actions with no execute callable (or those returning None) have their runtime effects drawn from transition_model.sample. Use the same model you passed to MCTSStrategy so plan-time and runtime share one noise distribution.

  • rng (random.Random | None) – Optional random.Random forwarded to the executor for reproducible sampling; retry back-off jitter never draws from it.

  • executor (Literal['sequential', 'parallel']) – "sequential" (default) runs one plan step per executor node invocation with GoapExecutor; "parallel" wires ParallelGoapExecutor, which runs every independent action of the next wave in one invocation (actions requiring human approval always run alone).

  • history_state (Literal['full', 'delta', 'planning']) – What each ActionResult in execution_history keeps of the world state. "full" (default) stores complete before/after snapshots; "delta" stores only the keys an action changed, with their prior values; "planning" stores only the keys preconditions, effects and the goal read. Use a compact mode when the world state carries large non-planning data (documents, LLM output), so checkpoints stop growing with every step (issue #74). Realised costs are recorded per action and do not depend on the snapshots.

  • goal (GoalSpec | MultiGoal | Mapping[str, Any] | None) – Default goal for start(), invoke() and ainvoke(): a GoalSpec, a MultiGoal, or a plain mapping of conditions.

  • effects (Literal['declared', 'merged', 'observed']) – Who says what an action did. "declared" (default) believes a returned dict, which must then set every declared effect key, else the declared effects. "merged" applies the declared effects and merges a returned dict on top, so an action returns only what it adds or what differs (issue #97). "observed" does the same, then asks the sensors and lets what they report for the action’s keys win, so actions need not re-read and return their own facts. Requires sensors.

  • always_observe (Iterable[str]) – State keys read from the sensors after every action and watched by every wait, besides each action’s effect keys and ActionSpec.observe.

  • max_actions (int | None) – Shorthand for termination_policies=[MaxActionsPolicy(max_actions)].

  • checkpointer (Checkpointer | None) – Checkpointer for the thread API (start(), notify(), resume(), waiting()). Defaults to an in-memory saver. compile() keeps taking its own.

  • on_stop (Callable[[str, GoapResult], Any] | None) – (thread_id, state) -> None called whenever a run made through the thread API stops: at the goal, at a wait, at a question for a person, or on failure.

  • stuck_handlers (list[StuckHandler] | None)

  • max_stuck_iterations (int)

  • termination_policies (list[TerminationPolicy] | None)

Threads (issue #96). With a goal the graph object runs threads itself; runs are serialised, so a call made while another run is in progress (an action that publishes an event) is delivered after it:

graph = GoapGraph(actions, goal={"delivered": True}, sensors=[read_platform])
graph.start({"order_id": "o-1"}, thread_id="o-1")
graph.notify("o-1", event)          # wakes a wait; never answers a question
graph.resume(True, thread_id="o-1") # answers a question; never ends a wait
graph.waiting("o-1")                # the interrupt payload, or None

astart, anotify, aresume and awaiting are the async forms. The calls may come from several OS threads; runs are still serialised.

__init__(actions, *, strategy=None, tracer=None, history=None, sensors=None, guards=None, resolvers=None, record_expansions=False, transition_model=None, rng=None, stuck_handlers=None, max_stuck_iterations=3, termination_policies=None, executor='sequential', history_state='full', goal=None, effects='declared', always_observe=(), max_actions=None, checkpointer=None, on_stop=None)[source]#
Parameters:
Return type:

None

Methods

__init__(actions, *[, strategy, tracer, ...])

ainvoke([goal, world_state, config])

Async convenience method: compile and invoke the graph.

ainvoke_nl(request[, world_state, config, ...])

Async variant of invoke_nl().

anotify(thread_id[, event])

Async notify().

aresume(value, *, thread_id)

Async resume().

astart([world_state, goal])

Async start().

awaiting(thread_id)

Async waiting(), for checkpointers that are async-only.

compile([checkpointer, store, ...])

Build and compile the GOAP StateGraph.

initial_state(goal[, world_state])

Build the JSON-native input for a compiled graph.

invoke([goal, world_state, config])

Convenience method: compile and invoke the graph in one call.

invoke_nl(request[, world_state, config, ...])

Interpret a natural language request and execute the GOAP loop.

notify(thread_id[, event])

Something happened: a thread paused in a wait looks again.

rehydrate(state)

Return state with typed goal, plan and execution_history.

resume(value, *, thread_id)

Answer the question the thread is paused on (an approval, a form).

start([world_state, goal])

Plan and run a thread until the goal, a wait, a question or a failure.

waiting(thread_id)

What the thread is paused on: its interrupt payload, or None.

waiting_action(thread_id)

The action name the thread is paused on if it is a wait, else None.

Attributes

compiled

The graph compiled once with this object's checkpointer.