Skip to navigation

nemoguardrails.server.experimental.provider.projection_policy

View as MarkdownOpen in Claude

Field and object policies for provider payload projections.

Model declarations provide field coverage, guarded text locations, and exported contract schemas.

Module Contents

Classes

NameDescription
ArrayVariantIdentify one reviewed object branch in a heterogeneous array.
ObjectPolicyDescribe the reviewed boundary of one JSON object.
PolicyModelRequire declared fields to carry guard policy metadata.

Functions

NameDescription
_check_reasonRequire a structured reason such as core_capability.tool_content.
_fieldBuild Annotated field metadata while keeping defaults in assignments.
constrainedMark a field restricted by its type and optional Pydantic constraints.
disabledDeclare an unsupported feature as an omittable, null-only field.
export_payload_schemaExport a fresh, inline schema with object and field guard annotations.
field_coverageDerive disjoint runtime field inventories from one object’s declarations.
field_policyRead a field’s guard metadata, returning an empty mapping if absent.
guardedMark guarded content or a container leading to guarded content.
guarded_array_variantResolve the one text-bearing branch of a reviewed object union.
model_graphCollect the root and nested policy models in traversal order.
opaqueMark a declared field as provider-owned data outside guarded content.
payload_contractBuild runtime coverage metadata for a request or response projection.
policy_json_schemaDescribe default object validation without the contract’s union restrictions.
replacement_blockerReturn a subject’s replacement blocker after checking it names a reviewed sibling.
text_locationDerive one buffered text target directly from typed field declarations.

Data

CONTRACT_VERSION

EXTENSION

_FIELD_CONSTRAINTS

_REASON

_SOURCE_COMPONENT

API

class nemoguardrails.server.experimental.provider.projection_policy.ArrayVariant(
match: tuple[tuple[str, str | int | bool], ...],
cardinality: typing.Literal['any', 'at_most_one', 'exactly_one']
)
Dataclass

Identify one reviewed object branch in a heterogeneous array.

Match keys must be required singleton Literal fields of the owning model. Cardinality applies when a text binding selects this branch from an array, not when the object is validated in isolation. Non-text branches use ‘any’. The same declaration describes selection in exported guard contracts.

cardinality
Literal['any', 'at_most_one', 'exactly_one']
match
tuple[tuple[str, str | int | bool], ...]
nemoguardrails.server.experimental.provider.projection_policy.ArrayVariant.__post_init__() -> None

Reject ambiguous or unrepresentable selector declarations.

class nemoguardrails.server.experimental.provider.projection_policy.ObjectPolicy(
source: str | None = None,
opaque: tuple[str, ...] = (),
unknown_fields: typing.Literal['forbid', 'configurable'] = 'forbid',
)
Dataclass

Describe the reviewed boundary of one JSON object.

This metadata does not select guardrails, a deployment configuration, or a capability profile. Field-specific policy belongs on the field annotations.

opaque
tuple[str, ...] = ()

Reviewed passthrough fields not declared as Pydantic fields. Names must be unique and must not overlap declared fields.

source
str | None = None

Provider component schema name, without a JSON Pointer prefix. This is provenance metadata, not a schema lookup or validation step.

unknown_fields
Literal['forbid', 'configurable'] = 'forbid'

How unreviewed members are handled. “forbid” always rejects them. “configurable” rejects them unless validation explicitly allows unknown content fields, which is reserved for trusted configuration. Members listed in opaque are reviewed.

variant
ArrayVariant | None = None

Optional discriminator and selection cardinality when this model is a branch of a guarded heterogeneous array.

nemoguardrails.server.experimental.provider.projection_policy.ObjectPolicy.__post_init__() -> None

Reject values the exported contract format cannot represent.

class nemoguardrails.server.experimental.provider.projection_policy.PolicyModel()

Bases: BaseModel

Require declared fields to carry guard policy metadata.

Combine this base with the appropriate runtime projection base. At subclass creation it checks field classifications, opaque inventory overlap, disabled field defaults, and unsupported aliases. At validation it enforces the object’s unknown-field policy. It does not prove upstream field coverage or serialize arbitrary custom validators into the exported schema.

