Skip to navigation

Provider Codecs

View as MarkdownOpen in Claude

Use this guide when a framework integration needs NeMo Relay middleware, intercepts, or subscribers to reason about provider-specific LLM payloads through a stable annotated shape.

What You Build

You will attach request and response codecs to a managed LLM wrapper so that:

  • Request intercepts can work with normalized instructions, messages, model names, tools, generation parameters, and tagged provider-specific fields
  • The provider callback still receives the provider payload that the framework expects
  • Response subscribers can receive normalized response annotations without changing the caller-visible provider response

Before You Start

You need:

  • A framework LLM boundary that can call llm.execute, llm.stream_execute, llmCallExecute, typedLlmExecute, or llm_call_execute.
  • A provider payload that is JSON-compatible.
  • A matching built-in provider codec, or a custom codec that can preserve unmodeled provider fields.
  • Request intercepts or subscribers that benefit from normalized request or response data.

What Provider Codecs Are

A provider codec is a pure data translator at the NeMo Relay LLM boundary.

  • An LLM request codec converts a raw provider request into a normalized annotated request, then encodes any annotated edits back into the original provider request.
  • An LLM response codec converts a raw provider response into a normalized response annotation for lifecycle events.

Provider codecs let framework code keep using provider-native payloads while NeMo Relay middleware works against a shared annotated model. For application-facing type conversion, use Using Codecs.

Inspect Normalized Content in Rust

Use AnnotatedLlmRequest.last_message() to select exactly the final supplied request item. Use AnnotatedLlmResponse.output() for the current response’s normalized content and tool calls. A request can contain assistant/tool history from earlier turns; a codec does not accumulate history between calls.

Both return a borrowed MessageView from nemo_relay_types::codec::content. The view’s root() identifies the normalized selection even when it has no parts. source() borrows the selected message, content, or response through ContentSource. To keep the selection after the annotation is dropped, call view.retain(). Its RetainedContent result owns the selected data. Calling view() on that result preserves the original request index and lets you traverse parts on demand. The in-process Python and Node.js bindings use this storage for their read-only views.

Message.content_view() and MessageContent.content_view() provide the same access for arbitrary history items and separate instructions.

use nemo_relay_types::codec::content::ContentKind;
use nemo_relay_types::codec::request::AnnotatedLlmRequest;
fn inspect(request: &AnnotatedLlmRequest) {
if let Some(view) = request.last_message() {
for entry in view.parts() {
match entry.kind {
ContentKind::Text(text) | ContentKind::Refusal(text) => println!("{text}"),
ContentKind::ToolCall(call) => println!("tool: {}", call.name),
_ => {}
}
}
if let Some(text) = view.text() {
println!("{text}");
}
}
}
  • parts() preserves typed text, refusals, tool calls/results, media, and opaque provider-native parts. Tool arguments retain their string or JSON representation. Tool-result messages yield a typed result containing their entire payload.
  • Each entry has a location with a normalized root, field, and optional array index. Locations describe the current source, not stable edit handles or original provider-wire offsets.
  • text_parts() yields borrowed text/refusal strings. It does not render tool arguments or results, recursively scan JSON, or include reasoning/media. Existing shallow native text/refusal fallbacks remain supported.
  • text() returns None when no eligible parts exist. It borrows one string and joins multiple strings with newlines, preserving whitespace and empty parts.
  • Separate tool calls follow message content. This order reflects normalized fields, not original provider ordering. Some decoders already combine text blocks; for example, Anthropic response text blocks become one joined string.

Known OpenAI Chat, OpenAI Responses, and Anthropic Messages request messages can remain provider-native when they contain extension fields. Their read views inspect recognized content strings or arrays in place, and the request helpers recognize their user/system/developer roles where supported by that provider. For example, an OpenAI Chat user message with content: "hello" and an extra provider field still yields "hello" from last_user_message(). For native OpenAI Chat assistant history, a string at value.refusal follows content, including an empty refusal. Entries from value.tool_calls follow the refusal and retain their original array indices. Their location fields are native_refusal and native_tool_calls. Function arguments stay strings. The native annotation, extension fields, and codec round-trip remain unchanged. Unknown message envelopes stay opaque; tool payloads and arbitrary nested metadata are not searched for text.

Migrate Existing Text Helpers

