> This page is for NeMo Relay, version v1.0.0.
> For other versions, use one of these documentation indexes:
> - Latest (v0.11.2) (default): https://docs.nvidia.com/nemo/relay/latest/llms.txt
> - dev: https://docs.nvidia.com/nemo/relay/dev/llms.txt
> - v1.0.0: https://docs.nvidia.com/nemo/relay/v1.0.0/llms.txt
> - v0.11.2: https://docs.nvidia.com/nemo/relay/v0.11.2/llms.txt
> - v0.10.4: https://docs.nvidia.com/nemo/relay/v0.10.4/llms.txt
> - v0.9.4: https://docs.nvidia.com/nemo/relay/v0.9.4/llms.txt
> - v0.8.4: https://docs.nvidia.com/nemo/relay/v0.8.4/llms.txt

> For clean Markdown of any page, append .md to the page URL. For a task-oriented documentation index, fetch https://docs.nvidia.com/nemo/relay/llms.txt. Use the documentation version matching the installed NeMo Relay package: latest follows the latest stable release, vX.Y.Z identifies a retained release snapshot, and dev documents development changes. Preserve the selected version when following links; do not mix examples or API contracts from different versions. Fetch the relevant section's /llms.txt before individual pages instead of loading a complete version index.

# Provider Response Codecs and Model Pricing

> Normalize LLM response data with provider codecs and configure model pricing estimates.

Use this guide when subscribers, exporters, or diagnostics need a provider-neutral view of raw LLM responses.

## What You Build

You will attach a response codec to a managed LLM wrapper so NeMo Relay can decode provider responses into `AnnotatedLLMResponse` data for LLM end events.

Response codecs are observability-only:

* They do not rewrite the value returned to the application.
* They do not run response middleware.
* They attach normalized response data to lifecycle events for subscribers and exporters.
* Decode failures are non-fatal. The LLM call still returns the provider response, and Relay emits the end event without an annotation.

## Before You Start

You need:

* A managed LLM boundary from [Wrap LLM Calls](/nemo/relay/v1.0.0/integrate-into-frameworks/wrap-llm-calls).
* A raw provider response that is JSON-compatible.
* A built-in response codec or a custom response codec for the provider response shape.
* A subscriber or exporter that consumes `annotated_response` from LLM end events.

## What Response Codecs Decode

Response codecs normalize provider output into fields that subscribers can inspect consistently:

