Skip to content
Packages Examples Agents Blog Get started

One wire format's typed bidirectional mapping to the canonical IR.

Concrete mappers implement the same operations the container-facing RelayMapperProtocol declares; the registry in the relay engine holds FormatMapper implementations.

format
property format() -> RelayFormat

The wire format this mapper serves; concrete mappers define it.

request_to_ir
def request_to_ir(
    payload: Any,
    *,
    context: ConversionContext
) -> Result[RelayRequest, RelayError]

Convert a source request DTO into canonical RelayRequest.

ir_to_request
def ir_to_request(
    request: RelayRequest,
    *,
    context: ConversionContext
) -> Result[Any, RelayError]

Convert a canonical RelayRequest into the target request DTO.

response_to_ir
def response_to_ir(
    payload: Any,
    *,
    context: ConversionContext
) -> Result[RelayResponse, RelayError]

Convert a source response DTO into canonical RelayResponse.

ir_to_response
def ir_to_response(
    response: RelayResponse,
    *,
    context: ConversionContext
) -> Result[Any, RelayError]

Convert a canonical RelayResponse into the target response DTO.

stream_to_delta
def stream_to_delta(
    event: Any,
    *,
    state: StreamState
) -> Result[tuple[StreamDelta, Ellipsis], RelayError]

Convert one source stream event into canonical StreamDeltas.

delta_to_stream
def delta_to_stream(
    delta: StreamDelta,
    *,
    state: StreamState
) -> Result[tuple[Any, Ellipsis], RelayError]

Convert one canonical StreamDelta into target stream events.


Per-conversion context with nil-safe callbacks and a loss sink.

Attributes: options: Cross-protocol adaptation options. Zero-value when the host supplied no context. default_max_tokens: Claude max_tokens fallback lookup, always callable. safety_setting: Gemini safety threshold lookup, always callable. supports_image_generation: Gemini image-generation capability lookup, always callable. preserve_thinking_suffix: Thinking-suffix bypass policy lookup, always callable. media_resolver: Resolver for URL media, or None. upstream_model: Host model name substituted when the source payload carries no model; empty when unset. losses: Semantic losses recorded during conversion.

wrap
def wrap(
    cls,
    context: RelayConversionContext | None
) -> ConversionContext

Adapt a host context, substituting nil-safe defaults.

Parameters
ParameterTypeDescription
`context`RelayConversionContext | NoneHost context, or ``None`` when the gateway supplied none.
Returns
TypeDescription
ConversionContextAn adapter with callable callbacks and the host's loss list.
max_tokens_for
def max_tokens_for(model: str) -> int | None

Return the default max_tokens for model.

Negative callback results are treated as invalid and yield None; mappers apply their own missing-option policy.

Parameters
ParameterTypeDescription
`model`strThe already-selected upstream model name.
Returns
TypeDescription
int | NoneA non-negative default, or ``None`` when absent or invalid.
normalize_model
def normalize_model(model: str) -> str

Normalize a model name without selecting a different model.

Parameters
ParameterTypeDescription
`model`strRaw model name from the source payload.
Returns
TypeDescription
strThe cleaned model name.
resolve_model
def resolve_model(model: str) -> str

Normalize a model name, substituting the host upstream model.

Empty source model names (e.g. Gemini responses that carry no model) fall back to the host upstream_model so downstream requests still identify the model.

Parameters
ParameterTypeDescription
`model`strRaw model name from the source payload.
Returns
TypeDescription
strThe cleaned model name, or the upstream fallback.

Explicit source/target conversion over a caller-owned registry.
Parameters
ParameterTypeDescription
`registry`The registry used when a conversion call does not pass its own ``registry`` override.
__init__
def __init__(registry: RelayRegistryProtocol) -> None

Initialise the engine with a default registry.

convert_request
def convert_request(
    payload: RelayRequestPayload,
    source: RelayFormat,
    target: RelayFormat,
    *,
    context: RelayConversionContext | None = None,
    registry: RelayRegistryProtocol | None = None
) -> Result[RelayConvertResult[RelayRequestPayload], RelayError]

Convert a request payload from source to target.

