> 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.

# Code Examples

> Choose Execute APIs first, then explore streaming, manual lifecycle fallbacks, and advanced helpers.

Use these examples after [Instrument a Tool Call](/nemo/relay/v1.0.0/instrument-applications/instrument-tool-call)
or [Instrument an LLM Call](/nemo/relay/v1.0.0/instrument-applications/instrument-llm-call), or when
you need to select a specific execution API.

Each reference file defines `run_example` in Python and Rust or `runExample` in
Node.js. Call the function from the working application in the tool or LLM guide;
await asynchronous functions. Keep that application's scope, subscriber, and
cleanup. These functions are integration fragments rather than standalone
programs.

## Invocation API Selection

Prefer Execute APIs whenever you can pass the actual tool or provider function
to Relay. Use manual start/end APIs only when another library owns the invocation
and exposes only lifecycle notifications. Do not retry a failed Execute call
through a manual API.

The following table shows which API to use based on your integration need:

| Need                                      | Preferred API                                                            | Use When                                                                 |
| ----------------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ |
| Run a tool with full instrumentation      | `tools.execute`, `toolCallExecute`, `tool_call_execute`                  | Application code owns the callback.                                      |
| Run an LLM call with full instrumentation | `llm.execute`, `llmCallExecute`, `llm_call_execute`                      | Application code owns the provider call.                                 |
| Run a streaming LLM call                  | `llm_stream_execute`, `typedLlmStreamExecute`, `llm_stream_call_execute` | You need chunk collection and one final aggregate end event.             |
| Emit start/end manually                   | `call` and `call_end` helpers                                            | A framework owns the real invocation boundary.                           |
| Emit a checkpoint                         | `scope.event`, `event`                                                   | You need milestone visibility inside an active scope.                    |
| Emit an OTLP log mark                     | Generic mark API with typed `severity`                                   | A sanitized checkpoint should become a telemetry log record.             |
| Record an OTLP metric                     | `metric`                                                                 | One validated measurement group should be routed to the metric pipeline. |
| Attach work to one request                | Scope-local registration helpers                                         | Middleware or subscribers should disappear when that scope closes.       |

## Managed Tool Execution

Pass the tool name, JSON-compatible arguments, and the tool function to the
Execute helper. The function returns a canonical `ToolExecutionResult`.

| Python                     | Node.js           | Rust                |
| -------------------------- | ----------------- | ------------------- |
| `nemo_relay.tools.execute` | `toolCallExecute` | `tool_call_execute` |

