Core Concepts¶
State IS events¶
Append-only log of frozen, typed events. Handlers consume and emit events. Projections (EventLog.filter(), reducers) derive views. No mutable shared state.
The taxonomy¶
Four event base classes, a Namespace, and the Invariant marker:
| Class | Role | Naming | Where it lives |
|---|---|---|---|
Namespace |
Group of related commands/events | Noun (Order) |
Top-level |
Command |
Intent / request | Imperative (Place, Ship) |
Nested in Namespace |
DomainEvent |
Fact inside the domain | Past-participle (Placed) |
Nested in Namespace or Command |
IntegrationEvent |
Fact crossing a system boundary | Past-participle | Top-level only |
SystemEvent |
Library-emitted fact | Past-participle | Top-level. A Halted subclass can nest |
Invariant |
Named rule gating a handler | Noun phrase (CustomerNotBanned) |
Anywhere. Nesting under Command is recommended |
Invariant is a marker class, not an Event subclass. See control-flow.
Command and DomainEvent must nest inside a Namespace. IntegrationEvent must be top-level. Direct Event subclassing is forbidden. All three raise TypeError at class creation.
from langgraph_events import Command, DomainEvent, Namespace
class Order(Namespace):
class Place(Command):
customer_id: str
class Placed(DomainEvent):
order_id: str
class Rejected(DomainEvent):
reason: str
class Shipped(DomainEvent):
tracking: str
Nesting is syntactic only. Order.Place.Placed is a DomainEvent with a __command__ back-reference, not a subclass of Place.
A declared command is a leaf of the class hierarchy. class Rush(Order.Place) raises TypeError. One Command is one intent, with its own handler, outcomes and node identity. Share common code through a helper function, not a base class. Subclassing a Namespace raises TypeError too. See Reducers. Refining an event, class FastPlaced(Order.Place.Placed), and subclassing Interrupted, IntegrationEvent or Halted keep working.
Command.Outcomes¶
Auto-generated union of the command's nested DomainEvent classes. Use it in isinstance and as the inline-handler return contract. When mypy must see it, declare an Outcomes: TypeAlias = … yourself. The library checks it against the nested events at class creation.
...
isinstance(evt, Order.Place.Outcomes) # Placed OR Rejected
typing.get_args(Order.Place.Outcomes) # (Placed, Rejected)
Handlers¶
Two styles: inline on a Command, or external via @on.
Inline¶
Name the method after the verb (place, ship, …) or use handle. self is the command instance. Pass the class to EventGraph. No decorator is needed.
from __future__ import annotations
from langgraph_events import Command, DomainEvent, EventGraph, Namespace
class Order(Namespace):
class Ship(Command):
order_id: str
class Shipped(DomainEvent):
tracking: str
def ship(self) -> Order.Ship.Shipped:
return Order.Ship.Shipped(tracking=f"track-{self.order_id}")
graph = EventGraph([Order.Ship])
# or register every inline handler on a namespace in one call:
graph = EventGraph.from_namespaces(Order)
- Exactly one public method per
Command. A helper must be underscore-prefixed, or class creation raisesTypeError. - Annotated return types must cover every nested
DomainEvent. - Write the qualified name in the return annotation (
Order.Ship.Shipped), not the bare nested name (Shipped). Underfrom __future__ import annotationsthe annotation is a string resolved against module globals only, so a bare nested name does not resolve. See Return contract. - Each member of the return annotation must be an
Eventsubclass,Scatter[...]orNone. Any other class, an event mixin too, raisesTypeErrorat graph construction. For a mixin, name theEventclasses that compose it. DomainEvents nested inside aCommandare Command-private. Only that Command's handler can emit them. A recovery handler emits a namespace-level sibling, for exampleOrder.Rejected. A violation raisesCommandPrivacyErrorat graph construction.
External: @on¶
Three shorthand forms:
...
# Bare: event type inferred from the annotation
@on
def notify(event: Order.Placed) -> None:
log_to_audit(event)
# Modifiers only: event type inferred, modifiers applied
@on(raises=NotifyError)
def push_notification(event: Order.Placed) -> None: ...
# Explicit types: required for multi-event subscription
@on(UserMessage, ToolResults)
async def call_llm(event: Event) -> AssistantMessage: ...
Bare @on requires a single annotated Event parameter. Otherwise it raises at decoration.
@on(Event) subscribes a handler to every dispatched event. That includes library events such as Resumed, HandlerRaised and HandlerRetried. An Interrupted event reaches it when the thread resumes. A Halted event never reaches it, because a Halted event ends the run before any handler matches. @on(Event) does not hide an OrphanedEventWarning.
Signature injection¶
Handler params resolve from:
log: EventLog: full historyconfig: RunnableConfig/store: BaseStore: LangGraph injections- A parameter annotated with the graph's
context_schema: the typed run context (see Run context) - Reducer channel or
Derivedvalue by parameter name (see Reducers) - Field matchers (external only): typed subset dispatch and injection
- Services: project dependencies, the typed fields of the
EventGraph(services=...)object
A handler parameter after the event, and each parameter of a RunScoped factory, bind by one rule:
| Order | Parameter | Value |
|---|---|---|
| 1 | annotated exactly RunnableConfig, the context_schema type, BaseStore, EventLog or Reflection |
that input. The parameter name does not matter |
| 2 | named like a stored reducer or a Derived |
its value at node start |
| 3 | named like a field of the services= object |
that service. A RunScoped service gives its result for the same node call |
The first match is used. So an exact library annotation wins over a reducer of the same name. The name log has no special meaning: a parameter reads the EventLog only when its annotation is EventLog. These rules apply to a handler parameter, a factory parameter and a Derived parameter alike:
- Each parameter must have an annotation. A parameter with none raises
TypeErrorat graph construction. The event parameter of a handler, a field-matcher parameter and a*argsor**kwargscatcher are not inputs, so they need none. - Each annotation must resolve. An annotation that does not resolve raises
TypeError, also on the event parameter. A usual cause is an import underif TYPE_CHECKING:. Keep the import at run time with# noqa: TC002. - A parameter that matches nothing raises
TypeErrorat graph construction. A default does not prevent it. The message gives a hint for a parameter namedconfigorlog, and for a default. - A default is the value when the input is unset. A reducer or a
Derivedis unset when its value isNone. A run config, a store or a run context is unset when the run has none. A service is never unset. - The annotation names the declared type of its source exactly. A misfit raises
TypeErrorat graph construction. The rules are described below.
services= takes one object whose class declares one typed field per service, such as a dataclass instance. The field name is the parameter name that reads the service. The field type is the declared type of the service. A factory field is typed RunScoped[T], and its result has the type T:
...
from dataclasses import dataclass
@dataclass
class Services:
primary_chat: BaseChatModel
backup_chat: BaseChatModel
model: RunScoped[ConversationModel]
EventGraph(
handlers=[...],
services=Services(primary_chat=chat_a, backup_chat=chat_b, model=RunScoped(model_for)),
)
@on(SomeEvent)
def react(event: SomeEvent, primary_chat: BaseChatModel, model: ConversationModel) -> ...: ...
A dict, a list or a NamedTuple raises TypeError that names this fix. A ClassVar field is no service. A Final[T] field declares T. An InitVar field raises TypeError, because the object does not keep it. mypy checks each value against its field type when the object is built. A field annotation that does not resolve raises TypeError at graph construction.
Declared types and the exact match¶
Each source declares its type, and a reader annotates that type exactly:
| Source | Declared type |
|---|---|
Reducer[E, T] |
list[T] |
ScalarReducer[E, T] |
T, or T \| None when default is None |
FoldReducer[S, E] |
S |
Derived |
the return annotation of fn. A class gives itself |
A field of the services= object |
the field type |
A RunScoped[T] field |
T. The return annotation of the factory must be T too |
See Declared types for the reducer subscriptions. Two annotations name the same type when they are equal after this normalization rule table:
| Rule | Example |
|---|---|
A typing alias is its origin class. A typing alias and its collections.abc alias compare by origin. The rule applies to each type argument, a Callable argument list too |
List[int] is list[int]. typing.Sequence[int] is collections.abc.Sequence[int] |
| A bare alias is its origin class | List is list |
Optional[X] is X \| None |
Optional[int] is int \| None |
| A union is the set of its members, so the order does not count | int \| str is str \| int |
A union member that is a union, behind Annotated or an alias, is flattened |
Annotated[int \| str, "x"] \| None is int \| str \| None |
The Literal members of a union merge, and None in a Literal is None |
Literal["a"] \| Literal["b"] is Literal["a", "b"]. Literal[1, None] is Optional[Literal[1]] |
A Literal is the set of its values, keyed by type and value |
Literal[1] is not Literal[True] |
Annotated metadata is stripped, at any depth |
list[Annotated[int, "x"]] is list[int] |
Any equals only Any |
Any is not object |
A NewType is its own type |
UserId is not int |
A type alias is its value, also a typing_extensions.TypeAliasType |
type Ids = list[int] is list[int] |
| A subscripted alias with parameters is its value with the arguments in place | for type Items[T] = list[T], Items[int] is list[int] |
| The empty tuple is its own type | tuple[()] is not tuple |
| A type variable, a forward reference, a string or a bare alias with parameters names no class yet | refused with TypeError |
Nothing else fits: no subclass, no base class, no abstract container, no numeric tower. One allowance applies to a reducer and a Derived only: a reader can leave None out of an optional source, because an unset value raises ReducerNotSetError. A service is never unset, so a reader of a service matches it exactly.
For a narrow view of a value, declare a Protocol as the type of the provider, and name the same Protocol in each reader. When two readers need two views, add an adapter: a RunScoped factory that reads the service and returns the view. It returns the same object, once per node call:
...
def loader_view(initiative_loader: InitiativeLoader) -> LoaderView:
return initiative_loader
@dataclass
class Services:
initiative_loader: InitiativeLoader
loader_view: RunScoped[LoaderView]
A Derived gives a Sequence view of a list reducer the same way: def history_view(history: list[str]) -> Sequence[str]: return history.
Run-scoped services¶
A plain service is injected as the same object on every dispatch. For a value built per node call, wrap a factory in RunScoped, and give the services= object a field typed RunScoped[T] for it. The library calls the factory once per node call and injects the result under the field name.
...
from langgraph_events import EventLog, RunScoped
def model_for(config: RunnableConfig) -> ConversationModel:
return models.main(config)
def planner_for(model: ConversationModel, log: EventLog, stage: str) -> Planner:
return Planner(model, log, stage)
@dataclass
class Services:
model: RunScoped[ConversationModel]
planner: RunScoped[Planner]
session_factory: SessionFactory
EventGraph(
handlers=[...],
reducers=[stage],
services=Services(
model=RunScoped(model_for),
planner=RunScoped(planner_for),
session_factory=session_factory,
),
)
@on(SomeEvent)
async def handle(event: SomeEvent, planner: Planner) -> ...: ...
Each factory parameter binds by the rule of a handler parameter. See Signature injection. A factory cannot read the event. Read the event in the handler instead.
Rules:
- The factory must be a plain function, a class or a callable object, with a return annotation. A coroutine function, or a factory without a return annotation, raises
TypeErroratRunScoped(...). Afunctools.partialis read through to the wrapped function, and a keyword that it binds is filled already. A callable object is read through its__call__. - The return annotation must resolve at graph build, so declare its class at module level. It must be the
Tof theRunScoped[T]field exactly, or the build raisesTypeError. - A factory runs only for a handler or a factory that declares it. It runs once per node call, before the invariants of the handler. One result serves every event that the node handles in that call, every retry attempt, and each factory that reads it.
- The factory runs synchronously on both the
invokeand theainvokepath. Do not do I/O in it. A factory can return an object whose async methods do the I/O. - A resumed run receives a freshly built config, not a checkpointed one.
- The factory runs before the handler's
raises=boundary. An error in the factory is not caught byraises=, is not retried, and does not produceHandlerRaised. It surfaces as an unhandled node error. A note names the reader that requested the service whose factory raised. A factory whose input failed did not run, so it gets no note. Keep the factory to a lookup. Validate the config in the factory and raise a clear error. - A parameter that names a stored reducer or a
Derived, with an annotation that rejectsNoneand no default, raisesReducerNotSetErrorwhen the value isNone. The message names the factory. EventGraph.namespaces()lists eachRunScopedservice with its inputs, in.text(),.json()and.mermaid(). The text names an input by its parameter name, or by its kind for a framework input, for exampleconfig. The mermaid diagram draws a service as a subroutine node with its own style. A dottedreadsarrow comes from each input reducer,DerivedorRunScopedservice. The node label lists each other input. As for a reducer, no arrow joins a service to the handlers that read it.EventTopology.namespaces()has no services, so it lists none.
Graph construction raises TypeError in each of these cases. The message names the factory, the parameter and the fix.
| Case | Fix |
|---|---|
| A factory parameter matches nothing | Rename the parameter, register the input, or annotate it with the exact library type. The message names the other services |
A factory parameter is *args or **kwargs |
Give each input its own parameter |
A service has the name of a reducer or a Derived |
Rename the service or the reducer. A handler or a factory parameter cannot name both |
| The annotation of a factory parameter does not name the declared type of its input | Change the annotation to the type that the message names, or add an adapter |
The factory returns another type than its RunScoped[T] field |
Make the factory return T, or change the field type |
| Factories read each other in a cycle | Remove one read. The message names the cycle, for example first -> second -> first |
Python cannot read the signature of the factory, for example dict |
Pass a function, a class or a callable object whose signature Python can read |
Run context¶
A per-run server fact, such as the run language or a model override, does not belong in configurable. That dict can also carry client input, and LangGraph copies its plain values into the checkpoint metadata. Use LangGraph's typed run context instead. Declare its type with EventGraph(context_schema=...), and pass a value with context= on each run call:
...
from dataclasses import dataclass
@dataclass(frozen=True)
class RunFacts:
language: str
def model_for(facts: RunFacts) -> ConversationModel:
return models.main(facts.language)
@on(SomeEvent)
def handle(event: SomeEvent, facts: RunFacts, model: ConversationModel) -> ...: ...
@dataclass
class Services:
model: RunScoped[ConversationModel]
graph = EventGraph(
[handle],
context_schema=RunFacts,
services=Services(model=RunScoped(model_for)),
)
graph.invoke(SomeEvent(), context=RunFacts(language="fr"))
Rules:
- The schema can be a dataclass, a pydantic model or a
TypedDict. LangGraph coerces adictcontext to a dataclass or a pydantic model. context_schemabelongs to the topology:EventTopology(handlers, context_schema=RunFacts).EventGraph(handlers, context_schema=...)passes it on, andEventGraph.of(topology, ...)reads it from the topology.- A handler parameter whose annotation is exactly the schema type receives the context. It is claimed like
RunnableConfig, before a service, so it is not intopology.requirements. Only the exact type matches. A parameter annotatedRunFacts | Noneor with a subclass stays unclaimed, and theTypeErrorof the build says so. Withoutcontext_schema, the error of a dataclass, pydantic orTypedDictparameter namescontext_schema=. - A
RunScopedfactory parameter annotated exactly with the schema type receives the context, at any position:def model_for(config: RunnableConfig, facts: RunFacts). A parameter annotated with another type binds by its name. On a graph withoutcontext_schema, theTypeErrorof a parameter that names nothing says to passcontext_schema=when the annotation is a dataclass, a pydantic model or aTypedDict. AnEventsubclass gets no such hint, because a factory cannot read the event. - A factory receives the context typed as its annotation, but
EventGraphis not generic in the context type. A type checker cannot match the factory to the schema. - The context is read through LangGraph's
get_runtime(). It is not written to the checkpoint state or to the checkpoint metadata. - When
context_schemais set, every run call must passcontext=. This includes a resume andAGUIAdapter.stream(). A missing context, or a context of another type, raisesTypeErrorthat names the schema, before the graph runs. A stream method ofEventGraphraises it at the first iteration, because a generator runs no code before then. - Each run method takes
context=as a keyword. A keyword that LangGraph's run does not take, for example a typo such ascontxt=, raisesTypeError. EventStoreruns no handler, so it needs no context. Build its topology with the samecontext_schemaas the graph, or without it.- A resume does not reuse the context of the earlier run. Pass the context again.
Return contract¶
- Annotated handlers must return a type in the declared union, or
None. - Unannotated
Command-subscribing handlers must return one ofCommand.Outcomes, orNone. Other unannotated handlers keep a shape-only check. - Omitting the return annotation is legal. An annotation that fails to resolve raises
TypeErrorat graph construction. - Violations raise
TypeErrorat dispatch.
EventGraph¶
...
graph = EventGraph([place, respond], max_rounds=100)
Topology is derived from handler subscriptions. No manual node or edge wiring is needed. max_rounds (default 100) sets the recursion limit and emits MaxRoundsExceeded (a Halted subtype) on overflow. graph.compiled exposes the underlying CompiledStateGraph for direct state access.
Supported scope¶
One root EventGraph runs per thread. A nested run raises NotImplementedError. A nested run is graph.compiled used as a subgraph node, or a run started from a handler or a node of another running graph. A root run with a non-empty checkpoint_ns raises too. To start a second event stream, start it outside the run context, for example through a task queue or a fresh contextvars.Context. Do not start it from a handler.
Topology, graph and store¶
EventGraph has three parts. Each part is a class that you can build alone:
| Class | Holds | Needs | Use it to |
|---|---|---|---|
EventTopology |
the handlers, reducers and namespaces | no service, no checkpointer | render the graph, list handler names, feed the migration gate |
EventStore |
a topology and a checkpointer | no service | find, abandon, rewrite and verify stored threads |
EventGraph |
a topology, its services and a checkpointer | every service a handler asks for | run, resume and stream threads. graph.event_store is its store |
EventGraph(handlers, ...) is the shortcut for
EventGraph.of(EventTopology(handlers, reducers=...), ...). A client that never runs a handler
does not need the services. Build the topology once, and bind the services only where a handler
runs:
from langgraph_events import EventGraph, EventStore, EventTopology
topology = EventTopology([place, respond], reducers=[messages])
# or: EventTopology.from_namespaces(Order, handlers=[respond], reducers=[messages])
print(topology.namespaces().mermaid())
print(topology.requirements) # one ServiceRequirement per service parameter
graph = EventGraph.of(topology, services=Services(llm=llm), checkpointer=saver)
store = EventStore(topology, saver)
for config in store.threads_paused_on(ApprovalRequested, thread_ids=ids):
store.abandon(config, reason="retired")
topology.requirementslists each handler parameter that only a service can fill, asServiceRequirement(node, qualname, param, annotation).nodeis the graph-node name of the handler.qualnameis the module and qualified name of the handler function. The annotation is the resolved annotation of the parameter.EventTopology.from_namespaces(*namespaces, handlers=..., reducers=...)collects the same handlers asEventGraph.from_namespaces(...). A store-only client does not list every handler.- Read the static facts of a graph from
topology:handler_names,reducer_names,injectable_names,resumable_node_names,reducers,requirementsandnamespaces(). On a graph, usegraph.topology.handler_names. The same properties onEventGraphforward to the topology. EventGraph.of(topology, ...)takes the keyword arguments ofEventGraph(...)exceptreducers. A requirement that no service matches raisesTypeError. The error names the missing type and the fields thatservices=holds, so a near-miss name shows.EventGraph(handlers, ...)builds the same graph asEventGraph.of(EventTopology(handlers, reducers=...), ...). It checkson_unresumable, thenservices=, then builds the topology.graph.event_storeisEventStore(graph.topology, checkpointer). A settle runs no handler, so the store needs no service. A graph with no checkpointer has no store, andgraph.event_storeraisesValueError.EventStoredoes not change the serde of the saver. A rewrite needs aNamespaceAwareSerde, so setsaver.serde = topology.serde()before you build the store.topology.serde()is the serde thatfrom_namespaces(..., checkpointer=...)wires. WARNING: every process that reads the saver must use the same serde. A process with LangGraph's default serde reads an event that aNamespaceAwareSerdewrote asNone. See Event migrations.
Retired events¶
A retired event is an event class that no handler returns any more. A stored thread can still
hold it, for example a thread paused on an Interrupted subclass whose handler is deleted.
The topology derives the serde from its handlers, so it does not see such a class. The class
still revives by import, but the serde does not collect its @migrate_from and @backfill.
Pass the class in retired=, and topology.serde() reads it:
topology = EventTopology([place, respond], retired=[ApprovalRequested])
saver.serde = topology.serde()
store = EventStore(topology, saver)
topology.retired_eventsreturns each class ofretired=once, in the order given.EventTopology.from_namespaces(...),EventGraph(...)andEventGraph.from_namespaces(...)takeretired=and pass it to the topology.from_namespaces(..., checkpointer=...)wires a serde that reads the retired events.- The migration gate records a retired event as a live
class in
events, because the class still imports. Itsreviverule keeps checking it. Theretiredlist of the baseline file is a different list. It holds each identity whose class is deleted. When you delete the class,baseline updatemoves its identity to that list. - An entry that is not an
Eventsubclass raisesTypeError. An abstract event class, for exampleIntegrationEvent, raisesTypeError. An entry that a handler returns raisesValueError. A handler can still subscribe to a retired event.
Namespace introspection & visualization¶
topology.namespaces()returns aNamespaceModel: code-derived structure and choreography. A renderer needs no services: build anEventTopologyand callnamespaces()on it.graph.namespaces()returns the same model.- Render:
.text()(tree),.text(view="structure")(taxonomy only),.mermaid()(flowchart),.json()/.to_dict(). - Inspect (all frozen dataclass tuples/dicts):
.namespaces:dict[str, NamespaceModel.Namespace].command_handlers,.policies,.edges,.seeds,.integration_events,.system_events
Edgecarrieskind(how:solid/scatter/raises/retry/framework) andcausation(causal role:intent/react/orchestrate/chain). Both surface intext(),json()and mermaid styling.
Rendered diagrams live on the Patterns page. The collapsible legend shows the shape and edge vocabulary.
Focused diagrams¶
mermaid(focus=...) draws the selected items, the edges that touch them, and the nodes at both
ends, dimmed as context. notes writes runtime facts on nodes and on a handler's edges, and
muted fades what the client does not use. A count of how often a handler wrote events comes
from the recorded causes:
...
from collections import Counter
from langgraph_events import Cause, NamespaceModel
model = graph.namespaces()
print(list(model.namespaces), [r.name for r in model.reactions]) # valid names
log = graph.invoke(Order.Place(customer_id="c1"))
emitted = Counter(c.via for e in log if isinstance(c := log.cause(e), Cause))
print(
model.mermaid(
focus=NamespaceModel.Focus(namespaces="Order", reactions="notify_customer"),
notes={via: f"emitted {n}x" for via, n in emitted.items()},
show_raises=False,
)
)
Every Cause.via is a valid note key: an @on handler by its name in model.reactions, an
inline command handler by its command qualname. A note on an @on handler goes under the label
of each of its edges. A handler that returns None writes no event, so the count means
"emitted", not "dispatched".
EventLog¶
Immutable, ordered container returned by invoke / ainvoke. Inject by type hint.
| Method | Returns |
|---|---|
log.filter(T) |
list[T] |
log.latest(T) / log.first(T) |
T \| None |
log.latest(T, not_followed_by=U) |
T \| None: the most recent T, or None when a U comes after it. See A request that is still open |
log.has(T) |
bool |
log.count(T) |
int |
log.select(T) / log.after(T) / log.before(T) |
chainable EventLog |
log.cause(e) |
the origin of e: Cause, NotRecorded, SourceDropped, FrameworkEvent, or None for a seed. See Causes |
log.effects(e) |
tuple[Event, ...]: the events that a handler produced from e, in log order |
log.flow(e) |
tuple[Event, ...]: the chain of Cause that ends at e |
log.causes |
one origin per event, aligned with events, or None when the log records no causes |
len(log), log[i] |
container protocol |
A request that is still open¶
not_followed_by= finds the latest request that no answer follows yet. Complex event
processing calls it a negation, or "A not followed by B". Events of U before the most recent
T do not count.
...
@on(MessageReceived)
def reply(event: MessageReceived, log: EventLog) -> MessageSent:
pending = log.latest(QuestionAsked, not_followed_by=Answered | Withdrawn)
if pending is None:
return MessageSent(text="No question waits for an answer.")
return MessageSent(text=f"Still waiting for an answer to: {pending.question}")
| Rule | Detail |
|---|---|
Value of U |
One Event class, or a union of Event classes written with \|. Any other value raises TypeError, also on an empty log. |
An event of both T and U |
It is a match, not a follower. So T can also be a member of U. |
A later subclass of T |
It is a match, also when it is a member of U. |
An older T with no follower |
It is not returned. Only the most recent T is checked. To list every open T, loop over log.filter(T). |
| Fields | They are not compared. Any event of U closes the T. To pair a request with its own answer, compare an ID in your handler. |
after(T) and before(T) |
They cut at the first T, not the latest one. So log.after(T) does not give this query. |
Causes¶
A graph run records the origin of each event. log.cause(e) states it, one case per type:
log.cause(e) returns |
Meaning |
|---|---|
Cause(source, via) |
The dispatch of source to the handler via wrote e. Usually the handler returned e. InvariantViolated, HandlerRaised and HandlerRetried carry the Cause of the dispatch they report. |
NotRecorded() |
e comes from history written before causes existed. |
SourceDropped(via, source_type) |
A handler produced e, but rewrite_store(drop=...) deleted its source. The handler and the type of the deleted event stay known. |
FrameworkEvent() |
The library wrote e: RunPaused, MaxRoundsExceeded, Cancelled, Abandoned or Unresumable. |
None |
A seed: e came from outside, through the invoke() input or pre_seed(). |
NotRecorded and SourceDropped are subclasses of UnknownCause, and each has a reason
sentence. A thread that starts on this release, and that rewrite_store(drop=...) never
rewrites, has no unknown cause.
via equals Edge.via unless the handler has a stable identity. For an inline command handler,
via is the command qualname, such as "Order.Place". For an @on(node_name=...) pin, it is
the pinned name. Cause.source is an event, while Edge.source is a type. HandlerRaised
states the same two facts as handler and source_event.
The lookup finds e by identity first, then as its one equal event. A copy that matches several
equal events raises ValueError: pass the logged object. A log from after(), before() or
select() answers like the log it came from. cause() also raises ValueError when the log
records no causes, or when e is not in the root log.
One dispatch can write several events, for example through Scatter. To count how often a
handler was dispatched, count the distinct id(c.source) over its Cause entries. A
SourceDropped keeps via, so those dispatches can be counted as a separate number.
The log.flow(e) chain starts at the first event whose own cause is not a Cause. The value
that answers an Interrupted, and the Resumed that the library creates, have that
Interrupted as their source.
A client that saves events in its own format saves each cause with them, and rebuilds the log
with EventLog(events, causes=...). Each Cause.source must be the same object as an earlier
event: pass events[j], not a copy. EventLog(log.events, causes=log.causes) rebuilds a root
log, unknown and library-written cases included. The round-trip, with the source saved as its
index in the event list:
...
from langgraph_events import Cause, EventLog
events = list(log.events)
index = {id(e): i for i, e in enumerate(events)}
saved = [(index[id(c.source)], c.via) if isinstance(c, Cause) else c for c in log.causes]
causes = [Cause(events[c[0]], c[1]) if isinstance(c, tuple) else c for c in saved]
rebuilt = EventLog(events, causes=causes)
A save written before causes existed has no entries. Load each of its events as NotRecorded(),
never as None, because None claims that the event is a seed.
A direct graph.compiled.update_state() or graph.compiled.invoke() that writes events must
write one causes entry per event too. Otherwise every older cause shifts by one position, and
no check can detect it. pre_seed() writes the causes for you.
Namespace as the declaration point¶
A Namespace is where related features attach:
- Declarative reducers as class attributes, auto-scoped to namespace events. See Reducers.
- Class-level
invariants/raiseson aCommand, forwarded to the inline command handler. See Control Flow. - Grouping in
graph.namespaces().
Namespace names are scoped to a graph¶
A namespace name identifies one namespace within a graph, not within the process. Reducer discovery and graph.namespaces() both group by name, so two namespaces of the same name in one graph is an error:
...
EventGraph([one.Place, two.Place])
# TypeError: Two different namespaces named 'Trading' reached this graph:
# app.a.Trading and app.b.Trading. Namespace names must be unique within a graph.
A namespace reached only through a handler's return type counts too.
Across graphs the name is free, so one process can run two versions of one namespace module in sequence against the same checkpointed log. Give each version its own NamespaceAwareSerde(namespaces=[...]), because identity resolution consults the serde's namespaces before it imports a module. See the migration gate rules.
System events¶
SystemEvent subclasses control runtime flow. Subscribe like any event. See Control Flow for Interrupted / Resumed, HandlerRaised, HandlerRetried, InvariantViolated. Full table in API.
To retire an Interrupted subclass, settle its paused threads first with graph.event_store.abandon(config) / .aabandon(). See Ending a pause without answering it.
Custom halts subclass Halted and nest under their namespace for locality. graph.namespaces() groups them with the namespace's events, not with the library's system events:
...
class Content(Namespace):
class Classified(DomainEvent):
label: str
class Blocked(Halted):
label: str
Mixins¶
MessageEvent is a plain mixin, not an Event subclass. It wraps a LangChain BaseMessage in a message or messages field. Compose it with any event branch and pair it with message_reducer():
from langchain_core.messages import HumanMessage
from langgraph_events import IntegrationEvent, MessageEvent
class UserMessageReceived(IntegrationEvent, MessageEvent):
message: HumanMessage
SystemPromptSet is a built-in IntegrationEvent + MessageEvent. See Graph-wide reducers for the invoke example.