convert_response
def convert_response(
    payload: RelayResponsePayload,
    source: RelayFormat,
    target: RelayFormat,
    *,
    context: RelayConversionContext | None = None,
    registry: RelayRegistryProtocol | None = None
) -> Result[RelayConvertResult[RelayResponsePayload], RelayError]

Convert a non-stream response payload from source to target.

new_stream_session
def new_stream_session(
    source: RelayFormat,
    target: RelayFormat,
    *,
    options: RelayStreamOptions | None = None,
    context: RelayConversionContext | None = None,
    registry: RelayRegistryProtocol | None = None
) -> Result[RelayStreamSessionProtocol, RelayError]

Create a stateful stream session for one upstream stream.

Stateful stream conversion is delivered by the shared stream lifecycle in a later task; every current route reports no stream support.

convert_stream_chunk
def convert_stream_chunk(
    session: RelayStreamSessionProtocol,
    event: Any
) -> tuple[Any, Ellipsis]

Convert one source stream event through session.

Raises
ExceptionDescription
RelayErrorStateful stream conversion is not implemented yet.
finalize
def finalize(session: RelayStreamSessionProtocol) -> tuple[Any, Ellipsis]

Close a stream deterministically and return terminal events.

Raises
ExceptionDescription
RelayErrorStateful stream conversion is not implemented yet.

Caller-owned registry of format mappers with derived routes.

__init__ creates an empty registry; with_defaults prepopulates the four built-in mappers. A caller may build and mutate their own instance without touching the process-global default registry.

__init__
def __init__() -> None

Create an empty registry.

with_defaults
def with_defaults(cls) -> RelayConverterRegistry

Return a registry prepopulated with the four built-in mappers.

register
def register(mapper: FormatMapper) -> None

Register a mapper for its declared wire format.

Parameters
ParameterTypeDescription
`mapper`FormatMapperA mapper exposing a ``format`` RelayFormat attribute.
Raises
ExceptionDescription
RelayErrorWith code ``duplicate_registration`` when a mapper is already registered for the format, or ``unsupported_format`` when the mapper does not declare a ``RelayFormat`` ``format`` attribute.
mapper
def mapper(
    source: RelayFormat,
    target: RelayFormat
) -> RelayMapperProtocol | None

Return the delegating route for a directed pair, or None.

Same-format pairs return None; the engine treats those as a no-op conversion.

Parameters
ParameterTypeDescription
`source`RelayFormatSource wire format.
`target`RelayFormatTarget wire format.
Returns
TypeDescription
RelayMapperProtocol | NoneThe route mapper, or ``None`` when no route exists.
converter_routes
def converter_routes() -> tuple[tuple[RelayFormat, RelayFormat], Ellipsis]

Return every supported directed route pair.

Returns
TypeDescription
tuple[tuple[RelayFormat, RelayFormat], Ellipsis]Sorted route pairs, excluding same-format no-op pairs.
mapper_ids
def mapper_ids() -> tuple[str, Ellipsis]

Return the registered mapper wire-format identifiers.

Returns
TypeDescription
tuple[str, Ellipsis]Sorted mapper ids, one per registered mapper.
converter_version
def converter_version() -> str

Return the converter engine version string.

Returns
TypeDescription
strThe module-level ``CONVERTER_VERSION`` constant.
route_quality
def route_quality(
    source: RelayFormat,
    target: RelayFormat
) -> ConversionQuality

Return the semantic-closeness quality for a directed pair.

Same-format pairs and unconfigured routes fall back to GOOD/DISCOURAGED via the quality matrix.

Parameters
ParameterTypeDescription
`source`RelayFormatSource wire format.
`target`RelayFormatTarget wire format.
Returns
TypeDescription
ConversionQualityThe stable quality value for the pair.
route
def route(
    source: RelayFormat,
    target: RelayFormat
) -> RouteSpec | None

Return the route spec for a directed pair, or None.

Same-format pairs return None (no-op conversion).

Parameters
ParameterTypeDescription
`source`RelayFormatSource wire format.
`target`RelayFormatTarget wire format.
Returns
TypeDescription
RouteSpec | NoneThe route spec, or ``None`` when no route exists.
route_by_id
def route_by_id(converter_id: str) -> RouteSpec | None

