Skip to navigation

Code Examples

View as MarkdownOpen in Claude

Use these examples after Instrument a Tool Call or Instrument an 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:

NeedPreferred APIUse When
Run a tool with full instrumentationtools.execute, toolCallExecute, tool_call_executeApplication code owns the callback.
Run an LLM call with full instrumentationllm.execute, llmCallExecute, llm_call_executeApplication code owns the provider call.
Run a streaming LLM callllm_stream_execute, typedLlmStreamExecute, llm_stream_call_executeYou need chunk collection and one final aggregate end event.
Emit start/end manuallycall and call_end helpersA framework owns the real invocation boundary.
Emit a checkpointscope.event, eventYou need milestone visibility inside an active scope.
Emit an OTLP log markGeneric mark API with typed severityA sanitized checkpoint should become a telemetry log record.
Record an OTLP metricmetricOne validated measurement group should be routed to the metric pipeline.
Attach work to one requestScope-local registration helpersMiddleware 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.

PythonNode.jsRust
nemo_relay.tools.executetoolCallExecutetool_call_execute

Refer to Instrument a Tool Call 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.

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

Calling the example function returns the following value:

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.

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

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

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:

FailureWhere 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 for the flush API and exporter requirements for each binding.

Manual Tool Lifecycle

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 and Instrument an LLM Call 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 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.

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

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

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)

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.

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()

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.

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.

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")

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 for an end-to-end policy example and API Reference for symbol-level details.