model_config
= ConfigDict(extra='allow')
policy
ObjectPolicy = ObjectPolicy()
nemoguardrails.server.experimental.provider.projection_policy.PolicyModel.__get_pydantic_json_schema__(
core_schema: pydantic_core.CoreSchema,
handler: pydantic.GetJsonSchemaHandler
) -> pydantic.json_schema.JsonSchemaValue
classmethod

Attach policy using model identity, independent of schema display titles.

Keep Pydantic’s references and validation assertions. Object closure describes default validation; trusted overrides and case-alias checks remain explicit guard annotations.

nemoguardrails.server.experimental.provider.projection_policy.PolicyModel.__pydantic_init_subclass__(
kwargs: typing.Any = {}
) -> None
classmethod

Check local policy consistency after Pydantic has assembled fields.

nemoguardrails.server.experimental.provider.projection_policy.PolicyModel.reject_coerced_variant_discriminators(
value: typing.Any
) -> typing.Any
classmethod

Keep parsed variant selection consistent with the original payload.

nemoguardrails.server.experimental.provider.projection_policy.PolicyModel.reject_unreviewed_fields(
info: pydantic.ValidationInfo
) -> typing_extensions.Self

Reject members outside the reviewed fields unless policy allows them.

A case variant of a reviewed name, such as Tools, is always rejected: some providers match member names case-insensitively, so it could reach a field this policy disables or inspects.

nemoguardrails.server.experimental.provider.projection_policy._check_reason(
reason: str
) -> None

Require a structured reason such as core_capability.tool_content.

nemoguardrails.server.experimental.provider.projection_policy._field(
metadata: dict[str, typing.Any],
constraints: dict[str, typing.Any]
) -> typing.Any

Build Annotated field metadata while keeping defaults in assignments.

nemoguardrails.server.experimental.provider.projection_policy.constrained(
reason: str | None = None,
constraints: typing.Any = {}
) -> typing.Any

Mark a field restricted by its type and optional Pydantic constraints.

The optional reason explains the restriction in the exported contract. This helper adds no restriction by itself; the annotation and constraints must express it. Defaults belong on the field assignment.

nemoguardrails.server.experimental.provider.projection_policy.disabled(
reason: str,
extension: bool = False
) -> typing.Any

Declare an unsupported feature as an omittable, null-only field.

Use field: Annotated[None, disabled(reason)] = None. Non-null values are rejected by the field type, and PolicyModel checks this declaration. A nonblank structured reason explains the restriction. Set extension for a locally recognized field outside the pinned provider schema.

nemoguardrails.server.experimental.provider.projection_policy.export_payload_schema(
projection_id: str
) -> dict[str, typing.Any]

Export a fresh, inline schema with object and field guard annotations.

This function does not validate the complete contract format, inspect an upstream provider schema, or capture arbitrary Python validator behavior. The operation exporter is responsible for format validation.

Parameters:

model
type[PolicyModel]

type[ PolicyModel ] — Trusted policy-annotated model to describe.

projection_id
str

Exported root title; the class name remains model metadata.

Returns: dict[str, Any]

A payload schema, not a complete operation contract.

Raises:

  • ValueError: Nested models are not policy-annotated, names collide, references recurse, or an anyOf union cannot be safely converted.

Derive disjoint runtime field inventories from one object’s declarations.

Local extensions occupy a separate inventory even when their annotation is constrained. The opaque inventory includes declared opaque attributes and ObjectPolicy.opaque names. This does not check an upstream schema.

nemoguardrails.server.experimental.provider.projection_policy.field_policy(
field: pydantic.fields.FieldInfo
) -> dict[str, typing.Any]

Read a field’s guard metadata, returning an empty mapping if absent.

The returned mapping may belong to the field; callers must not mutate it.

nemoguardrails.server.experimental.provider.projection_policy.guarded(
role: typing.Literal['user', 'assistant'] | None = None,
replaceable: bool | None = None,
blocked_by: str | None = None,
replacement_reason: str | None = None,
constraints: typing.Any = {}
) -> typing.Any

Mark guarded content or a container leading to guarded content.

Use inside Annotated and put defaults on the field assignment. Declaring replacement eligibility does not enable runtime replacement support.

Parameters:

role
Literal['user', 'assistant'] | NoneDefaults to None

Text subject role. Omit for structural container fields.