Return the route spec carrying converter_id, or None.

Parameters
ParameterTypeDescription
`converter_id`strA stable ``"_to_"`` identifier.
Returns
TypeDescription
RouteSpec | NoneThe matching route spec, or ``None`` when unknown.
routes
def routes() -> tuple[RouteSpec, Ellipsis]

Return specs for every registered directed pair, sorted by id.


Relay protocol conversion engine module for Oridecon applications.

Provides the caller-owned relay registry and the public conversion engine behind their contract protocols.

Usage

from oridecon.ai.relay import RelayModule
@module(
imports=[RelayModule.configure()]
)
class AppModule(Module):
pass
from oridecon.ai.relay import RelayModule
@module(
imports=[RelayModule.configure()]
)
class AppModule(Module):
pass
configure
def configure(cls) -> DynamicModule

Create a RelayModule with the built-in converter routes.

Returns
TypeDescription
DynamicModuleA DynamicModule descriptor.
stub
def stub(
    cls,
    config: Any = None
) -> DynamicModule

Create a RelayModule suitable for unit and integration testing.

Uses the same in-memory registry and synchronous engine as configure; no credentials or I/O are involved.

Parameters
ParameterTypeDescription
`config`AnyOptional test configuration override; the relay module needs no configuration, so it is ignored.
Returns
TypeDescription
DynamicModuleA DynamicModule descriptor.

Static metadata for one directed conversion route.

Attributes: source: Source wire format. target: Target wire format. quality: Semantic closeness of the conversion. request_supported: Whether request conversion is available. response_supported: Whether response conversion is available. stream_supported: Whether stateful stream conversion is available. feature_loss_policy: Machine-readable loss reasons this route is expected to record, in order.

Properties: converter_id: Stable "<source>_to_<target>" identifier.

converter_id
property converter_id() -> str

Stable "<source>_to_<target>" identifier for this route.


convert_request_by_id
def convert_request_by_id(
    registry: RelayConverterRegistry,
    payload: RelayRequestPayload,
    converter_id: str,
    *,
    context: RelayConversionContext | None = None
) -> Result[RelayConvertResult[RelayRequestPayload], RelayError]
Convert a request through the route identified by ``converter_id``.
Parameters
ParameterTypeDescription
`registry`RelayConverterRegistryThe registry carrying the route.
`payload`RelayRequestPayloadThe source request DTO.
`converter_id`strA stable ``"_to_"`` identifier.
`context`RelayConversionContext | NoneOptional host conversion context.
Returns
TypeDescription
Result[RelayConvertResult[RelayRequestPayload], RelayError]A request conversion result, or a relay error.

convert_request_via
def convert_request_via(
    registry: RelayRegistryProtocol,
    payload: RelayRequestPayload,
    source: RelayFormat,
    target: RelayFormat,
    *,
    context: RelayConversionContext | None = None
) -> Result[RelayConvertResult[RelayRequestPayload], RelayError]
Convert a request through an explicit registry.
Parameters
ParameterTypeDescription
`registry`RelayRegistryProtocolThe registry to resolve the route from.
`payload`RelayRequestPayloadThe source request DTO.
`source`RelayFormatSource wire format.
`target`RelayFormatTarget wire format.
`context`RelayConversionContext | NoneOptional host conversion context.
Returns
TypeDescription
Result[RelayConvertResult[RelayRequestPayload], RelayError]A request conversion result, or a relay error.

convert_response_by_id
def convert_response_by_id(
    registry: RelayConverterRegistry,
    payload: RelayResponsePayload,
    converter_id: str,
    *,
    context: RelayConversionContext | None = None
) -> Result[RelayConvertResult[RelayResponsePayload], RelayError]
Convert a response through the route identified by ``converter_id``.
Parameters
ParameterTypeDescription
`registry`RelayConverterRegistryThe registry carrying the route.
`payload`RelayResponsePayloadThe source response DTO.
`converter_id`strA stable ``"_to_"`` identifier.
`context`RelayConversionContext | NoneOptional host conversion context.
Returns
TypeDescription
Result[RelayConvertResult[RelayResponsePayload], RelayError]A response conversion result, or a relay error.