| Field           | Purpose                                                                                                                                                                                               |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`            | Provider response identifier.                                                                                                                                                                         |
| `model`         | Model that served the request, when the provider returns it.                                                                                                                                          |
| `message`       | Primary assistant message content.                                                                                                                                                                    |
| `tool_calls`    | Tool calls requested by the model.                                                                                                                                                                    |
| `finish_reason` | Normalized completion reason, such as `complete`, `length`, `tool_use`, or `content_filter`.                                                                                                          |
| `usage`         | Token accounting, including cache-read and cache-write counts when available. It can also include normalized `cost` when the provider reports cost or Relay can estimate it from known model pricing. |
| `api_specific`  | Provider-specific fields that do not fit the common model.                                                                                                                                            |
| `extra`         | Additional unmodeled response fields.                                                                                                                                                                 |

Use these annotations for observability, export, and debugging. Keep business logic that changes the caller-visible response in the framework or provider adapter, not in the response codec.

OpenAI Chat's structured `message.refusal` and OpenAI Responses' `refusal`
content blocks are normalized as `ContentPart::Refusal` entries in `message`.
When ordinary text and refusals occur together, the normalized message is a
parts array preserving their kinds. Chat text precedes its separate refusal
field; Responses preserves content-block order. Text-only responses retain
their existing string representation.

`response_text()` includes both text and refusal parts, joined with newlines.
Null or missing refusals add no part; explicit empty refusal strings remain
present. Chat's streaming collector accumulates `delta.refusal`; Responses
retains provisional refusal deltas and replaces them with completed content
parts, output items, or the terminal snapshot when available. Completion reasons,
usage, and tool calls remain separate.

Gemini streaming aggregation preserves `promptFeedback`, including prompt-block
reasons and safety ratings. A blocked prompt with no generated candidates stays
without candidates; buffered and aggregated responses both normalize its block
reason to `content_filter` when applicable.

OpenAI Chat streaming aggregation retains `system_fingerprint` and `service_tier`
and concatenates each choice's text and refusal logprob entries in arrival order.
These fields remain available through `api_specific` after response decoding.

Both gateway aggregation and daemon worker observation apply the streaming
codec's completion validation. An OpenAI Responses stream that ends without a
`response.completed`, `response.failed`, or `response.incomplete` event fails
validation. A first terminal event of `response.failed` also produces a codec
error, even though the worker received the terminal snapshot. In both cases the
worker marks its observation as truncated, omits its aggregate, and forwards the
original bytes to the application.

Observation truncation does not override delivery's terminal outcome. Body read
failures retain their body-error description. Cancellation retains an unset
OpenTelemetry status for successful HTTP responses; a received HTTP error is
still reported. The truncation flag remains available separately.

OpenAI Responses aggregation retains partial text, refusals, and function-call
arguments for output items supplied by the stream. Completed fields and parts
replace provisional deltas; completed items replace their provisional content;
a nonempty terminal output replaces the collected items. If the stream stops
after an empty item is added, the finalizer keeps the snapshot entry at that
index. An explicit `response.output_item.done` replaces that entry even when its
content is empty. This prevents duplicate
content while retaining observed output if a stream is interrupted. Partial
aggregation does not imply successful completion: missing-terminal validation
still applies, and usage is included only when the provider supplies it. The
finalizer exposes the partial aggregate; consumers can omit it on stream failure.

## Cost Estimation

Response codecs should keep reporting provider usage fields without rewriting
the caller-visible response. If a provider or framework reports cost, map it to
`Usage.cost` with `source: "provider_reported"`. Otherwise Relay can layer cost
estimation onto `AnnotatedLlmResponse.usage.cost` when all required inputs are
available:

* The decoded response includes `model`.
* The managed LLM call name identifies the provider or route, such as `openai`,
  `anthropic`, or `azure/openai`, when provider-specific model pricing is needed.
* The decoded response includes prompt and/or completion token usage.
* Relay has an explicit model pricing entry for that model or alias.

For cost metadata, missing-input behavior, and resolver contracts, refer to
[Cost Estimation](/nemo/relay/v1.0.0/reference/api/model-pricing#cost-estimation).

Model pricing is runtime state, not a CLI-only feature. Any host that initializes
Relay plugins can activate the built-in `pricing` component before it runs
managed LLM calls. This includes application code, eval harnesses, custom
agents, and framework integrations. The CLI commands below are a
file-management convenience for the local gateway. Embedded hosts can pass
the same component config directly through the plugin APIs.

Source precedence is deployment controlled:

1. Explicit application model pricing supplied programmatically.
2. Enterprise-managed system sources, such as a remotely synced file or a service
   backed by a database.

The built-in `pricing` plugin component accepts inline catalogs or JSON catalog
files in precedence order. In discovered `plugins.toml` config, system config
has higher precedence than the selected explicit-or-user config. For the
`pricing` component, higher-priority `sources` are prepended instead of
replacing lower-priority sources, so a system source wins for a matching model
while explicit-or-user sources remain available as fallbacks. Programmatic
application sources can precede both file layers:

```toml
[[components]]
kind = "pricing"
enabled = true

[[components.config.sources]]
type = "file"
path = "/etc/nemo-relay/pricing.json"

