nemoguardrails.guardrails.guardrails_types

View as Markdown

Module Contents

Classes

NameDescription
RailCallRecordOne rail’s execution record, carried on RailResult for GenerationLog synthesis.
RailDirectionDirection of a rail check, used for logging.
RailResultWrapper-class around RailOutcome object with IORails-specific metadata
TimedLLMResponseAn LLM response paired with wall-clock start/finish timestamps and a monotonic duration.

Functions

NameDescription
_has_evidenceWhether a verdict value carries anything worth showing.
_metadata_evidenceRender a rail’s metadata as text, or None when it carries no evidence.
_rendered_evidenceRender one verdict value, flattening a sequence into a comma-separated list.
_set_request_idSet an explicit request ID (e.g., derived from an OTEL trace ID).
client_reasonRender a blocked rail’s explanation for the error payload sent to the caller.
current_user_turn_indexPosition of the turn being checked: the last user message that carries content.
display_reasonRender a blocked rail’s full explanation for a log line or a span.
get_request_idReturn the current per-request correlation ID.
last_user_contentReturn the content of the turn being checked, or "" as the library actions expect.
reset_request_idRestore the request ID ContextVar to its previous value.
rewrite_user_messageReturn messages with the turn last_user_content reads rewritten to text.
serialize_promptRender a chat message list to a role-labeled string for GenerationLog’s prompt.
set_new_request_idGenerate a random request ID, set it in the current context, and return the reset token.
truncateReturn str(text) truncated to max_len characters (default: LOG_CONTENT_TRUNCATE_LENGTH).

Data

LLMMessage

LLMMessages

LOG_CONTENT_TRUNCATE_LENGTH

REQUEST_ID_BYTES

REQUEST_ID_HEX_CHARS

_CONTENT_EVIDENCE_KEYS

_UNSPECIFIED_REASON

_VERDICT_DECISION_KEY

_VERDICT_FAILED_KEY

_request_id_var

API

class nemoguardrails.guardrails.guardrails_types.RailCallRecord(
flow: str,
rail_type: str,
is_safe: bool,
made_call: bool = False,
action_name: typing.Optional[str] = None,
return_value: typing.Any = None,
task: typing.Optional[str] = None,
request_id: typing.Optional[str] = None,
usage: typing.Optional[nemoguardrails.types.UsageInfo] = None,
llm_model_name: typing.Optional[str] = None,
llm_provider_name: typing.Optional[str] = None,
prompt: typing.Optional[str] = None,
completion: typing.Optional[str] = None,
started_at: typing.Optional[float] = None,
finished_at: typing.Optional[float] = None,
duration: typing.Optional[float] = None
)
Dataclass

One rail’s execution record, carried on RailResult for GenerationLog synthesis.

Captures what a single rail did — its verdict and the (at most one) model call it made — as engine-neutral data. IORails maps a RailCallRecord to an ActivatedRail (with a single synthetic ExecutedAction and LLMCallInfo); the raw usage/timing is kept here so this module stays free of the pydantic GenerationLog types. Tool rails that make no model call leave usage None.

action_name
Optional[str] = None
completion
Optional[str] = None
duration
Optional[float] = None
finished_at
Optional[float] = None
flow
str
is_safe
bool
llm_model_name
Optional[str] = None
llm_provider_name
Optional[str] = None
made_call
bool = False
prompt
Optional[str] = None
rail_type
str
request_id
Optional[str] = None
started_at
Optional[float] = None
task
Optional[str] = None
usage
Optional[UsageInfo] = None
class nemoguardrails.guardrails.guardrails_types.RailDirection

Bases: enum.Enum

Direction of a rail check, used for logging.

INPUT
= 'Input'
OUTPUT
= 'Output'
class nemoguardrails.guardrails.guardrails_types.RailResult(
outcome: nemoguardrails.actions.rail_outcome.RailOutcome,
triggered_rail: str | None = None,
records: tuple[nemoguardrails.guardrails.guardrails_types.RailCallRecord, ...] = ()
)
Dataclass

Wrapper-class around RailOutcome object with IORails-specific metadata

The verdict itself lives entirely in outcome, which is the single source of truth: is_safe, reason and return_value are derived views of it rather than a second copy that could drift. What this type adds is the aggregation RailOutcome has no concept of, because it belongs to running many rails: which one blocked (triggered_rail) and what every rail did (records).

records carries the per-rail execution records for every rail that ran in this check (not just the blocking one), so IORails can synthesize a GenerationLog. It is empty unless log collection is active, and it is log-capture data rather than part of the verdict, so it is excluded from equality (compare=False).

__hash__ is spelled out as None because RailOutcome is deliberately unhashable: without this a frozen dataclass would generate a __hash__ that raises from inside hash() instead of reporting this type as unhashable.

failed
bool

Whether this block came from a rail that raised rather than one that decided.

is_safe
bool

Whether the checked content may proceed.

outcome
RailOutcome
reason
str | None

The rail’s own explanation, when it authored one.

records
tuple[RailCallRecord, ...] = field(default=(), compare=False)
return_value
dict[str, Any]

The rail’s structured verdict, as the log’s ExecutedAction.return_value.

The verdict keys are applied last so they win: metadata is free-form evidence and a custom action may put an allowed or failed key in it, which must not be able to record a blocked rail as having allowed the content, nor forge a rail failure.

failed is always present, as allowed is, so a log consumer reads a verdict rather than inferring one from a missing key. Without it a rail that broke and a rail that decided to block are the same record, which is the distinction the client-facing message already draws.

