API Reference
Complete reference for every public symbol in PyRapide. All imports are from the top-level pyrapide package unless otherwise noted.
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.
| Symbol | Description |
|---|---|
| Event | Immutable, uniquely-identified record representing an observable occurrence. Frozen Pydantic model with name, payload, source, and auto-generated ID. |
| Poset | Partially ordered set of events backed by a NetworkX DAG. Supports causal ordering, concurrent-event detection, and topological iteration. |
| Computation | A complete causal history: a Poset together with its originating architecture context. Entry point for all analysis queries. |
| Clock | Abstract base class for all clock types. Provides the tick interface used by the engine to advance logical time. |
| SynchronousClock | Clock that ticks in lockstep with the engine's main loop. All events in one tick are causally concurrent. |
| RegularClock | Clock that ticks at a fixed time interval. Useful for periodic polling or heartbeat architectures. |
| SlavedClock | Clock driven by an external signal rather than an internal timer. Ticks only when explicitly advanced by another component. |
| ClockManager | Manages multiple clocks within an architecture, coordinating ticks and resolving cross-clock causal dependencies. |
| CausalCycleError | Raised 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.
| Symbol | Description |
|---|---|
| interface | Class decorator that declares a component interface. Registers action signatures and provides/requires contracts for architecture wiring. |
| action | Method decorator marking an async method as an observable action. Actions produce events when invoked. |
| provides | Declares that an interface emits events of a specified type. Used in connection resolution. |
| requires | Declares that an interface consumes events of a specified type. The engine validates that all requirements are satisfied. |
| behavior | Decorator for defining behavioral rules on an interface. These constraints govern valid event sequences. |
| is_subtype | Returns True if one interface is a structural subtype of another, meaning its action signatures are a superset. |
| conforms_to | Returns 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.
| Symbol | Description |
|---|---|
| Pattern | Base class for all event patterns. Supports composition through operators and fluent methods. |
| Pattern.match | Creates a basic pattern that matches events by name, source, or payload predicates. |
| BasicPattern | A leaf-level pattern matching a single event criterion. Building block for composite patterns. |
| PatternMatch | Result object returned when a pattern matches. Contains the matched events and their bindings. |
| placeholder | Creates 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_immediately | Composes 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. |
| .union | Combines patterns into a union, matching all occurrences of any constituent pattern. |
| .where | Adds a predicate guard to a pattern. The pattern only matches if the predicate returns True for the matched events. |
| .timed | Adds a temporal constraint requiring the pattern to match within a specified duration. |
| .repeat | Matches 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.
| Symbol | Description |
|---|---|
| architecture | Class decorator declaring a system architecture. Registers component instances and their connections for engine execution. |
| connect | Creates a connection rule routing events matching a pattern to a target component. Supports three causal semantics. |
| pipe | Shorthand for a direct one-to-one connection between two components where all events from the source flow to the target. |
| agent | Decorator 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.
| Symbol | Description |
|---|---|
| Constraint | Base class for all constraint types. Subclass to define custom behavioral rules. |
| MustMatch | Constraint asserting that a pattern must be matched at least once during execution. Violation raised at end if unmatched. |
| Never | Constraint asserting that a pattern must never match. Violation raised immediately upon first match. |
| must_match | Factory function creating a MustMatch constraint from a pattern and an optional name. |
| never | Factory function creating a Never constraint from a pattern and an optional name. |
| constraint | Decorator for defining a custom constraint function. The function receives a Computation and returns a list of violations. |
| ConstraintViolation | Data class representing a single constraint violation, including the constraint name, violating events, and message. |
| ConstraintMonitor | Runtime monitor that evaluates constraints against a live computation, firing callbacks on violations. |
Executable
Decorators for implementing component behavior with reactive event handlers.
| Symbol | Description |
|---|---|
| module | Class decorator that makes a component executable. Binds event handlers and registers the component with the engine. |
| when | Method decorator that registers an async handler triggered when a specified pattern matches in the causal history. |
| get_context | Returns 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.
| Symbol | Description |
|---|---|
| Engine | Async execution engine that runs an architecture, dispatches events through connections, and builds the causal computation. |
| StreamProcessor | Manages multiple concurrent event sources, merges them into a unified causal stream, and applies sliding-window processing. |
| InMemoryEventSource | Simple 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.
| Symbol | Description |
|---|---|
| MCPEventAdapter | Translates MCP protocol messages (tool calls, results, errors, notifications) into causally-linked PyRapide events. |
| MCPEventTypes | Enum of standardized event names for MCP protocol operations: tool_call, tool_result, resource_read, notification, etc. |
| MCPPatterns | Pre-built pattern library for common MCP scenarios: tool roundtrips, error cascades, resource access sequences. |
| LLMEventAdapter | Translates LLM API interactions (prompts, completions, tool invocations) into causally-linked events for agent tracing. |
| LLMEventTypes | Enum 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
| Symbol | Description |
|---|---|
| queries.critical_path | Returns the longest causal chain in the computation, which is the sequence of events that determines overall latency. |
| queries.root_causes | Given a target event, traces backward through the DAG to find all root-cause events with no causal predecessors. |
| queries.impact_set | Returns the set of all events causally downstream of a given event, representing its full blast radius. |
| queries.causal_distance | Returns the length of the shortest causal path between two events, or infinity if they are causally unrelated. |
| queries.common_ancestors | Returns all events that are causal ancestors of both given events. Useful for finding shared origins. |
| queries.backward_slice | Returns the subgraph of all events that causally contribute to a given event, capturing everything in its causal past. |
| queries.forward_slice | Returns the subgraph of all events causally affected by a given event, capturing everything in its causal future. |
| queries.parallel_events | Returns all events that are concurrent with a given event; causally unrelated, happening "at the same time." |
| queries.bottleneck_events | Identifies events that lie on every causal path from source to sink. Removing them would disconnect the computation. |
| queries.event_frequency | Returns a frequency distribution of event names in the computation, useful for identifying hot spots. |
| queries.causal_density | Returns the ratio of causal edges to possible edges, measuring how tightly coupled the computation is. |
visualization
| Symbol | Description |
|---|---|
| visualization.to_dot | Exports the computation's causal graph as a Graphviz DOT string for rendering with dot, neato, or other layout engines. |
| visualization.to_mermaid | Exports the causal graph as a Mermaid diagram string, embeddable in Markdown documentation and GitHub READMEs. |
| visualization.to_json | Exports the causal graph as a JSON object with nodes and edges arrays, suitable for D3.js or custom frontends. |
| visualization.to_ascii | Renders a compact ASCII art representation of the causal graph for terminal output and log files. |
| visualization.summary | Returns a human-readable text summary of the computation: event counts, depth, width, critical path length, and constraint status. |
Machine Learning
| Symbol | Description |
|---|---|
| CausalPredictor | Learns from historical computations to predict likely downstream events given a partial causal history. |
| AnomalyDetector | Identifies 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.
| Symbol | Import Path | Description |
|---|---|---|
| AgentEventTypes | pyrapide.agent_templates.core | Unified event type constants for all agentic frameworks (17 types). |
| AgentPatterns | pyrapide.agent_templates.core | Pre-built pattern library: tool_roundtrip(), llm_roundtrip(), error_cascade(), and more. |
| BaseAgentAdapter | pyrapide.agent_templates.core | Abstract base class implementing the EventSource protocol for all adapters. |
| CausalTracker | pyrapide.agent_templates.core | Automatic causal linking engine using correlation IDs, scope stacks, and sequential heuristics. |
| ResultBridge | pyrapide.agent_templates.core | Analysis result formatting: dict, markdown, and Graphviz DOT output. |
| AutoGenAdapter | pyrapide.agent_templates.autogen | Microsoft AutoGen adapter via InterventionHandler on the runtime. |
| LangGraphAdapter | pyrapide.agent_templates.langgraph | LangGraph / LangChain adapter via BaseCallbackHandler with run_id correlation. |
| CrewAIAdapter | pyrapide.agent_templates.crewai | CrewAI adapter via global tool hooks and step/task callbacks. |
| LlamaIndexAdapter | pyrapide.agent_templates.llamaindex | LlamaIndex adapter via root Dispatcher event handler (25+ event types). |
| AgnoAdapter | pyrapide.agent_templates.agno | Agno adapter via pre/post hooks and RunEvent stream. |
| SwarmAdapter | pyrapide.agent_templates.swarm | OpenAI Swarm adapter via InstrumentedSwarm subclass (drop-in replacement). |
| MetaGPTAdapter | pyrapide.agent_templates.metagpt | MetaGPT adapter via monkey-patch wrappers on Role.run, Action.run, and Environment. |
| FlowiseAdapter | pyrapide.agent_templates.flowise | FlowiseAI 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.