[[components.config.sources]]
type = "inline"
[components.config.sources.catalog]
version = 1
entries = []
```

On Windows, use the expanded ProgramData path in TOML, for example
`C:\\ProgramData\\nemo-relay\\pricing.json`.

For catalog fields, defaults, and validation rules, refer to
[Cost Estimation](/nemo/relay/v1.0.0/reference/api/model-pricing#cost-estimation).

Use the CLI to validate catalog files and manage file-backed model pricing sources:

```bash
nemo-relay model-pricing validate <path/to/pricing.json>
nemo-relay model-pricing init --user
nemo-relay model-pricing add-source <path/to/pricing.json> --user
nemo-relay model-pricing resolve gpt-4o-mini --provider openai --prompt-tokens 1000 --completion-tokens 500
```

Replace `<path/to/pricing.json>` with the path to your pricing catalog before
running the validation or source-management commands.

`model-pricing init` creates or enables the `pricing` plugin component in the
selected `plugins.toml`. The initialized component has an empty `sources` list.
Use `model-pricing add-source` or an inline config edit to provide model pricing data.

`model-pricing add-source` validates the referenced JSON catalog before updating
`plugins.toml`. It creates the `pricing` component if needed and prepends the new
file source by default, making it the highest-priority source in that scope. Use
`--append` when the file should be a lower-priority fallback. Both commands
default to user config at `$XDG_CONFIG_HOME/nemo-relay/plugins.toml`. Pass
`--global` for `/etc/nemo-relay/plugins.toml` on Unix or
`%ProgramData%\nemo-relay\plugins.toml` on Windows.

`model-pricing resolve` uses the same discovered config path as the gateway. It
reports the winning catalog source, matched provider/model, and, when token
counts are supplied, the estimated total cost. The source line is one of
`file:<path>` or `inline:<index>`, which makes overlapping user/fleet
entries debuggable. This is a dry diagnostic command. It does not mutate
configuration.

`nemo-relay doctor` also validates enabled model pricing sources and reports missing,
unreadable, or invalid catalogs before the gateway starts.

For provider and route lookup, threshold pricing, and custom Rust sources,
refer to [Cost Estimation](/nemo/relay/v1.0.0/reference/api/model-pricing#cost-estimation).

Embedded applications and eval harnesses can initialize the built-in `pricing`
component for model pricing directly:

#### Python

```python
import asyncio

import nemo_relay

config = nemo_relay.plugin.PluginConfig(
    components=[
        nemo_relay.plugin.ComponentSpec(
            kind="pricing",
            config={
                "sources": [
                    {"type": "file", "path": "./pricing.json"},
                ],
            },
        )
    ]
)

report = nemo_relay.plugin.validate_exact(config)["config"]
if any(diagnostic["level"] == "error" for diagnostic in report["diagnostics"]):
    raise RuntimeError(report["diagnostics"])

async def main() -> None:
    async with nemo_relay.plugin.activate(config):
        # Run instrumented application work here.
        pass

asyncio.run(main())
```

#### Node.js

```ts
import * as plugin from 'nemo-relay-node/plugin';

const config = plugin.defaultConfig();
config.components = [
  plugin.ComponentSpec('pricing', {
    sources: [{ type: 'file', path: './pricing.json' }],
  }),
];

const report = plugin.validateExact(config).config;
if (report.diagnostics.some((diagnostic) => diagnostic.level === 'error')) {
  throw new Error(JSON.stringify(report.diagnostics));
}

const activation = await plugin.initialize(config);
// Run instrumented application work here.
await activation.close();
```

#### Rust

```rust
use nemo_relay::plugin::PluginConfig;
use nemo_relay::plugin::{initialize, validate_exact};
use serde_json::json;

let config: PluginConfig = serde_json::from_value(json!({
    "version": 1,
    "components": [{
        "kind": "pricing",
        "config": {
            "sources": [
                {"type": "file", "path": "./pricing.json"}
            ]
        }
    }]
}))?;

let report = validate_exact(config.clone());
if report.config.has_errors() {
    return Err("invalid model pricing plugin config".into());
}