triggered_rail
str | None = None
nemoguardrails.guardrails.guardrails_types.RailResult.allow(
reason: str | None = None,
metadata: collections.abc.Mapping[str, typing.Any] | None = None,
records: tuple[nemoguardrails.guardrails.guardrails_types.RailCallRecord, ...] = ()
) -> nemoguardrails.guardrails.guardrails_types.RailResult
classmethod

A result that lets the content through.

nemoguardrails.guardrails.guardrails_types.RailResult.block(
reason: str | None = None,
metadata: collections.abc.Mapping[str, typing.Any] | None = None,
triggered_rail: str | None = None,
records: tuple[nemoguardrails.guardrails.guardrails_types.RailCallRecord, ...] = ()
) -> nemoguardrails.guardrails.guardrails_types.RailResult
classmethod

A result that stops the content. Only a block names a triggering rail.

class nemoguardrails.guardrails.guardrails_types.TimedLLMResponse(
response: nemoguardrails.types.LLMResponse,
started_at: float,
finished_at: float,
duration: float
)
Dataclass

An LLM response paired with wall-clock start/finish timestamps and a monotonic duration.

Returned by IORails’ main-model call helper so the sequential and speculative paths both carry real timing into the generation RailCallRecord.

duration
float
finished_at
float
response
LLMResponse
started_at
float
nemoguardrails.guardrails.guardrails_types._has_evidence(
value: typing.Any
) -> bool

Whether a verdict value carries anything worth showing.

nemoguardrails.guardrails.guardrails_types._metadata_evidence(
metadata: typing.Any
) -> typing.Optional[str]

Render a rail’s metadata as text, or None when it carries no evidence.

nemoguardrails.guardrails.guardrails_types._rendered_evidence(
value: typing.Any
) -> str

Render one verdict value, flattening a sequence into a comma-separated list.

nemoguardrails.guardrails.guardrails_types._set_request_id(
request_id: str
) -> contextvars.Token[str]

Set an explicit request ID (e.g., derived from an OTEL trace ID).

Unlike set_new_request_id which generates a random ID, this accepts a caller-provided string. Returns the reset token for use with reset_request_id.

nemoguardrails.guardrails.guardrails_types.client_reason(
result: nemoguardrails.guardrails.guardrails_types.RailResult
) -> str

Render a blocked rail’s explanation for the error payload sent to the caller.

nemoguardrails.guardrails.guardrails_types.current_user_turn_index(
messages: nemoguardrails.guardrails.guardrails_types.LLMMessages
) -> typing.Optional[int]

Position of the turn being checked: the last user message that carries content.

nemoguardrails.guardrails.guardrails_types.display_reason(
result: nemoguardrails.guardrails.guardrails_types.RailResult
) -> str

Render a blocked rail’s full explanation for a log line or a span.

nemoguardrails.guardrails.guardrails_types.get_request_id() -> str

Return the current per-request correlation ID.

nemoguardrails.guardrails.guardrails_types.last_user_content(
messages: nemoguardrails.guardrails.guardrails_types.LLMMessages
) -> str

Return the content of the turn being checked, or "" as the library actions expect.

nemoguardrails.guardrails.guardrails_types.reset_request_id(
token: contextvars.Token[str]
) -> None

Restore the request ID ContextVar to its previous value.

nemoguardrails.guardrails.guardrails_types.rewrite_user_message(
messages: nemoguardrails.guardrails.guardrails_types.LLMMessages,
text: str
) -> nemoguardrails.guardrails.guardrails_types.LLMMessages

Return messages with the turn last_user_content reads rewritten to text.

Copied at both levels, because the caller’s own list reaches the engine by identity.

nemoguardrails.guardrails.guardrails_types.serialize_prompt(
messages: list[dict]
) -> str

Render a chat message list to a role-labeled string for GenerationLog’s prompt.

Content parity with LLMRails’ logged prompt, not byte-for-byte format parity: each message becomes "<role>: <content>". Non-content fields present on the message (name, tool_call_id, tool_calls, reasoning) are appended as a compact [key=value, ...] suffix so tool-call and reasoning-only turns are preserved rather than dropped. Messages are blank-line separated.

nemoguardrails.guardrails.guardrails_types.set_new_request_id() -> contextvars.Token[str]

Generate a random request ID, set it in the current context, and return the reset token.

nemoguardrails.guardrails.guardrails_types.truncate(
text: object,
max_len: int | None = None
) -> str

Return str(text) truncated to max_len characters (default: LOG_CONTENT_TRUNCATE_LENGTH).

nemoguardrails.guardrails.guardrails_types.LLMMessage: TypeAlias = dict[str, Any]
nemoguardrails.guardrails.guardrails_types.LLMMessages: TypeAlias = list[LLMMessage]
nemoguardrails.guardrails.guardrails_types.LOG_CONTENT_TRUNCATE_LENGTH = 200
nemoguardrails.guardrails.guardrails_types.REQUEST_ID_BYTES = 8
nemoguardrails.guardrails.guardrails_types.REQUEST_ID_HEX_CHARS = REQUEST_ID_BYTES * 2
nemoguardrails.guardrails.guardrails_types._CONTENT_EVIDENCE_KEYS = frozenset({'text', 'user_message', 'bot_message'})
nemoguardrails.guardrails.guardrails_types._UNSPECIFIED_REASON = 'unspecified'
nemoguardrails.guardrails.guardrails_types._VERDICT_DECISION_KEY = 'allowed'
nemoguardrails.guardrails.guardrails_types._VERDICT_FAILED_KEY = 'failed'
nemoguardrails.guardrails.guardrails_types._request_id_var: ContextVar[str] = ContextVar('request_id', default='no-req-id')