Installation
Initialization
register_worker
Register the worker with a iii instance, returns a connected worker client. Blocks up to 30 seconds for the WebSocket connection to be established. If the engine is not reachable in time, a warning is logged and the client is returned anyway; it keeps retrying in the background and flushes registrations once connected. Useadd_connection_state_listener to observe the actual transition.
Signature
- Parameters
- Example
Methods
register_trigger
Bind a trigger configuration to a registered function. Signature- Parameters
- Example
RegisterTriggerInput | dict[str, Any]
required
A
RegisterTriggerInput or dict with type, function_id, and optional config.register_function
Register a function with the engine. Pass a handler for local execution, or anHttpInvocationConfig
for HTTP-invoked functions (Lambda, Cloudflare Workers, etc.).
Handlers can be synchronous or asynchronous. Sync handlers are
automatically wrapped with run_in_executor so they do not
block the event loop. Each handler receives a data argument
containing the trigger payload, and may optionally accept a second
metadata argument carrying per-invocation metadata (e.g.
def handler(data, metadata=None) or def handler(data, *, metadata=None)). Metadata is only forwarded to handlers that
declare a parameter literally named metadata, so existing
handlers, including ones with unrelated extra parameters,
*args, or **kwargs, keep working unchanged.
request_format and response_format are auto-extracted
from the handler’s type hints when omitted or passed as None
(the default). To opt out of auto-extraction, pass an explicit
schema (RegisterFunctionFormat or dict). This behavior
is Python-specific; the Node SDK relies on explicit schemas because
TypeScript types are erased at runtime.
Signature
- Parameters
- Example
str
required
Unique string identifier for the function.
RemoteFunctionHandler | HttpInvocationConfig
required
A callable handler or
HttpInvocationConfig. Callable handlers receive data (the trigger payload) as the first argument and may optionally accept metadata (per-invocation metadata) as a second argument; they may return a value.str | None
Human-readable description of what the function does.
dict[str, Any] | None
Arbitrary metadata attached to the function.
RegisterFunctionFormat | dict[str, Any] | None
Schema describing expected input. When
None (default), auto-extracted from the handler’s first-parameter type hint. Pass an explicit schema to override; there is no way to register with no schema when the handler is typed.RegisterFunctionFormat | dict[str, Any] | None
Schema describing expected output. Same auto-extraction semantics as
request_format.ObserveHooks | dict[str, Any] | None
Makes the function observable on its own terms: owner delivery (
delivery="owner", args_format), and callbacks when an observer is added or removed (an :class:ObserveHooks, a subclass of it, or a dict of its fields). Without it the function is still observable (auto delivery, no args).bool
Calls this worker makes to its own function run in-process once the engine confirmed it (default
True). Like a remote invocation, each local call to a sync handler runs on a thread of its own (one per call, not pooled), so the caller can stop waiting at its timeout. A sync handler that blocks for long should be async, or set False so its calls go through the engine (also for a handler that relies on engine-side effects).trigger
Invoke a remote function. The routing behavior and return type depend on theaction field:
- No action: synchronous, waits for the function to return.
TriggerAction.Enqueue(...): async via named queue, returns a dict withmessageReceiptId.TriggerAction.Void(): fire-and-forget, returnsNone.
dispatch="remote" (or
action=Enqueue) always goes through the engine. Whatever a local
handler raises, BaseExceptions such as KeyboardInterrupt and
SystemExit included, reaches the caller as
InvocationError("invocation_failed") with the original as its
__cause__ (for a Void call nothing reaches the caller: the
error is logged).
Signature
- Parameters
- Example
dict[str, Any] | TriggerRequest
required
A
TriggerRequest or dict with function_id, payload, and optional action / timeout_ms / metadata / namespace / dispatch ("auto", the default, or "remote").register_trigger_type
Register a custom trigger type with the engine. Returns a :class:TriggerTypeRef handle with register_trigger
and register_function methods.
Signature
- Parameters
- Example
unregister_trigger_type
Unregister a previously registered trigger type. Signature- Parameters
- Example
RegisterTriggerTypeInput | dict[str, Any]
required
A
RegisterTriggerTypeInput or dict with id, an optional description, and (dict only) the namespace it was registered in.add_connection_state_listener
Subscribe to connection-state transitions. The handler is fired immediately with the current state (on the caller’s thread), then once per transition. Transitions fire on the SDK’s background event-loop thread: keep handlers fast and do not call sync SDK methods from them (they would raiseRuntimeError).
Treat calls as state notifications, not edges. A state may rarely
be observed twice around subscription. Registering the same handler
twice fires it twice. Returns an idempotent unsubscribe function
that removes only its own registration.
Signature
- Parameters
- Example
ConnectionStateCallback
required
connect_async
Connect to the III Engine via WebSocket. Initializes OpenTelemetry (if configured), attaches the event loop, and establishes the WebSocket connection. This is called automatically during construction; use it only if you need to reconnect manually from an async context. Signaturecurrent_invocation
The invocation the calling code runs in (in every handler, remote or local), orNone outside any handler.
Signature
Example
get_address
Return the engine address this worker resolved to. The explicitregister_worker argument, else III_URL, else
:data:DEFAULT_ENGINE_URL. Mirrors the Rust SDK’s address() and the
Node SDK’s getAddress().
Signature
get_connection_state
Return the current WebSocket connection state. SignatureExample
observe
Observes a function: every event ofsource (an invocation of an
auto function, or what its owner hands over) that passes
source["filters"] invokes target, a registered function.
Returns synchronously, also before the connection is up; the observer
is replayed with the same id on every reconnect. Errors
(INVALID_ARGS, INVALID_FILTER, FORBIDDEN, an owner’s
rejection, UNSUPPORTED against an engine without observe) show up
as state error and make ready() raise :class:ObserveRejection.
Signature
- Parameters
- Example
ObserveSource | dict[str, Any]
required
What is observed:
function_id, namespace, args (owner-delivered functions only), filters, and on / capture / deliver.Target
required
The function to invoke: its id, or
{"function_id": ..., "namespace": ...}. Register it first; until then the observer stays pending.ObserverOptions | dict[str, Any] | None
id, max_fires, expires_in_ms, max_in_flight, metadata (the activation’s metadata sidecar).shutdown
Gracefully shut down the client, releasing all resources. Cancels any pending reconnection attempts, rejects all in-flight invocations with an error, closes the WebSocket connection, and stops the background event-loop thread. After this call the instance must not be reused. SignatureExample
shutdown_async
Gracefully shut down the client, releasing all resources. Cancels any pending reconnection attempts, rejects all in-flight invocations with an error, closes the WebSocket connection, and stops the background event-loop thread. After this call the instance must not be reused. SignatureExample
trigger_async
Invoke a remote function. The routing behavior and return type depend on theaction field:
- No action: synchronous, waits for the function to return.
TriggerAction.Enqueue(...): async via named queue, returns a dict withmessageReceiptId.TriggerAction.Void(): fire-and-forget, returnsNone.
dispatch="remote" (or action=Enqueue) always goes through
the engine.
Signature
- Parameters
- Example
dict[str, Any] | TriggerRequest
required
A
TriggerRequest or dict with function_id, payload, and optional action / timeout_ms / metadata / namespace / dispatch ("auto" or "remote").Types
iii
Caller · EnqueueResult · InitOptions · InvocationContext · MiddlewareFunctionInput · Observed · ObserveHooks · Observer · ObserverHandle · ObserverOptions · ObserveSource · StreamRequest · StreamResponse · TelemetryOptions · TriggerAction · TriggerActionEnqueue
Caller
Who started an invocation: the worker (worker_id / worker_name,
stamped by the engine), and the function and invocation the call was made
from (absent for top-level calls). parent is that handler’s own caller,
one level only.
EnqueueResult
Result returned when a function is invoked withTriggerAction.Enqueue.
InitOptions
Configuration options passed toregister_worker.
InvocationContext
The invocation the current code runs in, in every handler, remote or local. Returned byiii.current_invocation().
MiddlewareFunctionInput
Input passed to the RBAC middleware function on every function invocation through the RBAC port.Observed
What the target of an auto observer (or ofobs.emit) receives with
deliver: "envelope" (the default). Fields not in the observer’s
capture are absent.
ObserveHooks
Theobserve option of register_function: how the function’s
observers are delivered, and the callbacks that run when one is added or
removed.
Pass an instance, built with keyword arguments or from a subclass that
sets the attributes and defines the callbacks as (sync or async) methods.
Only delivery, args_format, legacy_trigger_type and allow
travel to the engine; the callbacks stay in this process.
Observer
An observer as the function’s owner sees it (on_observer_added,
FunctionRef.observers()): its args, filters, target, capture and
on. Never its metadata, policy or the observing worker.
The object stays the same for the observer’s whole lifetime, so owners
keep it in their own index (expression → observers, route table, …).
ObserverHandle
Whatiii.observe returns, synchronously.
The observer is replayed with the same id on every reconnect until it is
disposed. State listeners are called in order, on a callback thread of the
SDK (never on the event loop that reads the engine’s frames), so they may
call the sync API.
ObserverOptions
The observer itself: its id, policy and metadata (the third argument ofiii.observe).
ObserveSource
The left side ofiii.observe: what is observed.
StreamRequest
Incoming streaming request received by a function registered with a stream trigger.StreamResponse
Streaming response built on top of a ChannelWriter.TelemetryOptions
Worker metadata reported to the engine (language, framework, project).TriggerAction
Factory for creating trigger actions used withtrigger().
TriggerActionEnqueue
Routes the invocation through a named queue for async processing. Requires thequeue worker in worker-compose.yaml and a matching
entry under that worker’s queue_configs.
Without it the trigger rejects with enqueue_error (no queue provider).
iii.channel
Channel · ChannelReader · ChannelWriter · StreamChannelRef
Channel
A streaming channel pair for worker-to-worker data transfer.ChannelReader
WebSocket-backed reader for streaming binary data and text messages.ChannelWriter
WebSocket-backed writer for streaming binary data and text messages.StreamChannelRef
Reference to a streaming channel for worker-to-worker data transfer.iii.engine
EngineFunctions · EngineTriggers
EngineFunctions
Engine function ids for internal operations (parity with the Node SDK).EngineTriggers
Engine trigger ids (parity with the Node SDK).iii.errors
InvocationError · ObserveRejection · RegistrationRejectedError
InvocationError
Raised when an invocation dispatched by the SDK fails. Inspecterr.code to react to a specific category (e.g.
'FORBIDDEN' for RBAC denials, 'TIMEOUT' for timeouts). Catch
this class to handle every rejection. except Exception continues to
work because InvocationError inherits from Exception.
Attributes are read-only after construction. stacktrace is the
engine-side trace when the remote handler raised; it may include
internal file paths and should not be surfaced to end users. str(err)
intentionally never includes the stacktrace.
ObserveRejection
Rejects an observer with a code of its own. Raise it from anon_observer_added hook (HTTP_ROUTE_CONFLICT,
INVALID_CRON_EXPRESSION, …); any other exception rejects the
observer with OBSERVE_REJECTED. Also what ObserverHandle.ready()
raises when the observer turns error or disposed, with the
engine’s code (INVALID_ARGS, FORBIDDEN, UNSUPPORTED, …).
RegistrationRejectedError
Raised when the engine rejects this worker’s registration. The engine pushes aregistrationrejected message and closes the
connection on a registration collision (e.g. another live worker already
owns (namespace, worker_name)). This is fatal: the SDK does not
reconnect. Inspect the attributes to identify the conflict.
iii.protocol
MessageType · RegisterFunctionFormat · RegisterFunctionInput · RegisterFunctionMessage · RegisterTriggerInput · RegisterTriggerMessage · RegisterTriggerTypeInput · RegisterTriggerTypeMessage · SDK_FEATURES · TriggerRequest
MessageType
Message types for iii communication.RegisterFunctionFormat
Format definition for function parameters.RegisterFunctionInput
Input for registering a function, matches Node.js RegisterFunctionInput.RegisterFunctionMessage
RegisterTriggerInput
Input for registering a trigger (matches Node SDK’s RegisterTriggerInput).RegisterTriggerMessage
RegisterTriggerTypeInput
Input for registering a trigger type.RegisterTriggerTypeMessage
SDK_FEATURES
TriggerRequest
Request object fortrigger().
iii.runtime
FunctionRef · TriggerTypeRef
FunctionRef
Reference to a registered function, allowing programmatic unregistration.TriggerTypeRef
Typed handle returned by :meth:iii.III.register_trigger_type.
.. deprecated:: 0.25.0
Trigger types are replaced by functions with an observe descriptor,
and these helpers by iii.observe. Migration guide:
https://iii.dev/docs/upgrading/from-0-24-x
Type parameters:
C: configuration type for :meth:register_triggerR: call-request type for :meth:register_function
iii.state
IState · StateDeleteInput · StateDeleteResult · StateEventData · StateEventType · StateGetInput · StateListInput · StateSetInput · StateSetResult · StateUpdateInput · StateUpdateResult
IState
Abstract interface for state management operations.StateDeleteInput
Input for deleting a state value.StateDeleteResult
Result of a state delete operation.StateEventData
Payload for state change events.StateEventType
Types of state change events.StateGetInput
Input for retrieving a state value.StateListInput
Input for listing all values in a state scope.StateSetInput
Input for setting a state value.StateSetResult
Result of a state set operation.StateUpdateInput
Input for atomically updating a state value.StateUpdateResult
Result of a state update operation.iii.stream
IStream · StreamDeleteInput · StreamDeleteResult · StreamGetInput · StreamListGroupsInput · StreamListInput · StreamSetInput · StreamSetResult · StreamUpdateInput · StreamUpdateResult
IStream
Abstract interface for stream operations.StreamDeleteInput
Input for stream delete operation.StreamDeleteResult
Result of stream delete operation.StreamGetInput
Input for stream get operation.StreamListGroupsInput
Input for stream list groups operation.StreamListInput
Input for stream list operation.StreamSetInput
Input for stream set operation.StreamSetResult
Result of stream set operation.StreamUpdateInput
Input for stream update operation.StreamUpdateResult
Result of stream update operation.iii.trigger
Trigger · TriggerActionVoid · TriggerConfig · TriggerHandler
Trigger
Represents a registered trigger. .. deprecated:: 0.25.0register_trigger is replaced by iii.observe, which returns an
:class:~iii.ObserverHandle.
TriggerActionVoid
Fire-and-forget routing. No response is returned.TriggerConfig
Configuration passed to a trigger handler when a trigger instance is registered or unregistered. .. deprecated:: 0.25.0 Replaced by the :class:~iii.Observer an on_observer_added hook
receives (id, args, filters, target).
TriggerHandler
Abstract base class for trigger handlers. .. deprecated:: 0.25.0 Replaced by :class:~iii.ObserveHooks (on_observer_added /
on_observer_removed) on register_function. Migration guide:
https://iii.dev/docs/upgrading/from-0-24-x