The Rust methods system_prompt(), last_user_message(), and response_text() now return Option<Cow<'_, str>> instead of Option<&str>. Use .as_deref() on an existing result to borrow its text, or .map(Cow::into_owned) to retain an owned string. A joined result owns its string, so keep that result alive while borrowing from it.

All three methods now include every text/refusal part of their selected item, joined with newlines. system_prompt() selects instructions when present, otherwise the first system/developer item. last_user_message() selects the last user item. Neither skips a selected textless item to find earlier or later text. response_text() reads the current output and excludes tool content.

Python’s existing methods inherit these extraction and selection behaviors and continue to return str | None. The views read existing annotations and preserve provider wire payloads. The OpenAI Chat response decoder now represents a response containing both text and a refusal as typed parts at /message. For selector examples, see Update OpenAI Response Redaction Policies.

Python Content Snapshots

Python exposes the same typed traversal through MessageView in nemo_relay.codecs:

from nemo_relay import AnnotatedLLMRequest
from nemo_relay.codecs import MessageView
request = AnnotatedLLMRequest([
{"role": "user", "content": [
{"type": "text", "text": "hello"},
{"type": "refusal", "refusal": "cannot help"},
]},
])
view = request.last_message()
if view is not None:
assert view.text() == "hello\ncannot help"
for entry in view.parts():
print(entry.kind, entry.location.field, entry.location.index)
# Arbitrary normalized content can be inspected independently of an annotation.
assert MessageView.from_content("").text() == ""

Use request.message(index) for any history item, including negative Python indices. Out-of-range indices raise IndexError. request.instructions_view() selects only top-level instructions, and response.output() selects the current message and separate tool calls. Empty request history and absent instructions return None; response output always returns a view, even without parts. MessageView.from_message(message) accepts a normalized message dictionary and preserves its role, including tool-result semantics. from_content(content) accepts a normalized string or content-part list without a message role.

Ownership: selection copies the selected content and tool calls into a Rust-owned snapshot. It does not copy the rest of the history or response metadata. Iterators, entries, tool views, and payload views share that snapshot and remain usable after the annotation or parent view is deleted. Later edits to the annotation do not change an existing snapshot. A retained entry can keep the entire selected snapshot alive. These are read-only snapshots rather than zero-copy borrows of a mutable Python annotation.

Python and Node.js iterators retain independent forward-only Rust cursors. Traversing all parts takes linear time; retained entries keep their source position for constant-time lookup without copying payloads. Rust callers that own their source storage can use ContentCursor with next_part(view) or next_text(view) for the same lifetime-independent traversal state. Use a separate cursor for each immutable selected view.

Strings returned by text(), text_parts(), and entry properties are Python-owned. Media/native entry.value and tool payload.value create independent Python values when accessed; editing a returned dictionary or list changes neither the snapshot nor the annotation. No tool JSON string is parsed or JSON value rendered into text during traversal.

entry.kind distinguishes text, refusal, tool_call, tool_result, image_url, image, audio, file, and provider_native. An unrecognized future kind is reported as unknown. Explicit text/refusals use entry.text. Calls expose entry.tool_call with id, call_id, name, and arguments; results expose entry.tool_result with id, call_id, name, is_error, and payload. Both argument and result payload views expose kind (null, string, json, or content) and value. A JSON string retains kind json. Native entries also expose provider and native_kind. Inapplicable properties return None.

Locations expose root, message_index, field, and index. A request-selected item retains its nonnegative history index; standalone views have no history index. Locations describe the snapshot’s normalized source, not stable editing handles or original provider offsets. Default text extraction follows the Rust rules above, including exclusions and supported shallow native fallbacks.

The standalone Python worker SDK obtains equivalent typed snapshots through one Rust-host RPC per selection. Annotations remain dictionaries; helpers are async module functions such as await codecs.last_message(runtime, request) and await codecs.response_text(runtime, response). Reads on returned snapshots are local. Python does not duplicate Rust selection or extraction policies. Refer to Python worker content access for transport ownership and older-host behavior.

Node.js and TypeScript Content Snapshots

Import the codecs namespace from the main nemo-relay-node entry point. Pass normalized annotations returned by codec decoding or attached to runtime events:

import { codecs } from 'nemo-relay-node';
const annotation = {
messages: [{
role: 'assistant',
content: [
{ type: 'text', text: 'Checking the forecast.' },
{ type: 'tool_use', id: 'c1', name: 'weather', input: { city: 'Boston' } },
],
}],
};
const view = codecs.lastMessage(annotation);
if (view !== null) {
for (const entry of view.parts()) {
if (entry.kind === 'tool_call') {
console.log(entry.toolCall.name, entry.toolCall.arguments.kind);
console.log(entry.toolCall.arguments.value);
}
}
console.log(view.text()); // Checking the forecast.
}

lastMessage(request) selects exactly the final item; message(request, index) supports negative indices and raises RangeError for out-of-range or noninteger indices. instructionsView(request) selects only top-level instructions. output(response) views the current message and separate tool calls, including textless output. Empty history and absent instructions return null; output always returns a view. Use MessageView.fromMessage(message) or MessageView.fromContent(content) for standalone normalized data.

Views expose parts(), textParts(), and text(). The ContentEntry union is discriminated by kind: text/refusals expose text, calls expose toolCall, results expose toolResult, and media/native entries expose value. Native entries also expose provider and nativeKind. Calls provide id, callId, name, and arguments; results provide id, callId, name, isError, and payload. Payload views preserve the null, string, json, or content representation. Argument strings are not parsed, and JSON values are not rendered into text.

Locations expose root, messageIndex, field, and index. Their discriminator values retain normalized names such as request_message, tool_calls, and native_content. Separate tool calls follow message content without claiming to reconstruct provider-wire order. Locations are read-time snapshot positions, not stable editing handles.

Ownership: selection copies only the selected message/content/output into Rust-owned storage. It leaves the remaining history and response metadata out of the snapshot. Iterators, structured entries, and payload views retain that storage after their original annotation or parent view becomes unreachable. Later edits to an annotation do not change existing views. Views, entries, locations, and tool/payload descriptors are read-only. Accessing a media/native value or tool payload value creates an independent JavaScript value; editing that returned object or array changes neither the snapshot nor the annotation. Strings are JavaScript-owned immutable values. A retained entry can keep the selected snapshot alive.

systemPrompt(request), lastUserMessage(request), and responseText(response) provide the named text helpers with the same selection rules as Rust and Python. Default text includes text/refusals and supported shallow native fallbacks; tools, reasoning, media, and arbitrary nested metadata are excluded. No eligible text yields null, an explicit empty string yields "", and joining preserves whitespace and empty parts. Selection never searches past a selected textless item. Codec decoding and encoding continue to use normalized JSON objects; these helpers add no mutable redaction or live streaming extraction.

C content snapshots

The experimental C ABI accepts normalized JSON from a codec or runtime event. Call nemo_relay_inspect_llm_content_json with a source and selection from nemo_relay.h. Requests support last message, indexed message (including negative indices), instructions, system prompt, and last user message. Responses support output. Standalone messages and content support all parts. Only indexed message selection reads the signed index argument.

This example runs inside a response sanitizer callback with a resolved codec:

#include "nemo_relay.h"
#include <stdio.h>
void inspect_response(const FfiLlmSanitizeResponseCodec *codec, const char *wire_json) {
char *annotation = nemo_relay_llm_sanitize_response_codec_decode(codec, wire_json);
if (annotation == NULL) {
fprintf(stderr, "%s\n", nemo_relay_last_error());
return;
}
char *snapshot = NULL;
NemoRelayStatus status = nemo_relay_inspect_llm_content_json(
NEMO_RELAY_CONTENT_SOURCE_RESPONSE, annotation,
NEMO_RELAY_CONTENT_SELECT_OUTPUT, 0, &snapshot);
if (status != NEMO_RELAY_STATUS_OK) {
fprintf(stderr, "%s\n", nemo_relay_last_error());
}
nemo_relay_string_free(annotation);
if (snapshot != NULL) {
puts(snapshot);
nemo_relay_string_free(snapshot);
}
}

On success, an absent selection sets the output pointer to null. A selected item returns its own JSON snapshot, including when it contains no text. Each snapshot contains ordered parts and text_parts arrays. Each part contains:

  • location: the normalized root, field, nullable part index, and a message_index for request-message roots.
  • kind: text, refusal, tool_call, tool_result, image_url, image, audio, file, or provider_native.
  • value: the text/refusal string, media value, typed tool object, or native object with provider, kind, and value. Tool arguments and result payloads carry their own kind (null, string, json, or content). The null kind omits its value. A json payload can explicitly contain null.