convert_response_via
def convert_response_via(
    registry: RelayRegistryProtocol,
    payload: RelayResponsePayload,
    source: RelayFormat,
    target: RelayFormat,
    *,
    context: RelayConversionContext | None = None
) -> Result[RelayConvertResult[RelayResponsePayload], RelayError]
Convert a response through an explicit registry.
Parameters
ParameterTypeDescription
`registry`RelayRegistryProtocolThe registry to resolve the route from.
`payload`RelayResponsePayloadThe source response DTO.
`source`RelayFormatSource wire format.
`target`RelayFormatTarget wire format.
`context`RelayConversionContext | NoneOptional host conversion context.
Returns
TypeDescription
Result[RelayConvertResult[RelayResponsePayload], RelayError]A response conversion result, or a relay error.

malformed_payload
def malformed_payload(detail: str) -> RelayError
The wire payload did not match the expected shape.
Parameters
ParameterTypeDescription
`detail`strHuman-readable description of the malformed field.
Returns
TypeDescription
RelayErrorA ``RelayError`` with code ``malformed_payload``.

media_resolution_required
def media_resolution_required(detail: str) -> RelayError
URL media requires a resolver the host did not supply.
Parameters
ParameterTypeDescription
`detail`strThe media URL that cannot be resolved.
Returns
TypeDescription
RelayErrorA ``RelayError`` with code ``media_resolution_required``.

missing_required_option
def missing_required_option(detail: str) -> RelayError
A required field or host option is absent.
Parameters
ParameterTypeDescription
`detail`strWhich required option is missing.
Returns
TypeDescription
RelayErrorA ``RelayError`` with code ``missing_required_option``.

record_loss
def record_loss(
    context: ConversionContext,
    *,
    field: str,
    target: RelayFormat,
    reason: str,
    severity: str = 'warning'
) -> None
Record a semantic loss on the conversion context.

The engine copies the accumulated losses into the RelayConvertResult and surfaces warning/error losses as warnings.

Parameters
ParameterTypeDescription
`context`ConversionContextThe per-conversion context holding the loss sink.
`field`strSource wire field (or feature) that was dropped or adapted.
`target`RelayFormatTarget format the loss applies to.
`reason`strMachine-readable reason (e.g. ``json_mode_not_supported``).
`severity`str``error``, ``warning``, or ``info``.

route_quality
def route_quality(
    source: RelayFormat,
    target: RelayFormat
) -> ConversionQuality
Return the semantic-closeness quality for a directed pair.
Parameters
ParameterTypeDescription
`source`RelayFormatSource wire format.
`target`RelayFormatTarget wire format.
Returns
TypeDescription
ConversionQuality:data:`ConversionQuality.GOOD` for same-format conversion and for routes without a configured quality, otherwise the configured matrix value.

translate
def translate(
    exc: Exception,
    *,
    detail: str
) -> RelayError
Translate an unexpected exception into a stable error category.

RelayError passes through unchanged. DTO parsing failures (ValueError, TypeError, KeyError) become malformed_payload; any other exception becomes serialization_error.

Parameters
ParameterTypeDescription
`exc`ExceptionThe exception raised inside a mapper.
`detail`strContext describing what was being translated.
Returns
TypeDescription
RelayErrorA stable ``RelayError``.

unsupported_feature
def unsupported_feature(detail: str) -> RelayError
The source feature cannot be converted to the target.
Parameters
ParameterTypeDescription
`detail`strThe feature that could not be converted.
Returns
TypeDescription
RelayErrorA ``RelayError`` with code ``unsupported_feature``.

unsupported_format
def unsupported_format(detail: str) -> RelayError
The payload does not belong to this mapper's wire format.
Parameters
ParameterTypeDescription
`detail`strThe expected and actual payload shapes.
Returns
TypeDescription
RelayErrorA ``RelayError`` with code ``unsupported_format``.

warning_messages
def warning_messages(losses: Sequence[RelayLoss]) -> tuple[str, Ellipsis]
Render losses into stable warning strings.
Parameters
ParameterTypeDescription
`losses`Sequence[RelayLoss]Loss records accumulated during conversion.
Returns
TypeDescription
tuple[str, Ellipsis]One ``"field: reason (target, severity)"`` string per loss.