Refer to [Instrument a Tool Call](/nemo/relay/v1.0.0/instrument-applications/instrument-tool-call#minimal-example)
for the complete example, scope setup, and event verification.

## Managed LLM Execution

Use managed execution when NeMo Relay should run the full middleware pipeline around the provider call.
This example uses a local callback and makes no external model request.

#### Python

```python title={"managed_llm.py"}
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

import nemo_relay
from nemo_relay import LLMRequest


async def run_example() -> nemo_relay.Json:
    """Execute the local provider callback through Relay."""
    request = LLMRequest({}, {"messages": [{"role": "user", "content": "hello"}]})

    async def invoke(provider_request: LLMRequest) -> dict[str, object]:
        return {"text": "hi", "request": provider_request.content}

    response = await nemo_relay.llm.execute(
        "demo-provider",
        request,
        invoke,
        model_name="demo-model",
    )
    return response

```

#### Node.js

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

import { LlmRequest, llmCallExecuteAsync, type LlmRequestShape } from 'nemo-relay-node';

/** Execute the local provider callback through Relay. */
export async function runExample() {
  const request = new LlmRequest({}, { messages: [{ role: 'user', content: 'hello' }] });

  const response = await llmCallExecuteAsync(
    'demo-provider',
    request,
    async (providerRequest: LlmRequestShape) => ({ text: 'hi', request: providerRequest.content }),
    null,
    null,
    null,
    null,
    'demo-model',
  );
  return response;
}

```

#### Rust

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

use nemo_relay::llm::{LlmCallExecuteParams, LlmRequest, llm_call_execute};
use serde_json::json;
use std::sync::Arc;

/// Execute the local provider callback through Relay.
pub async fn run_example() -> Result<serde_json::Value, Box<dyn std::error::Error>> {
    let request = LlmRequest {
        headers: Default::default(),
        content: json!({"messages": [{"role": "user", "content": "hello"}]}),
    };

    let response = llm_call_execute(
        LlmCallExecuteParams::builder()
            .name("demo-provider")
            .request(request)
            .func(Arc::new(|provider_request| {
                Box::pin(
                    async move { Ok(json!({"text": "hi", "request": provider_request.content})) },
                )
            }))
            .model_name("demo-model")
            .build(),
    )
    .await?;
    Ok(response)
}

```

Calling the example function returns the following value:

**`Expected managed LLM result`**

```json title="Expected managed LLM result"
{
  "text": "hi",
  "request": {
    "messages": [
      {
        "role": "user",
        "content": "hello"
      }
    ]
  }
}
```

With the guide's subscriber registered, expect one LLM start/end pair named
`demo-provider`.

## Streaming LLM Execution

Use the streaming helper when a model returns its response in chunks. The
collector gathers those chunks. The finalizer builds one response from the
collected data for the LLM end event.

When the stream ends normally, Relay runs the finalizer automatically. If you
stop reading early, close the stream to stop the producer and finalize the
partial response. Relay records that early close as an interruption.

The following examples read one chunk and then close the stream. Closing runs
the finalizer and completes the LLM lifecycle with the collected response. These
examples use local generators, so they require no provider credentials.
In Python, the collector receives typed dataclass instances, while iterating the
returned stream yields JSON chunks.
The Rust example also needs `tokio-stream` in the application's dependencies,
alongside the dependencies from the [Rust Quick Start](/nemo/relay/v1.0.0/getting-started/quick-start/rust).

#### Python

```python title={"streaming_llm.py"}
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

from collections.abc import AsyncIterator
from dataclasses import dataclass

from nemo_relay import Json, LLMRequest
from nemo_relay.typed import DataclassCodec, llm_stream_execute


async def run_example() -> Json:
    """Read one stream chunk and close the producer."""

    @dataclass
    class Chunk:
        delta: str

    @dataclass
    class FinalResponse:
        text: str

    request = LLMRequest({}, {"messages": [{"role": "user", "content": "hello"}]})
    collected: list[Chunk] = []

    async def stream_impl(_request: LLMRequest) -> AsyncIterator[Chunk]:
        yield Chunk(delta="hi")

    stream = await llm_stream_execute(
        "demo-provider",
        request,
        stream_impl,
        collector=collected.append,
        finalizer=lambda: FinalResponse(text="".join(chunk.delta for chunk in collected)),
        chunk_json_codec=DataclassCodec(Chunk),
        response_json_codec=DataclassCodec(FinalResponse),
    )

    try:
        first_chunk = await anext(stream)
        # Stop early after deciding no more output is needed.
    finally:
        await stream.aclose()
    return first_chunk

```

#### Node.js

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

import { LlmRequest } from 'nemo-relay-node';
import { typedLlmStreamExecute, type Codec } from 'nemo-relay-node/typed';

/** Read one stream chunk and close the producer. */
export async function runExample() {
  type Chunk = { delta: string };
  type FinalResponse = { text: string };

  const chunkCodec: Codec<Chunk> = {
    toJson: (value) => value,
    fromJson: (json) => json as Chunk,
  };
  const responseCodec: Codec<FinalResponse> = {
    toJson: (value) => value,
    fromJson: (json) => json as FinalResponse,
  };

  const request = new LlmRequest({}, { messages: [{ role: 'user', content: 'hello' }] });
  const collected: Chunk[] = [];

  const stream = await typedLlmStreamExecute(
    'demo-provider',
    request,
    async function* () {
      yield { delta: 'hi' };
    },
    (chunk) => {
      collected.push(chunk);
    },
    () => ({ text: collected.map((chunk) => chunk.delta).join('') }),
    chunkCodec,
    responseCodec,
  );

  try {
    const firstChunk = await stream.next();
    // Stop early after deciding no more output is needed.
    return firstChunk;
  } finally {
    await stream.close();
  }
}

```

#### Rust

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

use nemo_relay::llm::{
    LlmAttributes, LlmRequest, LlmStreamCallExecuteParams, llm_stream_call_execute,
};
use nemo_relay::middleware::LlmJsonStream;
use serde_json::json;
use tokio_stream::StreamExt;

/// Read one stream chunk and close the producer.
pub async fn run_example() -> Result<Option<serde_json::Value>, Box<dyn std::error::Error>> {
    let request = LlmRequest {
        headers: Default::default(),
        content: json!({"messages": [{"role": "user", "content": "hello"}]}),
    };

    let mut stream = llm_stream_call_execute(
        LlmStreamCallExecuteParams::builder()
            .name("demo-provider")
            .request(request)
            .func(std::sync::Arc::new(|_req| {
                Box::pin(async move {
                    Ok(LlmJsonStream::new(tokio_stream::iter(vec![Ok(
                        json!({"delta": "hi"}),
                    )])))
                })
            }))
            .collector(Box::new(|_chunk| Ok(())))
            .finalizer(Box::new(|| json!({"text": "hi"})))
            .attributes(LlmAttributes::STREAMING)
            .model_name("demo-model")
            .build(),
    )
    .await?;

    let first_chunk = stream.next().await;
    // Stop early after deciding no more output is needed.
    stream.close().await?;
    Ok(first_chunk.transpose()?)
}

```

After closing the stream, the example function returns the first chunk:

**`Expected first stream chunk`**

```json title="Expected first stream chunk"
{
  "delta": "hi"
}
```

### Handle Stream Failures

Always close a stream after you finish reading it, including after a read
error. Use `await stream.aclose()` in Python, `await stream.close()` in
Node.js, or `stream.close().await` in Rust. Closing waits for producer cleanup
and finalization. Repeated calls return the same close result.

In Node.js, both `llmStreamCallExecute` and `typedLlmStreamExecute` report
failures at the following points:

| Failure                                                                           | Where It Is Reported                       |
| --------------------------------------------------------------------------------- | ------------------------------------------ |
| The provider callback throws or rejects before returning an async iterable.       | The call that creates the stream rejects.  |
| The provider returns a value that is not an async iterable.                       | The call that creates the stream rejects.  |
| The iterator or collector throws or rejects while reading a chunk.                | `stream.next()` rejects. The stream stops. |
| Producer cleanup fails.                                                           | `stream.close()` rejects.                  |
| The finalizer throws, rejects, or returns a value that cannot be encoded as JSON. | `stream.close()` rejects.                  |

Node.js collectors and finalizers can return a `Promise`. Relay waits for a
collector before yielding its chunk. It waits for the finalizer before
reporting the end of the stream.

If the finalizer fails, the combined response is `null`. Relay omits the response
payload from the end event. It does not use the call's `data` value as a
fallback. A finalizer failure marks an otherwise completed LLM end event as
`ERROR`.

In Node.js, `stream.close()` gives priority to a stream error that `next()` has
not yet reported. Cleanup errors take priority over finalizer errors. If `next()`
already reported the stream error, close does not report it again. It can
still report a cleanup or finalizer error. Handle errors from both reading
and closing. Keep the read error if cleanup also fails, and report the
cleanup error separately. If a stream error has not yet been reported,
`close()` reports that error and logs any accompanying producer cleanup failure.

### Cancel the Producer

Closing requests cancellation, but the producer must be able to stop its work.
In Node.js, the provider callback receives `(request, signal)`. Pass this
`AbortSignal` to provider operations that support it. Stop pending work when
the signal aborts. Release resources in the iterator's cleanup path.

Close has no cleanup timeout. It can remain pending if the producer does not
stop. An asynchronous collector must also finish after the producer stops.
Set time limits on provider operations and make cleanup finish promptly.

### Wait for Subscriber Delivery

Stream completion and subscriber delivery are separate steps. Reading the
last chunk or closing the stream does not wait for queued response sanitizers
and subscribers. Close the stream first. Then flush subscribers before
reading captured events. Before checking exporter output or shutting down,
also complete the exporter's flush, export, or shutdown operation.
Refer to [Waiting for Delivery](/nemo/relay/v1.0.0/about-nemo-relay/concepts/subscribers#waiting-for-delivery)
for the flush API and exporter requirements for each binding.

## Manual Tool Lifecycle

> **Warning**
>
> Prefer execution wrappers for tool and LLM calls whenever you can pass the actual
> function to Relay. Explicit tool and LLM start/end calls emit scope events, but
> they do not execute the tool or provider function or automatically run the full execution
> middleware pipeline. Use them only when another library owns the invocation and
> exposes reliable start and finish notifications. Refer to
> [Instrument a Tool Call](/nemo/relay/v1.0.0/instrument-applications/instrument-tool-call#minimal-example)
> and [Instrument an LLM Call](/nemo/relay/v1.0.0/instrument-applications/instrument-llm-call#minimal-example)
> for the execution wrappers.

The following examples start and finish the lifecycle for a `search` operation.
Relay records the lifecycle; the surrounding code performs the operation.
Preserve the start handle and arrange for the matching end event on success and
failure. Request and execution intercepts do not run automatically on this path;
event-payload sanitizers still apply.
Refer to [Explicit API Calls](/nemo/relay/v1.0.0/integrate-into-frameworks/code-examples#fallback-explicit-api-calls)
for the fallback's execution coverage and error-handling responsibilities.
If you are replaying events or bridging a framework clock, pass an explicit timestamp to the manual start, end, or mark helpers.
Python accepts timezone-aware `datetime` values, Node.js accepts Unix microseconds since epoch, and Rust accepts `DateTime<Utc>`.
Every manual tool end helper accepts the canonical `ToolExecutionResult`; wrap
the business payload and add an optional opaque annotation when needed.

Change `query` to an empty string to exercise the failure path below. Each
example attempts the matching end call before propagating the operation's
original error. The `error` field is an application-defined failure payload.
If the end call also fails, Python attaches that failure to the original
exception; Node.js and Rust report it separately.

Pass `"weather"` to the function for the successful path or an empty string for
the failure path.

#### Python

```python title={"manual_tool_lifecycle.py"}
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

import nemo_relay


def run_example(query: str = "weather") -> dict[str, int]:
    """Complete the manual tool lifecycle and preserve operation errors."""

    def search(query: str) -> dict[str, int]:
        if not query:
            raise ValueError("query is required")
        return {"hits": 2}

    handle = nemo_relay.tools.call("search", {"query": query}, data={"attempt": 1})
    try:
        result = search(query)
    except Exception as execution_error:
        try:
            nemo_relay.tools.call_end(
                handle,
                nemo_relay.ToolExecutionResult({"error": str(execution_error)}),
            )
        except Exception as completion_error:
            execution_error.add_note(f"Relay could not record tool completion: {completion_error}")
        raise
    else:
        nemo_relay.tools.call_end(handle, nemo_relay.ToolExecutionResult(result))
    return result

```

#### Node.js

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

import { toolCall, toolCallEnd } from 'nemo-relay-node';

/** Complete the manual tool lifecycle and preserve operation errors. */
export function runExample(query = 'weather') {
  function search(query: string): { hits: number } {
    if (!query) throw new Error('query is required');
    return { hits: 2 };
  }

  const handle = toolCall('search', { query }, null, null, { attempt: 1 }, null, null);
  let result: { hits: number };
  try {
    result = search(query);
  } catch (executionError) {
    const message = executionError instanceof Error ? executionError.message : String(executionError);
    try {
      toolCallEnd(handle, { result: { error: message } }, null, null);
    } catch (completionError) {
      console.error('Relay could not record tool completion:', completionError);
    }
    throw executionError;
  }
  toolCallEnd(handle, { result }, null, null);
  return result;
}

```

#### Rust

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

use nemo_relay::tool::{
    ToolCallEndParams, ToolCallParams, ToolExecutionResult, tool_call, tool_call_end,
};
use serde_json::{Value, json};

fn search(query: &str) -> nemo_relay::Result<Value> {
    if query.is_empty() {
        return Err(nemo_relay::FlowError::InvalidArgument(
            "query is required".into(),
        ));
    }
    Ok(json!({"hits": 2}))
}

/// Complete the manual tool lifecycle and preserve operation errors.
pub fn run_example(query: &str) -> nemo_relay::Result<()> {
    let handle = tool_call(
        ToolCallParams::builder()
            .name("search")
            .args(json!({"query": query}))
            .data(json!({"attempt": 1}))
            .build(),
    )?;

    let (result, execution_error) = match search(query) {
        Ok(result) => (result, None),
        Err(error) => (json!({"error": error.to_string()}), Some(error)),
    };
    let completion_result = tool_call_end(
        ToolCallEndParams::builder()
            .handle(&handle)
            .execution_result(ToolExecutionResult::new(result))
            .build(),
    );

    if let Some(execution_error) = execution_error {
        if let Err(completion_error) = completion_result {
            eprintln!("Relay could not record tool completion: {completion_error}");
        }
        return Err(execution_error);
    }
    completion_result
}

```

With the guide's subscriber registered, both paths print these tool lifecycle
lines. Enclosing application scopes can print additional lines:

**`Expected manual tool lifecycle events`**

```text title="Expected manual tool lifecycle events"
scope search
scope search
```

The two lines are the start and end of the same tool call. An empty query still
propagates an error containing `query is required` after the end call is
attempted. Error formatting differs across bindings.

## Partial Middleware Calls

These helpers are useful when framework code cannot use managed execution but still wants a request rewrite or block decision.
They apply selected middleware stages; they do not invoke the tool or provider,
manage the complete lifecycle, or replace an Execute call.

Without registered transforms, the returned tool arguments still contain
`query: "weather"`, and the model request still contains the `hello` message.
No tool or LLM lifecycle pair is emitted because these helpers do not execute a
callback.

#### Python

```python title={"partial_middleware.py"}
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

import nemo_relay
from nemo_relay import LLMRequest


async def run_example() -> tuple[nemo_relay.Json, LLMRequest]:
    """Apply selected middleware without invoking a callback."""
    tool_arguments = await nemo_relay.tools.request_intercepts("search", {"query": "weather"})
    await nemo_relay.tools.conditional_execution("search", tool_arguments)

    llm_request = LLMRequest({}, {"messages": [{"role": "user", "content": "hello"}]})
    outcome = await nemo_relay.llm.request_intercepts("demo-provider", llm_request)
    await nemo_relay.llm.conditional_execution(outcome.request)
    return (tool_arguments, outcome.request)

```

#### Node.js

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

import {
  LlmRequest,
  llmConditionalExecution,
  llmRequestIntercepts,
  toolConditionalExecution,
  toolRequestIntercepts,
} from 'nemo-relay-node';

/** Apply selected middleware without invoking a callback. */
export async function runExample() {
  const toolArgs = await toolRequestIntercepts('search', { query: 'weather' });
  await toolConditionalExecution('search', toolArgs);

  const request = new LlmRequest({}, { messages: [{ role: 'user', content: 'hello' }] });
  const outcome = await llmRequestIntercepts('demo-provider', request);
  await llmConditionalExecution(outcome.request);
  return { toolArguments: toolArgs, request: outcome.request };
}

```

#### Rust

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

use nemo_relay::llm::{LlmRequest, llm_conditional_execution, llm_request_intercepts};
use nemo_relay::tool::{tool_conditional_execution, tool_request_intercepts};
use serde_json::json;

/// Apply selected middleware without invoking a callback.
pub async fn run_example()
-> Result<(serde_json::Value, nemo_relay::llm::LlmRequest), Box<dyn std::error::Error>> {
    let tool_arguments = tool_request_intercepts("search", json!({"query": "weather"})).await?;
    tool_conditional_execution("search", &tool_arguments).await?;

    let request = LlmRequest {
        headers: Default::default(),
        content: json!({"messages": [{"role": "user", "content": "hello"}]}),
    };
    let outcome = llm_request_intercepts("demo-provider", request).await?;
    llm_conditional_execution(&outcome.request).await?;
    Ok((tool_arguments, outcome.request))
}

```

## Scope and Context Helpers

Use normal scope helpers first. Reach for explicit stack helpers only when work crosses thread, task, worker, or request boundaries.

The Python example emits `started` and `worker-ran` within the same `request`
scope. The Node.js example initializes a stack for the current worker and emits
`started` within `request`; it does not create another worker. The Rust example
emits `started` in a task-bound stack and installs that stack on another thread.

#### Python

```python title={"scope_context.py"}
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

from concurrent.futures import ThreadPoolExecutor

import nemo_relay


def run_example() -> None:
    """Use an explicit scope stack across execution boundaries."""
    with nemo_relay.scope.scope("request", nemo_relay.ScopeType.Agent):
        nemo_relay.scope.event("started", data={"ok": True})
        shared = nemo_relay.propagate_scope_to_thread()

        def worker() -> None:
            nemo_relay.set_thread_scope_stack(shared)
            nemo_relay.scope.event("worker-ran")

        with ThreadPoolExecutor() as pool:
            pool.submit(worker).result()

```

#### Node.js

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

import { ScopeType, createScopeStack, event, setThreadScopeStack, withScope } from 'nemo-relay-node';

/** Use an explicit scope stack across execution boundaries. */
export async function runExample() {
  const workerStack = createScopeStack();
  setThreadScopeStack(workerStack);

  await withScope('request', ScopeType.Agent, async (handle) => {
    event('started', handle, { ok: true }, null);
  });
}

```

#### Rust

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

use nemo_relay::context::{create_scope_stack, set_thread_scope_stack, with_task_scope_stack};
use nemo_relay::scope::{EmitMarkEventParams, event};
use serde_json::json;

/// Use an explicit scope stack across execution boundaries.
pub async fn run_example() -> Result<(), Box<dyn std::error::Error>> {
    let stack = create_scope_stack();
    with_task_scope_stack(stack.clone(), async {
        event(
            EmitMarkEventParams::builder()
                .name("started")
                .data(json!({"ok": true}))
                .build(),
        )
    })
    .await?;

    std::thread::spawn(move || {
        set_thread_scope_stack(stack);
        // NeMo Relay calls in this thread attach to the same explicit stack.
    })
    .join()
    .unwrap();
    Ok(())
}

```

## Temporarily Exclude a Global Registration

The following examples discover a global subscriber, register a state-driven gate,
and remove the gate after application work finishes. Use the same registration
kind during discovery and gate registration.

> **Note**
>
> Activate an observability component that registers an OpenTelemetry subscriber
> before calling this function. Pass the application work as its callback. If the
> subscriber is absent, the example reports `OpenTelemetry subscriber was not found`
> and does not run the callback. This is a configured-application example, not a
> standalone program.

#### Python

```python title={"global_registration_gate.py"}
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

from collections.abc import Awaitable, Callable

from nemo_relay.runtime_registrations import (
    RuntimeRegistrationKind,
    deregister_conditional_middleware_guardrail,
    list_runtime_registrations,
    register_conditional_middleware_guardrail,
)


async def run_example(run_application: Callable[[], Awaitable[None]]) -> None:
    """Pause a configured OpenTelemetry subscriber during application work."""
    target = next(
        (
            registration
            for registration in list_runtime_registrations({RuntimeRegistrationKind.SUBSCRIBER})
            if registration.local_name == "opentelemetry" and registration.owner.plugin_kind == "observability"
        ),
        None,
    )
    if target is None:
        raise RuntimeError("OpenTelemetry subscriber was not found")

    paused = True
    register_conditional_middleware_guardrail(
        "pause-opentelemetry",
        {RuntimeRegistrationKind.SUBSCRIBER},
        target.effective_name,
        lambda _kinds, _name: "export paused" if paused else None,
    )
    try:
        await run_application()
    finally:
        deregister_conditional_middleware_guardrail("pause-opentelemetry")

```

#### Node.js

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

import {
  deregisterConditionalMiddlewareGuardrail,
  listRuntimeRegistrations,
  registerConditionalMiddlewareGuardrail,
} from 'nemo-relay-node';

/** Pause a configured OpenTelemetry subscriber during application work. */
export async function runExample(runApplication: () => Promise<void>) {
  const target = listRuntimeRegistrations(['subscriber']).find(
    (registration) => registration.localName === 'opentelemetry' && registration.owner.pluginKind === 'observability',
  );
  if (!target) throw new Error('OpenTelemetry subscriber was not found');

  let paused = true;
  registerConditionalMiddlewareGuardrail('pause-opentelemetry', ['subscriber'], target.effectiveName, () =>
    paused ? 'export paused' : null,
  );
  try {
    await runApplication();
  } finally {
    deregisterConditionalMiddlewareGuardrail('pause-opentelemetry');
  }
}

```

#### Rust

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

use nemo_relay::registry::{
    RuntimeRegistrationKind, deregister_conditional_middleware_guardrail,
    list_runtime_registrations, register_conditional_middleware_guardrail,
};
use std::collections::BTreeSet;
use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
};

/// Pause a configured OpenTelemetry subscriber during application work.
pub async fn run_example<F, ApplicationFuture>(
    run_application: F,
) -> Result<(), Box<dyn std::error::Error>>
where
    F: FnOnce() -> ApplicationFuture,
    ApplicationFuture: std::future::Future<Output = Result<(), Box<dyn std::error::Error>>>,
{
    let kinds = BTreeSet::from([RuntimeRegistrationKind::Subscriber]);
    let target = list_runtime_registrations(Some(&kinds))?
        .into_iter()
        .find(|registration| {
            registration.local_name == "opentelemetry"
                && registration.owner.plugin_kind.as_deref() == Some("observability")
        })
        .ok_or("OpenTelemetry subscriber was not found")?;

    let paused = Arc::new(AtomicBool::new(true));
    let callback_state = Arc::clone(&paused);
    register_conditional_middleware_guardrail(
        "pause-opentelemetry",
        kinds,
        &target.effective_name,
        Arc::new(move |_kinds, _name| {
            callback_state
                .load(Ordering::Acquire)
                .then(|| "export paused".to_string())
        }),
    )?;

    let application_result = run_application().await;
    deregister_conditional_middleware_guardrail("pause-opentelemetry")?;
    application_result?;
    Ok(())
}

```

Python and Node.js use `try` and `finally` for cleanup. Rust attempts
deregistration after the application future completes, then returns the
application result if deregistration succeeds.

> **Rust Cleanup Limitations**
>
> Dropping this example's future while application work is pending skips
> deregistration and can leave the subscriber gate registered and the subscriber
> excluded. If application work and deregistration both fail, the example returns
> the deregistration error; the application error is lost. Use an owning cleanup
> guard when cancellation must remove the gate, and handle both errors explicitly
> when both must be retained.

If a gate callback fails, Relay keeps the target eligible and adds a runtime
diagnostic.

## Middleware Registration Families

The runtime exposes the same registration families for tool and LLM calls:

* Sanitize-request guardrails change emitted start-event payloads only
* Sanitize-response guardrails change emitted end-event payloads only
* Conditional-execution guardrails return an allow-or-block decision
* Request intercepts change the real request before execution
* Execution intercepts wrap the callback and may post-process or short-circuit
* LLM stream execution intercepts wrap streaming provider callbacks

Every family also has a scope-local surface:

* Python: `nemo_relay.scope_local.register_*`
* Node.js: `scopeRegister*`
* Rust: middleware `scope_register_*` functions under
  `nemo_relay::registry`; subscriber scope registration under
  `nemo_relay::subscriber`

Use [Add Middleware](/nemo/relay/v1.0.0/instrument-applications/advanced-guide) for an end-to-end policy example and [API Reference](/nemo/relay/v1.0.0/reference/api) for symbol-level details.