Join text_parts with newlines for display. An empty array means no eligible text. A single empty string represents explicitly empty text. On failure, the output pointer is null. Read nemo_relay_last_error() on the calling thread.

Go content snapshots

The experimental Go binding accepts json.RawMessage annotations. Use InspectLLMContent after decoding in a sanitizer callback, or pass a retained normalized annotation directly. The first argument identifies the input and the third selects the view. The signed index applies to ContentSelectMessage.

import (
"encoding/json"
relay "github.com/NVIDIA/NeMo-Relay/go/nemo_relay"
)
func responseText(codec *relay.LLMResponseSanitizeCodec, wire json.RawMessage) (string, bool, error) {
annotation, err := codec.Decode(wire)
if err != nil {
return "", false, err
}
snapshot, err := relay.InspectLLMContent(relay.ContentSourceResponse, annotation, relay.ContentSelectOutput, 0)
if err != nil {
return "", false, err
}
text, present := snapshot.Text()
return text, present, nil
}

An absent selection returns (nil, nil). A selected tool-only message has a snapshot with typed Parts, and its Text() returns ("", false). An explicitly empty text part returns ("", true). The snapshot and its entries belong to Go and can outlive the annotation and the callback. Tool arguments, result payloads, and opaque provider values retain their JSON representations in json.RawMessage.

How Provider Codecs Work

When a managed LLM call has a request codec:

  1. NeMo Relay calls decode before LLM request intercepts run.
  2. Request intercepts receive both the raw request and the annotated request.
  3. Intercepts edit provider-body fields through the annotated request and may edit transport headers through the raw request. Raw request.content is read-only while the codec is active.
  4. NeMo Relay uses the request codec to merge the annotated request into the original raw request.
  5. Execution intercepts and the provider callback receive the encoded provider request.

If a codec-aware intercept changes raw request.content or omits the returned annotation, Relay rejects the outcome before creating the LLM lifecycle. When no request codec is active, the raw request remains fully writable and is the provider-visible source of truth.

Gateway interceptors must preserve the request’s effective stream mode. The gateway chooses buffered or streaming response handling before request intercepts run and rejects changes between those modes before contacting the provider.

When a managed LLM call has a response codec, NeMo Relay decodes the raw provider response for observability and attaches the result to the emitted LLM end event. The response codec does not rewrite the value returned to the application. Use Provider Response Codecs for response-only behavior and custom response codec examples.

Manual lifecycle calls can also use a request codec. In Python, pass codec to llm.call(). In Node.js, pass both codecDecode and codecEncode to llmCall(), after the optional timestamp. The decode callback receives the request. The encode callback receives an object with annotated and original fields. In Rust, use LlmCallParams::builder().codec(...).

Manual calls record work that the application runs itself. They do not run request or execution intercepts. Set the response codec for manual Rust calls with LlmCallEndParams::builder().response_codec(...).

The request codec helps sanitizers redact private data. Relay also uses it to create or update the request annotation after sanitization. These changes affect only the copy saved in telemetry. The request sent to the provider stays the same.

Rules for personally identifiable information (PII) need a codec when they target normalized fields. These fields use Relay’s common request and response format. If the call has no codec and the PII settings have no matching fallback codec, Relay leaves the payload out of telemetry.

The built-in codecs guarantee encode(decode(original), original) == original at the JSON-value level. Their encoders compare an edited annotation with a decoded baseline and patch only changed fields. As a result, unchanged string-versus-block content, explicit nulls, legacy field names, ordered input items, metadata, and unknown fields remain untouched. Removing an unknown top-level key from extra removes it from the provider payload; adding or changing a key overlays it.

During a managed Rust call, the runtime passes the decoded request to LlmCodec::encode_with_baseline. Built-in codecs use this baseline instead of decoding the same request again. Custom Rust codecs can also use this method. The default calls encode, so existing codecs still work.

Use a baseline from the same codec and the same raw request body. Do not edit the baseline or change that raw body after decoding. Request headers can change while middleware runs.