let mut activation = initialize(config, None).await?;
// Run instrumented application work here.
activation.close()?;
```

Initialize model pricing once during process or harness startup, before the
managed LLM calls or manual lifecycle end events whose responses should be
cost-annotated. Retain the activation handle and close it during teardown if
later cases need a different resolver.

Built-in response codecs attach estimated cost directly to
`AnnotatedLlmResponse.usage.cost` when model pricing is known. Managed LLM
wrappers and manual lifecycle endings also enrich decoded or supplied response
annotations when they contain `model` and `usage` but omit `usage.cost`.
Existing cost values are preserved, so provider-reported cost remains
authoritative in the annotation.

Observability exporters prefer codec-normalized usage and cost, then fall back to
raw payload fields and model-pricing estimates, subject to each exporter's
currency and reported-cost policy. When cost is available, each exporter projects
it per the [exporter field mapping](/nemo/relay/v1.0.0/reference/api/model-pricing#exporter-field-mapping).

## Token and Cost Field Semantics

Refer to [Token and Cost Field Semantics](/nemo/relay/v1.0.0/reference/api/model-pricing#token-and-cost-field-semantics).

### Granularity

Refer to [Granularity](/nemo/relay/v1.0.0/reference/api/model-pricing#granularity).

### Usage Fields

Refer to [Usage Fields](/nemo/relay/v1.0.0/reference/api/model-pricing#usage-fields).

### Cost Fields

Refer to [Cost Fields](/nemo/relay/v1.0.0/reference/api/model-pricing#cost-fields).

### Exporter Field Mapping

Refer to [Exporter Field Mapping](/nemo/relay/v1.0.0/reference/api/model-pricing#exporter-field-mapping).

### Stability

Refer to [Stability](/nemo/relay/v1.0.0/reference/api/model-pricing#stability).

## Built-in Response Codecs

The built-in provider codecs also implement response decoding:

* `OpenAIChatCodec` — OpenAI Chat Completions API
* `OpenAIResponsesCodec` — OpenAI Responses API
* `AnthropicMessagesCodec` — Anthropic Messages API
* `OCIGenAIChatCodec` — OCI Generative AI chat API (`GENERIC`, `COHERE`, and `COHEREV2` formats)
* `GeminiGenerateContentCodec` — Google Gemini `generateContent` API

Choose the codec that matches the actual provider response shape. For example, do not use `OpenAIChatCodec` for an OpenAI Responses API payload only because both came from an OpenAI-compatible provider.

## Attach a Built-in Response Codec

The examples below attach built-in response codecs for supported provider response
shapes.

#### Python

```python
import nemo_relay
from nemo_relay import LLMRequest
from nemo_relay.codecs import OpenAIChatCodec

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": [
            {
                "finish_reason": "stop",
                "message": {"role": "assistant", "content": "Hello from the provider."},
            }
        ],
        "usage": {"prompt_tokens": 8, "completion_tokens": 5, "total_tokens": 13},
    }

codec = OpenAIChatCodec()
response = await nemo_relay.llm.execute(
    "openai-chat",
    LLMRequest({}, {"model": "gpt-4o-mini", "messages": []}),
    invoke_provider,
    model_name="gpt-4o-mini",
    response_codec=codec,
)
```

#### Node.js

```ts
import { OpenAIChatCodec, flushSubscribers } from 'nemo-relay-node';
import { JsonPassthrough, typedLlmExecute } from 'nemo-relay-node/typed';

const codec = new OpenAIChatCodec();

const response = await typedLlmExecute(
  'openai-chat',
  { headers: {}, content: { model: 'gpt-4o-mini', messages: [] } },
  async (providerRequest) => {
    const content = providerRequest.content as { model: string };
    return {
      id: 'chatcmpl-demo',
      model: content.model,
      choices: [
        {
          finish_reason: 'stop',
          message: { role: 'assistant', content: 'Hello from the provider.' },
        },
      ],
      usage: { prompt_tokens: 8, completion_tokens: 5, total_tokens: 13 },
    };
  },
  new JsonPassthrough(),
  {
    modelName: 'gpt-4o-mini',
    responseCodec: codec,
  },
);
await flushSubscribers();
```

#### Rust

```rust
use nemo_relay::llm::{llm_call_execute, LlmCallExecuteParams, LlmRequest};
use nemo_relay_codecs::openai_chat::OpenAIChatCodec;
use nemo_relay_types::codec::traits::LlmResponseCodec;
use serde_json::json;
use std::sync::Arc;

let request = LlmRequest {
    headers: Default::default(),
    content: json!({"model": "gpt-4o-mini", "messages": []}),
};
let response_codec: Arc<dyn LlmResponseCodec> = Arc::new(OpenAIChatCodec);

