Code Examples
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:
Managed Tool Execution
Pass the tool name, JSON-compatible arguments, and the tool function to the
Execute helper. The function returns a canonical ToolExecutionResult.
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.
Python
Node.js
Rust
Calling the example function returns the following value:
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.
Python
Node.js
Rust
After closing the stream, the example function returns the first chunk:
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:
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.
Python
Node.js
Rust
With the guide’s subscriber registered, both paths print these tool lifecycle lines. Enclosing application scopes can print additional lines:
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
Node.js
Rust
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
Node.js
Rust
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.
Python
Node.js
Rust
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.
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 undernemo_relay::registry; subscriber scope registration undernemo_relay::subscriber
Use Add Middleware for an end-to-end policy example and API Reference for symbol-level details.