The runtime passes ownership of the request to encode_owned_with_baseline. The default calls encode_with_baseline. It then adds the original request headers to the result. If a header appears in both, it keeps the original request’s value. An override can move the request body or keep it for later use.

Editing Arrays and Mappings

Request intercepts can change several array entries at a time. You can add, remove, reorder, or replace entries. You can also replace the whole array. A mapping, such as a JSON object, stores values by key. You can add, remove, or change those values, including nested arrays and objects. You can also set a value to null. All edits must be valid for the annotated request and the target provider.

Relay keeps provider fields on unchanged entries. It can also keep them on edited tool calls and results by matching their call IDs. Relay can match by ID only when that ID identifies one entry of the same kind in each version. For example, if you edit and reorder results a and b, each keeps its own provider fields. A new result c uses only the fields you supply.

Gemini can attach provider data, such as thoughtSignature, to a call. Relay keeps that data on surviving calls with a clear ID match. This still works when you change the call list or move calls between assistant messages. New calls do not inherit fields from old calls.

Relay treats entries with no match as replacements. They use only the values you return, without hidden fields from the original entries. For a single edit, Relay can keep fields from the same array position. This requires the array’s size and order to stay the same. Relay does not match objects in arbitrary JSON arrays by a generic id field.

For a mapping {"a": 1, "b": 2}, returning {"a": 10, "c": null} changes a, removes b, and adds c. Relay keeps provider fields that were missing from the original annotation.

Use the annotated request surfaces according to their ownership:

  • instructions for Anthropic system or OpenAI Responses instructions.
  • Portable messages, content parts, function calls and results, tools, and tool_choice when the component has shared semantics.
  • Tagged api_specific fields for modeled controls that belong to Anthropic Messages, OpenAI Chat Completions, OpenAI Responses, or OCI Generative AI.
  • { provider, kind, value } native components for provider-only input items, blocks, tools, tool choices, and future union members. value is the exact provider JSON.
  • Top-level extra only for unknown future fields.

Provider-native components are intentionally surface-bound. If an intercept places an Anthropic native block in an OpenAI request, or makes a portable edit that the target API cannot encode, Relay returns an explicit error before the provider callback.

Built-in Provider Codecs

Use the built-in provider codecs when the framework payload already matches a supported provider API:

  • OpenAIChatCodec: OpenAI Chat Completions-compatible requests and responses.
  • OpenAIResponsesCodec: OpenAI Responses-compatible requests and responses.
  • AnthropicMessagesCodec: Anthropic Messages-compatible requests and responses.
  • OCIGenAIChatCodec: OCI Generative AI chat-compatible requests and responses in the GENERIC, COHERE, and COHEREV2 API formats.
  • GeminiGenerateContentCodec: Gemini generateContent-compatible requests and responses.

Provider Codec Roles

Provider codecs have separate request and response roles:

  • LlmCodec decodes provider-specific requests into an annotated request form and encodes edits back into the provider request.
  • LlmResponseCodec decodes raw provider responses into annotated response data for lifecycle events.

The built-in provider codecs expose the same core methods:

CodecPython ImportNode.js ImportMethods
OpenAI Chatnemo_relay.codecs.OpenAIChatCodecOpenAIChatCodec from nemo-relay-nodedecode, encode, decode_response / decodeResponse
OpenAI Responsesnemo_relay.codecs.OpenAIResponsesCodecOpenAIResponsesCodec from nemo-relay-nodedecode, encode, decode_response / decodeResponse
Anthropic Messagesnemo_relay.codecs.AnthropicMessagesCodecAnthropicMessagesCodec from nemo-relay-nodedecode, encode, decode_response / decodeResponse
OCI Generative AI chatnemo_relay.codecs.OCIGenAIChatCodecOCIGenAIChatCodec from nemo-relay-nodedecode, encode, decode_response / decodeResponse
Gemini generateContentnemo_relay.codecs.GeminiGenerateContentCodecGeminiGenerateContentCodec from nemo-relay-nodedecode, encode, decode_response / decodeResponse

Choose the provider codec that matches the payload shape the framework already sends to the provider. Do not translate to a different provider shape only to make the codec fit.