let response = llm_call_execute(
    LlmCallExecuteParams::builder()
        .name("openai-chat")
        .request(request)
        .func(Arc::new(|provider_request| Box::pin(async move {
            Ok(json!({
                "id": "chatcmpl-demo",
                "model": provider_request.content["model"],
                "choices": [{
                    "finish_reason": "stop",
                    "message": {
                        "role": "assistant",
                        "content": "Hello from the provider."
                    }
                }],
                "usage": {
                    "prompt_tokens": 8,
                    "completion_tokens": 5,
                    "total_tokens": 13
                }
            }))
        })))
        .model_name("gpt-4o-mini")
        .response_codec(response_codec)
        .build(),
)
.await?;
```

## Read Annotated Responses

Subscribers can inspect `annotated_response` on LLM end events. The exact event category fields are binding-provided, so defensive checks should confirm the annotation exists before reading it.

#### Python

```python
import nemo_relay

def on_event(event: nemo_relay.Event) -> None:
    annotated = getattr(event, "annotated_response", None)
    if annotated is None:
        return

    print("model", annotated.model)
    print("text", annotated.response_text())
    print("usage", annotated.usage)
    print("cost", (annotated.usage or {}).get("cost"))

nemo_relay.subscribers.register("response-debugger", on_event)
```

#### Node.js

```ts
import { registerSubscriber, type JsonObject, type JsonValue } from 'nemo-relay-node';

const isJsonObject = (value: JsonValue | undefined): value is JsonObject =>
  typeof value === 'object' && value !== null && !Array.isArray(value);

registerSubscriber('response-debugger', (event) => {
  const profile = event.category_profile;
  if (!isJsonObject(profile)) {
    return;
  }
  const annotated = profile.annotated_response;
  if (!isJsonObject(annotated)) {
    return;
  }

  console.log('model', annotated.model);
  console.log('message', annotated.message);
  console.log('usage', annotated.usage);
  const usage = annotated.usage;
  console.log('cost', isJsonObject(usage) ? usage.cost : null);
});
```

## Custom Response Codecs

Use a custom response codec when the provider or framework response does not match a built-in shape.

In Python, a custom response codec can route to built-in codecs and return their native `AnnotatedLLMResponse` values:

```python
import nemo_relay
from nemo_relay.codecs import OpenAIChatCodec, OpenAIResponsesCodec

class OpenAIRoutingResponseCodec:
    def __init__(self) -> None:
        self.chat = OpenAIChatCodec()
        self.responses = OpenAIResponsesCodec()

    def decode_response(self, response: nemo_relay.Json) -> nemo_relay.AnnotatedLLMResponse:
        if response.get("object") == "response":
            return self.responses.decode_response(response)
        return self.chat.decode_response(response)
```

In Node.js, implement `decodeResponse` and return the normalized response JSON shape:

```ts
import type { JsonValue, LlmResponseCodec } from 'nemo-relay-node/typed';

const frameworkResponseCodec: LlmResponseCodec = {
  decodeResponse(response: JsonValue): JsonValue {
    const raw = response as {
      id?: string;
      model_name?: string;
      text?: string;
      stop_reason?: string;
      token_usage?: {
        input?: number;
        output?: number;
      };
    };

    return {
      id: raw.id ?? null,
      model: raw.model_name ?? null,
      message: raw.text ?? '',
      finish_reason: raw.stop_reason === 'max_tokens' ? 'length' : 'complete',
      usage: {
        prompt_tokens: raw.token_usage?.input ?? null,
        completion_tokens: raw.token_usage?.output ?? null,
        total_tokens:
          raw.token_usage?.input === undefined || raw.token_usage?.output === undefined
            ? null
            : raw.token_usage.input + raw.token_usage.output,
      },
      provider_stop_reason: raw.stop_reason ?? null,
    };
  },
};
```

In Rust, implement `LlmResponseCodec` directly:

```rust title={"framework_response_codec.rs"}
// SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use nemo_relay_types::codec::request::MessageContent;
use nemo_relay_types::codec::response::{AnnotatedLlmResponse, FinishReason, Usage};
use nemo_relay_types::codec::traits::LlmResponseCodec;
use nemo_relay_types::error::{FlowError, Result};
use nemo_relay_types::Json;
use serde::Deserialize;
use serde_json::Map;

