Skip to content

API Reference

Complete reference for every public symbol in PyRapide. All imports are from the top-level pyrapide package unless otherwise noted.

imports.py python
from pyrapide import Event, Poset, Computation, interface, action
from pyrapide import architecture, connect, Pattern, Engine
from pyrapide import MCPEventAdapter, StreamProcessor
from pyrapide import queries, visualization

Core

Foundational classes for events, partial orders, computations, clocks, and cycle detection.

SymbolDescription
EventImmutable, uniquely-identified record representing an observable occurrence. Frozen Pydantic model with name, payload, source, and auto-generated ID.
PosetPartially ordered set of events backed by a NetworkX DAG. Supports causal ordering, concurrent-event detection, and topological iteration.
ComputationA complete causal history: a Poset together with its originating architecture context. Entry point for all analysis queries.
ClockAbstract base class for all clock types. Provides the tick interface used by the engine to advance logical time.
SynchronousClockClock that ticks in lockstep with the engine's main loop. All events in one tick are causally concurrent.
RegularClockClock that ticks at a fixed time interval. Useful for periodic polling or heartbeat architectures.
SlavedClockClock driven by an external signal rather than an internal timer. Ticks only when explicitly advanced by another component.
ClockManagerManages multiple clocks within an architecture, coordinating ticks and resolving cross-clock causal dependencies.
CausalCycleErrorRaised when an operation would introduce a cycle into the causal DAG, violating the partial-order invariant.

Types

Decorators and functions for defining typed component interfaces, behavioral contracts, and subtype relationships.

SymbolDescription
interfaceClass decorator that declares a component interface. Registers action signatures and provides/requires contracts for architecture wiring.
actionMethod decorator marking an async method as an observable action. Actions produce events when invoked.
providesDeclares that an interface emits events of a specified type. Used in connection resolution.
requiresDeclares that an interface consumes events of a specified type. The engine validates that all requirements are satisfied.
behaviorDecorator for defining behavioral rules on an interface. These constraints govern valid event sequences.
is_subtypeReturns True if one interface is a structural subtype of another, meaning its action signatures are a superset.
conforms_toReturns True if an interface satisfies the behavioral contracts of another, including action signatures and constraint compliance.

Patterns

Composable event pattern matching with operator overloading. Patterns describe causal sequences, joins, independence, and temporal constraints.

SymbolDescription
PatternBase class for all event patterns. Supports composition through operators and fluent methods.
Pattern.matchCreates a basic pattern that matches events by name, source, or payload predicates.
BasicPatternA leaf-level pattern matching a single event criterion. Building block for composite patterns.
PatternMatchResult object returned when a pattern matches. Contains the matched events and their bindings.
placeholderCreates a named placeholder for capturing matched events in pattern expressions.
>> (sequence)Operator composing two patterns into a causal sequence. The left pattern must causally precede the right.
.then_immediatelyComposes a strict sequence where the right pattern must be the immediate causal successor with no intervening events.
& (join)Operator requiring both patterns to match, with their matched events sharing a common causal ancestor.
| (independence)Operator requiring both patterns to match independently. Their matched events must be causally unrelated.
.or_Matches if either pattern matches. Short-circuits on the first successful match.
.unionCombines patterns into a union, matching all occurrences of any constituent pattern.
.whereAdds a predicate guard to a pattern. The pattern only matches if the predicate returns True for the matched events.
.timedAdds a temporal constraint requiring the pattern to match within a specified duration.
.repeatMatches the pattern a specified number of times in causal succession. Supports min/max bounds.

Architecture

Decorators and functions for composing components into executable architectures with causal connections.

SymbolDescription
architectureClass decorator declaring a system architecture. Registers component instances and their connections for engine execution.
connectCreates a connection rule routing events matching a pattern to a target component. Supports three causal semantics.
pipeShorthand for a direct one-to-one connection between two components where all events from the source flow to the target.
agentDecorator for defining autonomous agent components with their own event loops and decision-making logic.

Constraints

Declarative behavioral rules that specify what must happen and what must never happen during execution.

SymbolDescription
ConstraintBase class for all constraint types. Subclass to define custom behavioral rules.
MustMatchConstraint asserting that a pattern must be matched at least once during execution. Violation raised at end if unmatched.
NeverConstraint asserting that a pattern must never match. Violation raised immediately upon first match.
must_matchFactory function creating a MustMatch constraint from a pattern and an optional name.
neverFactory function creating a Never constraint from a pattern and an optional name.
constraintDecorator for defining a custom constraint function. The function receives a Computation and returns a list of violations.
ConstraintViolationData class representing a single constraint violation, including the constraint name, violating events, and message.
ConstraintMonitorRuntime monitor that evaluates constraints against a live computation, firing callbacks on violations.

Executable

Decorators for implementing component behavior with reactive event handlers.

SymbolDescription
moduleClass decorator that makes a component executable. Binds event handlers and registers the component with the engine.
whenMethod decorator that registers an async handler triggered when a specified pattern matches in the causal history.
get_contextReturns the current execution context inside a handler. Provides access to the computation, the triggering event, and the engine.

Runtime

The execution engine and streaming infrastructure for running architectures and processing live event sources.