The nemo-relay gateway selects the matching request codec automatically on the provider generation routes it proxies: /v1/messages, /v1/chat/completions, and /v1/responses, for both buffered and streaming calls. Gemini generateContent and OCI Generative AI chat do not yet have gateway routes, so use GeminiGenerateContentCodec or OCIGenAIChatCodec directly when a framework sends those payload shapes. Count-token, model, probe, and non-LLM passthrough routes do not use request codecs.

Example: Add a System Message with a Provider Codec

This example uses a request intercept to edit the normalized request. The codec writes the edited messages back into the provider payload before the provider callback runs.

import nemo_relay
from nemo_relay import LLMRequest
from nemo_relay.codecs import OpenAIChatCodec
def add_system_message(
_name: str,
request: LLMRequest,
annotated: nemo_relay.AnnotatedLLMRequest | None,
) -> nemo_relay.LLMRequestInterceptOutcome:
if annotated is None:
return nemo_relay.LLMRequestInterceptOutcome(request)
# Attributes of the annotated request can be re-assigned, but cannot be modified in-place.
# For example `annotated.messages.append(...)` would not work, but re-assigning
# `annotated.messages = annotated.messages + [...]` does work.
annotated.messages = [
{"role": "system", "content": "Answer with concise technical detail."},
*annotated.messages,
]
return nemo_relay.LLMRequestInterceptOutcome(request, annotated)
nemo_relay.intercepts.register_llm_request(
"framework.add_system_message",
10,
False,
add_system_message,
)
async def invoke_provider(request: LLMRequest) -> dict[str, object]:
content = request.content
if not isinstance(content, dict):
raise TypeError("Provider request content must be an object")
return {
"id": "chatcmpl-demo",
"model": content["model"],
"choices": [
{"message": {"role": "assistant", "content": "Codec-enabled response."}},
],
}
codec = OpenAIChatCodec()
request = LLMRequest(
{},
{
"model": "gpt-4o-mini",
"messages": [{"role": "user", "content": "Explain scopes."}],
"temperature": 0.2,
},
)
response = await nemo_relay.llm.execute(
"openai-chat",
request,
invoke_provider,
model_name="gpt-4o-mini",
codec=codec,
response_codec=codec,
)

Example: Edit Provider-Specific and Native Data

The tagged api_specific object is mutable. Python getters return JSON values, so retrieve, edit, and reassign the value. The same reassignment pattern works for a provider-native component inside messages.

def tune_responses_request(
_name: str,
request: LLMRequest,
annotated: nemo_relay.AnnotatedLLMRequest | None,
) -> nemo_relay.LLMRequestInterceptOutcome:
if annotated is None:
return nemo_relay.LLMRequestInterceptOutcome(request)
api_specific = dict(annotated.api_specific or {})
if api_specific.get("api") == "openai_responses":
api_specific["background"] = True
api_specific["stream_options"] = {"include_obfuscation": False}
annotated.api_specific = api_specific
messages = list(annotated.messages)
for index, item in enumerate(messages):
if (
item.get("role") == "provider_native"
and item.get("provider") == "openai_responses"
and item.get("kind") == "reasoning"
):
native_value = dict(item["value"])
native_value["encrypted_content"] = "updated-ciphertext"
messages[index] = {**item, "value": native_value}
annotated.messages = messages
# request.headers remains mutable; request.content is read-only here.
request.headers["x-request-policy"] = "codec-aware"
return nemo_relay.LLMRequestInterceptOutcome(request, annotated)

Native values are not normalized across providers. Keep the provider tag unchanged unless you also replace the entire component with a representation that the target codec owns.

Codec-Owned Redaction in Rust

Request and response codecs can opt into two separate redaction operations. The PII component selects fields and applies detection and replacement policy. The active codec owns provider formatting and decides whether it can safely represent the result.

OperationInputsGuarantee
edit_request / edit_responseOriginal provider payload and NormalizedEditsApply changes at original source positions, preserve unrelated fields, and verify the normalized result.
project_request / project_responseApproved sanitized annotation onlyConstruct clean trajectory output without restoring fields from the original provider payload.
Unsupported or unsafe Unsupported or unsafe Original provider payload Active codec decodes Normalized baseline PII detection and policy Sanitized normalized data NormalizedEdits: original array slots Codec source-aware editor Verified sanitized provider payload Codec clean projector Clean trajectory payload Omit payload