replaceable
bool | NoneDefaults to None

Whether the subject permits replacement. The buffered binding defaults to read-only when this is not declared.

blocked_by
str | NoneDefaults to None

Sibling field whose non-empty value prevents replacement.

replacement_reason
str | NoneDefaults to None

Structured reason for the replacement restriction.

**constraints
AnyDefaults to {}

min_length, max_length, pattern, ge, le, or strict. Format support is checked separately when exporting a complete guard contract; strictness has no JSON Schema keyword.

nemoguardrails.server.experimental.provider.projection_policy.guarded_array_variant(
annotation: typing.Any

Resolve the one text-bearing branch of a reviewed object union.

Every branch must declare a mutually exclusive discriminator. The selected branch has bounded cardinality; other branches must not hide guarded text. Return None for a non-union item, whose ordinary array bounds apply instead. No JSON Schema generation or provider lookup participates in binding.

nemoguardrails.server.experimental.provider.projection_policy.model_graph(

Collect the root and nested policy models in traversal order.

Models are keyed by class name. Reject nested models without policy and distinct models sharing a name. Repeated references are visited once; recursive schema export is rejected separately.

nemoguardrails.server.experimental.provider.projection_policy.opaque() -> typing.Any

Mark a declared field as provider-owned data outside guarded content.

Use field: Annotated[Any, opaque()] = None for an unconstrained optional value. ObjectPolicy.opaque is the alternative for reviewed fields that do not need a model attribute. Do not declare the same field in both places.

nemoguardrails.server.experimental.provider.projection_policy.payload_contract(
projection_id: str,
direction: typing.Literal['request', 'response'],

Build runtime coverage metadata for a request or response projection.

Parameters:

model
type[PolicyModel]

type[ PolicyModel ] — Policy-annotated root, with policy-annotated nested models.

projection_id
str

Stable identifier for this payload projection.

direction
Literal['request', 'response']

Whether the projection describes a request or response.

profile
PayloadCapabilityProfileDefaults to PayloadCapabilityProfile.SINGLE_TEXT_V1

PayloadCapabilityProfile — Framework-defined capability implemented by the runtime.

Returns: PayloadProjectionContract

Root and nested-model coverage, ready to attach in a binding module.

nemoguardrails.server.experimental.provider.projection_policy.policy_json_schema(
) -> dict[str, typing.Any]

Describe default object validation without the contract’s union restrictions.

Add reviewed opaque properties, default closure, and explicit object policy to the root and nested model definitions. Inline references so the schema can be embedded in an OpenAPI document without dangling definition paths; retain union semantics. Recursive models cannot be inlined and are rejected. The result is fresh; arbitrary Python validators are not serialized.

nemoguardrails.server.experimental.provider.projection_policy.replacement_blocker(
subject: dict[str, typing.Any]
) -> str | None

Return a subject’s replacement blocker after checking it names a reviewed sibling.

A misspelled blocker would never match a provider member and would silently allow replacement, so buffered and stream subjects both validate it.

Raises:

  • ValueError: The blocker is not a declared or reviewed opaque field of the model.

Derive one buffered text target directly from typed field declarations.

Follow guarded models and exactly-one-item lists without schema generation or contract-format conversion. Heterogeneous arrays use ObjectPolicy.variant to select exactly one text-bearing member. A nullable subject, or one without a minimum length, may hold no text.

Raises:

  • ValueError: A subject is missing or ambiguous, a guarded container is unsupported, or a replacement blocker is not a reviewed sibling.
nemoguardrails.server.experimental.provider.projection_policy.CONTRACT_VERSION = '1.0.0-alpha.1'
nemoguardrails.server.experimental.provider.projection_policy.EXTENSION = 'x-nemo-guardrails'
nemoguardrails.server.experimental.provider.projection_policy._FIELD_CONSTRAINTS = frozenset({'min_length', 'max_length', 'pattern', 'ge', 'le', 'strict'})
nemoguardrails.server.experimental.provider.projection_policy._REASON = re.compile('(core_capability|provider_integrity|projection_policy)\\.[a-z][a-z0-...
nemoguardrails.server.experimental.provider.projection_policy._SOURCE_COMPONENT = re.compile('[A-Za-z_][A-Za-z0-9._-]*')