SymbolDescription
EngineAsync execution engine that runs an architecture, dispatches events through connections, and builds the causal computation.
StreamProcessorManages multiple concurrent event sources, merges them into a unified causal stream, and applies sliding-window processing.
InMemoryEventSourceSimple event source backed by an in-memory list. Useful for testing and replaying recorded event sequences.

Integrations

Adapters for connecting PyRapide to MCP servers, LLM tool-calling APIs, and other external event producers.

SymbolDescription
MCPEventAdapterTranslates MCP protocol messages (tool calls, results, errors, notifications) into causally-linked PyRapide events.
MCPEventTypesEnum of standardized event names for MCP protocol operations: tool_call, tool_result, resource_read, notification, etc.
MCPPatternsPre-built pattern library for common MCP scenarios: tool roundtrips, error cascades, resource access sequences.
LLMEventAdapterTranslates LLM API interactions (prompts, completions, tool invocations) into causally-linked events for agent tracing.
LLMEventTypesEnum of standardized event names for LLM operations: prompt, completion, tool_call, tool_result, chain_step.

Analysis

Query functions, visualization backends, and machine-learning tools for exploring causal computations.

queries

SymbolDescription
queries.critical_pathReturns the longest causal chain in the computation, which is the sequence of events that determines overall latency.
queries.root_causesGiven a target event, traces backward through the DAG to find all root-cause events with no causal predecessors.
queries.impact_setReturns the set of all events causally downstream of a given event, representing its full blast radius.
queries.causal_distanceReturns the length of the shortest causal path between two events, or infinity if they are causally unrelated.
queries.common_ancestorsReturns all events that are causal ancestors of both given events. Useful for finding shared origins.
queries.backward_sliceReturns the subgraph of all events that causally contribute to a given event, capturing everything in its causal past.
queries.forward_sliceReturns the subgraph of all events causally affected by a given event, capturing everything in its causal future.
queries.parallel_eventsReturns all events that are concurrent with a given event; causally unrelated, happening "at the same time."
queries.bottleneck_eventsIdentifies events that lie on every causal path from source to sink. Removing them would disconnect the computation.
queries.event_frequencyReturns a frequency distribution of event names in the computation, useful for identifying hot spots.
queries.causal_densityReturns the ratio of causal edges to possible edges, measuring how tightly coupled the computation is.

visualization

SymbolDescription
visualization.to_dotExports the computation's causal graph as a Graphviz DOT string for rendering with dot, neato, or other layout engines.
visualization.to_mermaidExports the causal graph as a Mermaid diagram string, embeddable in Markdown documentation and GitHub READMEs.
visualization.to_jsonExports the causal graph as a JSON object with nodes and edges arrays, suitable for D3.js or custom frontends.
visualization.to_asciiRenders a compact ASCII art representation of the causal graph for terminal output and log files.
visualization.summaryReturns a human-readable text summary of the computation: event counts, depth, width, critical path length, and constraint status.

Machine Learning

SymbolDescription
CausalPredictorLearns from historical computations to predict likely downstream events given a partial causal history.
AnomalyDetectorIdentifies computations whose causal structure deviates significantly from learned baselines, flagging unusual patterns.

Agent Templates

Drop-in adapters for 8 agentic AI frameworks, plus shared infrastructure for event normalization, causal linking, and pre-built patterns.

SymbolImport PathDescription
AgentEventTypespyrapide.agent_templates.coreUnified event type constants for all agentic frameworks (17 types).
AgentPatternspyrapide.agent_templates.corePre-built pattern library: tool_roundtrip(), llm_roundtrip(), error_cascade(), and more.
BaseAgentAdapterpyrapide.agent_templates.coreAbstract base class implementing the EventSource protocol for all adapters.
CausalTrackerpyrapide.agent_templates.coreAutomatic causal linking engine using correlation IDs, scope stacks, and sequential heuristics.
ResultBridgepyrapide.agent_templates.coreAnalysis result formatting: dict, markdown, and Graphviz DOT output.
AutoGenAdapterpyrapide.agent_templates.autogenMicrosoft AutoGen adapter via InterventionHandler on the runtime.
LangGraphAdapterpyrapide.agent_templates.langgraphLangGraph / LangChain adapter via BaseCallbackHandler with run_id correlation.
CrewAIAdapterpyrapide.agent_templates.crewaiCrewAI adapter via global tool hooks and step/task callbacks.
LlamaIndexAdapterpyrapide.agent_templates.llamaindexLlamaIndex adapter via root Dispatcher event handler (25+ event types).
AgnoAdapterpyrapide.agent_templates.agnoAgno adapter via pre/post hooks and RunEvent stream.
SwarmAdapterpyrapide.agent_templates.swarmOpenAI Swarm adapter via InstrumentedSwarm subclass (drop-in replacement).
MetaGPTAdapterpyrapide.agent_templates.metagptMetaGPT adapter via monkey-patch wrappers on Role.run, Action.run, and Environment.
FlowiseAdapterpyrapide.agent_templates.flowiseFlowiseAI adapter via REST API and SSE event stream consumer.

This reference covers PyRapide's public API. For detailed usage examples, see the documentation. For the source code, visit the GitHub repository.