LlmCodec::redaction() returns an optional LlmRequestRedaction capability. LlmResponseCodec::redaction() returns an optional LlmResponseRedaction capability. Each operation defaults to Ok(None), so a custom Rust codec can implement editing, projection, or both. Runtime and opaque codec identities can opt in; a built-in identity alone does not grant support. Codecs that implement only the existing decode and encode methods still compile, but normalized PII sanitization omits their payloads until they opt in. Generic raw JSON policies continue to operate independently of these capabilities.

NormalizedEdits borrows the baseline and sanitized serialized annotations. Its array coordinates refer to the baseline: removing an array entry leaves a null slot, and removing an object field deletes the key. Keep array lengths and order through the sanitizer handoff. The codec validates the baseline and performs any supported compaction after mapping edits to provider locations. These coordinates are local to one operation, not stable edit handles.

Set require_complete_output when the policy covers normalized output or provider-specific output fields, even if the first normalized result has no matching content. A codec must cover unmodeled alternatives or omit the payload. Built-in editors reject extra choices or candidates in this case.

The OpenAI Responses editor supports removal of complete normalized text and refusal parts, retaining the surviving blocks’ original provider metadata. Deleting required fields, compacting arrays before handoff, and ambiguous request-part removals fail closed. Provider decoders that combine text blocks retain their existing normalized representation.

Clean projection accepts data already approved by the caller’s policy. It has no original wire payload parameter and must not retrieve retained source data. Request projections clear headers; built-in response projections exclude opaque native content and extras and emit empty tool argument objects.

Rust codecs can implement each operation independently. A Python request codec can set supports_request_redaction = True when its encoder preserves source positions and unrelated provider fields. Relay verifies the edited request by decoding it again. Google ADK uses this opt-in. If edits to repeated function calls leave multiple possible sources for part metadata such as a thought signature, the ADK encoder rejects the edit and Relay omits the published request payload. Python response codecs and Node.js, C, and worker-defined custom codecs have no opt-in yet. Built-in codec handles use the Rust implementation. This API sanitizes observability payloads; it does not rewrite caller-visible requests or responses.

Example: Write a Custom Framework Codec

Use a custom codec when a framework uses a payload shape that does not directly match a built-in provider format. The codec decodes the framework shape into AnnotatedLLMRequest, and encodes edits back into the framework shape.

from nemo_relay import AnnotatedLLMRequest, LLMRequest
from nemo_relay.codecs import LlmCodec
class FrameworkChatCodec(LlmCodec):
def decode(self, request: LLMRequest) -> AnnotatedLLMRequest:
content = request.content
if not isinstance(content, dict):
raise TypeError("Framework request content must be an object")
params = {}
if "temperature" in content:
params["temperature"] = content["temperature"]
return AnnotatedLLMRequest(
content.get("turns", []),
model=content.get("model_name"),
params=params or None,
tools=content.get("tool_specs"),
extra={"tenant_id": content.get("tenant_id")},
)
def encode(self, annotated: AnnotatedLLMRequest, original: LLMRequest) -> LLMRequest:
original_content = original.content
if not isinstance(original_content, dict):
raise TypeError("Framework request content must be an object")
content = {
**original_content,
"turns": annotated.messages,
}
if annotated.model is not None:
content["model_name"] = annotated.model
if annotated.params:
content.update(annotated.params)
if annotated.tools is not None:
content["tool_specs"] = annotated.tools
return LLMRequest(original.headers, content)

Validation Checklist

Use this checklist to confirm the implementation preserves the expected runtime contract.

  • Intercepts receive annotated only when the managed call supplies a request codec.
  • An unchanged annotation encodes to the exact original JSON value.
  • Built-in codecs keep provider fields on unchanged entries and on calls or results with a clear ID match.
  • Built-in codecs treat entries with no match as replacements. These entries use only the fields you supply.
  • Provider-specific edits use api_specific; extra is limited to unknown future top-level fields.
  • Provider-mismatched native components fail before the provider callback.
  • Response codecs are used only for event annotations, not caller-visible response rewriting.
  • Codec implementations are pure data transforms and do not perform provider I/O.
  • Framework-owned clients, sockets, streams, callbacks, and file handles stay outside codec results.

Next Steps

Use these links to continue from this workflow into the next related task.