#[derive(Deserialize)]
struct FrameworkResponse {
    id: Option<String>,
    model_name: Option<String>,
    text: Option<String>,
    input_tokens: Option<u64>,
    output_tokens: Option<u64>,
}

struct FrameworkResponseCodec;

impl LlmResponseCodec for FrameworkResponseCodec {
    /// Decode a framework response into Relay's standard response fields.
    fn decode_response(&self, response: &Json) -> Result<AnnotatedLlmResponse> {
        let raw: FrameworkResponse = serde_json::from_value(response.clone())
            .map_err(|error| FlowError::Internal(error.to_string()))?;
        let total_tokens = match (raw.input_tokens, raw.output_tokens) {
            (Some(input), Some(output)) => input.checked_add(output),
            _ => None,
        };

        Ok(AnnotatedLlmResponse {
            id: raw.id,
            model: raw.model_name,
            message: raw.text.map(MessageContent::Text),
            tool_calls: None,
            finish_reason: Some(FinishReason::Complete),
            usage: Some(Usage {
                prompt_tokens: raw.input_tokens,
                completion_tokens: raw.output_tokens,
                total_tokens,
                cache_read_tokens: None,
                cache_write_tokens: None,
                uncached_input_tokens: None,
                cost: None,
            }),
            optimization_summary: None,
            api_specific: None,
            extra: Map::new(),
        })
    }
}

```

## Streaming Responses

Streaming LLM wrappers decode the aggregated response produced by the stream finalizer. The response codec does not see each token or chunk. Use stream collectors for chunk-level behavior, and use response codecs for the final normalized end-event annotation.

### Borrowing Stream Chunks in Rust

Rust callers can use `LlmStreamCallExecuteParams::borrowed_collector` to read each
JSON chunk without copying the whole chunk. Built-in streaming codecs provide
this callback through `StreamingCodec::borrowed_collector()`:

```rust
use nemo_relay::llm::LlmStreamCallExecuteParams;
use nemo_relay_codecs::openai_chat::OpenAIChatStreamingCodec;
use nemo_relay_types::codec::streaming::StreamingCodec;

let streaming_codec = OpenAIChatStreamingCodec::new();
let params = LlmStreamCallExecuteParams::builder()
    .name("openai")
    .request(request)
    .func(provider_stream)
    .collector(streaming_codec.collector())
    .borrowed_collector_opt(streaming_codec.borrowed_collector())
    .finalizer(streaming_codec.finalizer())
    .build();
```

If you set a borrowed collector, the runtime calls it instead of the owned
`collector`. Copy any fields you need after the callback returns. If the callback
returns an error, the runtime stops the stream. It runs the same finalizer and
cleanup steps as an owned collector.

Custom codecs can keep the default `None` to use their existing owned callback.
Python, Node.js, and FFI collectors still receive owned chunks.

## Validation Checklist

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

* The response codec matches the actual provider response shape.
* `decode_response` returns a normalized response with safe, JSON-compatible fields.
* The provider response returned to the application is unchanged.
* Subscribers see `annotated_response` only on LLM end events where decode succeeds.
* Decode errors are tested and do not break the LLM call.
* Streaming finalizers produce the same shape the response codec expects.

## Common Issues

Check these symptoms first when the workflow does not behave as expected.

* **No annotation appears**: The response codec returned an error or the raw provider response did not match the codec.
* **Returned response changed unexpectedly**: Response codecs are not the right place to mutate caller-visible output.
* **Tool calls are missing**: The codec did not map the provider's tool-call structure into `tool_calls`.
* **Usage is inconsistent across providers**: Normalize known token fields and preserve provider-specific usage details in `api_specific` or `extra`.

## Next Steps

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

* Use [Provider Codecs](/nemo/relay/v1.0.0/integrate-into-frameworks/provider-codecs) for request-side provider codecs and full request/response examples.
* Use [Wrap LLM Calls](/nemo/relay/v1.0.0/integrate-into-frameworks/wrap-llm-calls) to add the managed LLM boundary first.
* Use [Observability](/nemo/relay/v1.0.0/configure-plugins/observability/about) after annotations are visible in local subscribers.