Skip to main content

NVIDIA NeMo Relay integration

View Markdown

NVIDIA NeMo Relay records every model call and tool call that an agent makes, and applies guardrails to those calls. Temporal's integration with NeMo Relay is an SDK Plugin that records a Workflow Execution as one Relay trace.

Relay tracks an agent run in memory. On Temporal, each step of an agent runs as an Activity, often in another process or on another machine, where that memory is missing. Relay then records every step as a trace of its own: a five-node LangGraph agent leaves five traces, and you can't see the run as a whole. The plugin tells each Activity which Workflow Execution it belongs to, and you don't change agent code.

With the OpenAI Agents SDK, a tool call that a Relay guardrail blocks can wait for a person's approval instead of failing. The Workflow records the request and waits for the decision, so no process has to stay alive during the wait.

You don't need the plugin when the whole agent runs in one Activity, because Relay already records that as one trace.

Code snippets in this guide are taken from the NeMo Relay plugin samples. Refer to the samples for the complete code.

Prerequisites​

  • This guide assumes you are familiar with NeMo Relay. If you aren't, start with the NeMo Relay documentation.
  • If you are new to Temporal, read Understanding Temporal or take the Temporal 101 course.
  • Set up your local development environment by following Set up your local development environment. Leave the Temporal development server running if you want to test your code locally.
  • Use Python 3.11 or later on Linux, Windows, or Apple silicon macOS. NeMo Relay publishes no wheel for Intel macOS.
  • Export NVIDIA_API_KEY in the Worker's environment to run the approval sample, which calls a model on NVIDIA NIM. The other samples use stand-in models and need no key.

Install the plugin​

Install the temporalio-nemo-relay package:

uv add temporalio-nemo-relay

or with pip:

pip install temporalio-nemo-relay

The package depends on temporalio, nemo-relay, and httpx2, which is enough to carry Relay's context to every Activity. governed_activity_as_tool and relay_openai_client also need the OpenAI Agents SDK integration, which the openai-agents extra installs:

uv add "temporalio-nemo-relay[openai-agents]"

Refer to the package requirements for the supported Python, Temporal SDK, and NeMo Relay versions.

Import NeMoRelayPlugin, relay_openai_client, and requires_temporal_approval from temporalio.nemo_relay, and governed_activity_as_tool from temporalio.nemo_relay.workflow.

Record a Workflow Execution as one trace​

Add NeMoRelayPlugin to the Client. Workers created from that Client inherit the plugin. When you also use the plugin of an agent framework, put NeMoRelayPlugin before it. The Relay scope of an Activity then also covers the framework's interceptors.

nemo_relay_plugin/hello_world/run_worker.py

client = await Client.connect(
os.environ.get("TEMPORAL_ADDRESS", "localhost:7233"),
plugins=[NeMoRelayPlugin()],
)

worker = Worker(
client,
task_queue="nemo-relay-hello-world",
workflows=[HelloWorldWorkflow],
activities=[read_temperature, write_summary],
)

NeMoRelayPlugin has no required arguments. Pass plugins_toml or plugin_config to activate Relay's plugin host, which loads Relay's exporters, redaction, and pricing, and your own policy components. The host stays active while any Worker that uses this NeMoRelayPlugin runs, and Workers that share one NeMoRelayPlugin share the host. Without those arguments, events still reach the subscribers that your application registers. The samples register a subscriber that prints each event.

Activities record their work with Relay as they do outside Temporal. In the hello world sample, one Activity makes a Relay-managed tool call and the other records an event:

nemo_relay_plugin/hello_world/activities.py

@activity.defn
async def read_temperature(node_id: str) -> Reading:
# A Relay-managed tool call. Relay records it under the scope of this Activity.
reading: Any = await tools.execute(
"read_sensor", {"node_id": node_id}, _read_sensor
)
return Reading(node_id, reading.result["celsius"], current_trace_id())


@activity.defn
async def write_summary(reading: Reading) -> Summary:
text = f"{reading.node_id} is at {reading.celsius} C"
scope.event("summary_written", data={"node_id": reading.node_id})
return Summary(text, current_trace_id())

The Workflow has no Relay code. The plugin sends Relay's context with each Activity in a Temporal header:

nemo_relay_plugin/hello_world/workflow.py

@workflow.defn
class HelloWorldWorkflow:
@workflow.run
async def run(self, node_id: str) -> HelloWorldResult:
# Nothing here is about Relay. The plugin sends Relay's context with each Activity.
reading = await workflow.execute_activity(
read_temperature,
node_id,
start_to_close_timeout=timedelta(seconds=10),
)
summary = await workflow.execute_activity(
write_summary,
reading,
start_to_close_timeout=timedelta(seconds=10),
)
return HelloWorldResult(summary.text, [reading.trace_id, summary.trace_id])

Each Activity attempt runs in a Relay scope named RunActivity:<activity type>, and what the Activity records with Relay nests under that scope. The sample's Worker prints each event with the root of its trace:

[relay] function start RunActivity:read_temperature trace root 01a23d35-d418-746c-bf7c-1cab70955c3e
[relay] tool start read_sensor trace root 01a23d35-d418-746c-bf7c-1cab70955c3e
[relay] tool end read_sensor trace root 01a23d35-d418-746c-bf7c-1cab70955c3e
[relay] function end RunActivity:read_temperature trace root 01a23d35-d418-746c-bf7c-1cab70955c3e
[relay] function start RunActivity:write_summary trace root 01a23d35-d418-746c-bf7c-1cab70955c3e
[relay] mark summary_written trace root 01a23d35-d418-746c-bf7c-1cab70955c3e
[relay] function end RunActivity:write_summary trace root 01a23d35-d418-746c-bf7c-1cab70955c3e

The root of the trace is the Workflow's first Run ID. Relay derives the OpenTelemetry trace identifier from the root, so the trace identifier is the first Run ID without the dashes:

Workflow Run ID: 01a23d35-d418-746c-bf7c-1cab70955c3e
Relay trace ID: 01a23d35d418746cbf7c1cab70955c3e

Use the first Run ID of a Workflow Execution to find its trace, or a trace identifier to find the Workflow Execution.

The Workflow Execution has no scope of its own, so the RunActivity scopes are siblings under the root. Each one carries these values in its metadata:

Metadata keyValue
temporal.workflow_id and session.idThe Workflow ID
temporal.run_idThe Run ID of the run that started the Activity
temporal.task_queueThe Task Queue of the Activity
temporal.activity_typeThe Activity Type
temporal.activity_idThe Activity ID
temporal.attemptThe attempt number, starting at 1

Activities on any Worker, in any process, and on any retry join the same trace. A Child Workflow joins the trace of its parent. The root stays the same across Continue-As-New and Workflow retries.

To continue the trace of the program that starts the Workflow, pass propagate_client_context=True to the plugin. start_workflow then sends the caller's Relay scope, and the caller's context reaches every Activity unchanged, with its W3C traceparent and tracestate.

Trace a LangGraph agent​

Temporal's LangGraph integration runs each node with execute_in="activity" as its own Activity. With NeMoRelayPlugin on the Client, those nodes write to one trace. You don't change graph state or node code.

Install both packages:

uv add temporalio-nemo-relay temporalio-langgraph

In the sample, three nodes record their work with Relay:

nemo_relay_plugin/langgraph_agent/workflow.py

async def plan(state: State) -> State:
with scope.scope("plan", ScopeType.Function):
text = await _call_model(f"Plan how to answer: {state['question']}")
return {"plan": text, "trace_ids": _trace_ids(state)}


async def research(state: State) -> State:
with scope.scope("research", ScopeType.Function):
found: Any = await tools.execute(
"search", {"query": state["question"]}, _search
)
summary = await _call_model(
"\n".join([f"Summarize: {state['question']}", *found.result["hits"]])
)
return {"findings": [summary], "trace_ids": _trace_ids(state)}


async def answer(state: State) -> State:
with scope.scope("answer", ScopeType.Function):
text = await _call_model(
"\n".join([f"Answer: {state['question']}", *state["findings"]])
)
return {"answer": text, "trace_ids": _trace_ids(state)}

_call_model makes a Relay-managed model call with nemo_relay.llm.execute. Each node also returns the identifier of the trace it wrote to, so the sample can count the traces.

The graph runs every node as an Activity, and runs research on a second Task Queue:

nemo_relay_plugin/langgraph_agent/workflow.py

def build_graph(tools_task_queue: str = TOOLS_TASK_QUEUE) -> StateGraph:
in_activity = {
"execute_in": "activity",
"start_to_close_timeout": timedelta(seconds=30),
}
g = StateGraph(State)
g.add_node("plan", plan, metadata=in_activity)
# Another Task Queue. Only the Temporal header links this node to the other two.
g.add_node(
"research", research, metadata={**in_activity, "task_queue": tools_task_queue}
)
g.add_node("answer", answer, metadata=in_activity)
g.add_edge(START, "plan")
g.add_edge("plan", "research")
g.add_edge("research", "answer")
g.add_edge("answer", END)
return g

Both plugins go on the Client:

nemo_relay_plugin/langgraph_agent/run_worker.py

client = await Client.connect(
os.environ.get("TEMPORAL_ADDRESS", "localhost:7233"),
plugins=[
# NeMoRelayPlugin goes before LangGraphPlugin. agent_activities=True gives each
# node's Activity a Relay Agent scope, the type that Relay's own LangGraph
# integration gives a node.
NeMoRelayPlugin(agent_activities=True),
LangGraphPlugin(graphs={GRAPH: build_graph()}),
],
)

agent_activities=True runs every Activity attempt in a Relay Agent scope, the type that Relay's own LangGraph integration gives a node. Relay's Agent Trajectory Interchange Format (ATIF) exporter writes one trajectory per top-level Agent scope. Under the root, that scope is an Activity, so the exporter writes one trajectory per Activity, not one for the whole Workflow Execution. Each trajectory has the Workflow's first Run ID as its session_id. That differs from the session.id metadata key, which is the Workflow ID. To select some Activities, pass a list of Activity Types instead of True.

The sample's starter prints the traces that the three nodes wrote to. There is one, and its identifier is the Run ID without the dashes:

Workflow Run ID: 01a23d36-22ea-79a4-873b-5908a31b75c3
3 nodes, 1 Relay trace(s):
01a23d3622ea79a4873b5908a31b75c3

Start the sample's Workers with --without-relay-plugin, and every node starts a trace of its own, even when two nodes run on the same Worker:

Workflow Run ID: 01a23d36-5f7c-75c0-9115-ebc16700f1dc
3 nodes, 3 Relay trace(s):
01a23d365f897ef28c7b96d7ebc35bcf
01a23d365f8e7a508ea57a27a008d49a
01a23d365f927102adb5c06582c8ad10

Inside a node, Relay's LangGraph integration works as Relay's LangGraph guide shows: NemoRelayCallbackHandler, create_tool_node, and NemoRelayMiddleware record under the Activity's scope. Install it with uv add "nemo-relay[langgraph]". Nodes with execute_in="workflow" and routing functions aren't traced, because Relay never runs in Workflow code.

Run model calls through Relay​

With the OpenAI Agents SDK integration, each model call runs as an Activity. relay_openai_client() returns an AsyncOpenAI client. Its chat/completions and responses calls that don't stream run through nemo_relay.llm.execute. Relay's guardrails, request intercepts, sanitizers, and pricing then apply to each of those calls, and the call appears in the trace. Streaming calls and other requests go to the endpoint without Relay. The client works with OpenAI-compatible endpoints such as NVIDIA NIM.

Pass the client to OpenAIProvider as openai_client:

nemo_relay_plugin/human_in_the_loop/run_worker.py

client = await Client.connect(
os.environ.get("TEMPORAL_ADDRESS", "localhost:7233"),
plugins=[
NeMoRelayPlugin(),
OpenAIAgentsPlugin(
model_params=ModelActivityParameters(
start_to_close_timeout=timedelta(minutes=2)
),
model_provider=OpenAIProvider(
# Each model call runs through Relay, so Relay's guardrails apply to it and
# it is in the trace.
openai_client=relay_openai_client(
base_url=NIM_BASE_URL,
api_key=os.environ["NVIDIA_API_KEY"],
),
use_responses=False,
),
),
],
)
register_policy()

worker = Worker(
client,
task_queue=TASK_QUEUE,
workflows=[FleetTriageWorkflow],
activities=[get_gpu_fleet_status, open_maintenance_ticket],
)

register_policy() registers the guardrail that the next section describes.

When a Relay guardrail rejects a model call, the model Activity fails with an error that Temporal doesn't retry.

Wait for a person's approval​

A governed tool is an Activity that runs through Relay's guardrails. When a guardrail asks for a person's approval, the Workflow waits for the decision.

Make an Activity a governed tool​

governed_activity_as_tool is activity_as_tool with Relay's governance added. The Worker runs the Activity through nemo_relay.tools.execute, so Relay's tool guardrails and intercepts apply.

nemo_relay_plugin/human_in_the_loop/workflow.py

@workflow.defn
class FleetTriageWorkflow:
@workflow.run
async def run(self, request: TriageRequest) -> str:
agent = Agent(
name="GPU fleet triage",
model=request.model,
instructions=INSTRUCTIONS,
tools=[
activity_as_tool(
get_gpu_fleet_status,
start_to_close_timeout=timedelta(seconds=10),
),
# A governed tool runs through Relay's guardrails. When a guardrail asks for an
# approval, the Workflow waits for the approve_tool Update, for up to a day here.
governed_activity_as_tool(
open_maintenance_ticket,
start_to_close_timeout=timedelta(seconds=10),
approval_timeout=timedelta(days=1),
),
],
)
result = await Runner.run(agent, request.prompt)
return str(result.final_output)

approval_timeout is how long the Workflow waits for a decision. Without it, the Workflow waits until a decision arrives.

For each Activity that a Worker has when NeMoRelayPlugin configures it, the plugin registers a second Activity Type, nemo_relay.governed.<activity name>, that runs the same function through Relay. A governed tool call is scheduled on that Activity Type. So a governed tool needs an Activity that you give the Worker directly. An Activity that a later plugin adds gets no governed Activity Type, and neither does a Dynamic Activity.

Warning

Keep a Worker that has a Dynamic Activity and no NeMoRelayPlugin off the Task Queue of a governed tool. A Dynamic Activity takes every Activity Type that its Worker doesn't have by name, the governed ones included, so that Worker would run a governed tool call with no guardrail. Pass task_queue to governed_activity_as_tool to put the tool on a Task Queue of its own, and let only Workers with the plugin poll it. Or make the Dynamic Activity raise an error for the Activity Types that start with nemo_relay.governed..

Register the guardrail​

requires_temporal_approval builds a Relay tool guardrail from a predicate. For the calls that the predicate selects, the guardrail asks the Workflow whether a person has approved this tool call. Register the guardrail on the Worker, from a Relay plugin or with nemo_relay.guardrails.register_tool_conditional_execution:

nemo_relay_plugin/human_in_the_loop/policy.py

def needs_approval(tool_name: str, args: dict[str, Any]) -> bool:
return tool_name == "open_maintenance_ticket" and args.get("priority") == "P0"


def register_policy() -> None:
"""Register the guardrail with Relay. A Worker does this once, before it runs."""
guardrails.register_tool_conditional_execution(
POLICY,
10,
# The guardrail rejects the call until the Workflow that owns it has recorded a
# person's approval of that one tool call.
requires_temporal_approval(
needs_approval,
reason="A P0 ticket takes the node out of service, so a person must approve it",
),
)

A guardrail gets a tool's arguments by parameter name. An Activity gets positional arguments, and the plugin binds them to parameter names before it hands them to Relay, so the predicate can read args.get("priority").

Approvals need an async def Activity that you turned into a tool with governed_activity_as_tool. The guardrail sends a Query to the Workflow with the Activity's Client, and a sync Activity has no Client. For any other tool call that the predicate selects, the guardrail raises and Relay doesn't run the tool.

When the model asks for a P0 ticket, the following happens:

  1. The guardrail rejects the call. The Activity fails with a non-retryable ApplicationError of type RelayApprovalRequired, and its own code doesn't run.
  2. The Workflow records a pending approval and shows it through the tool_approvals Query.
  3. The Workflow waits for the approve_tool Update.
  4. On an approval, the Activity runs again. The guardrail finds the decision in the Workflow and allows the call.
  5. On a denial, or when approval_timeout passes, the model gets a denial message as the tool's output. Pass on_deny="raise" to fail the tool call instead.

The approval never travels in arguments or headers, so neither the model nor an Activity input can forge it.

Send the decision​

Any Client can read the pending approvals and send a decision. A Query needs a Worker, so tool_approvals and guardrails built with requires_temporal_approval need a Worker that polls the Workflow's Task Queue. The sample's starter asks at the terminal:

nemo_relay_plugin/human_in_the_loop/run_workflow.py

async def decide_pending_approvals(handle: WorkflowHandle) -> None:
"""Show each tool call that waits for a person, and send the person's decision."""
ledger = await handle.query(TOOL_APPROVALS_QUERY, result_type=ToolApprovalLedger)
for pending in ledger.pending.values():
print(f"\n{pending.tool_name} needs an approval: {pending.reason}")
print(f" arguments: {pending.args}")
answer = await asyncio.to_thread(input, " Approve? [y/N] ")
await handle.execute_update(
APPROVE_TOOL_UPDATE,
# A decision is for the one tool call that tool_call_id names.
ToolApprovalDecision(
tool_call_id=pending.tool_call_id,
approved=answer.strip().lower() == "y",
approver="fleet-lead",
),
)

The Temporal CLI works too:

temporal workflow query -w <workflow-id> --name tool_approvals
temporal workflow update execute -w <workflow-id> --name approve_tool \
-i '{"tool_call_id": "...", "approved": true, "approver": "fleet-lead", "note": "fan tray confirmed"}'

After a denial, the model gets Tool call denied by fleet-lead: followed by the note, or by the guardrail's reason when there is no note.

After an approval, the sample's Workflow Execution has this trace. The model Activities of the OpenAI Agents SDK integration always run in an Agent scope, so each model call nests under its Activity:

Run ID 01a23d47-eb0d-7d88-9302-f994d0411862 root, not a scope
├─ RunActivity:invoke_model_activity agent
│ └─ nvidia/nemotron-3-super-120b-a12b llm
├─ RunActivity:get_gpu_fleet_status function
├─ RunActivity:invoke_model_activity agent
│ └─ nvidia/nemotron-3-super-120b-a12b llm
├─ RunActivity:nemo_relay.governed.open_maintenance_ticket function
│ ├─ p0-tickets-need-approval guardrail
│ ├─ open_maintenance_ticket mark: rejected
│ └─ approval_requested mark
├─ RunActivity:nemo_relay.governed.open_maintenance_ticket function
│ ├─ p0-tickets-need-approval guardrail
│ ├─ approval_verified mark
│ └─ open_maintenance_ticket tool
└─ RunActivity:invoke_model_activity agent
└─ nvidia/nemotron-3-super-120b-a12b llm

The time that the Workflow waits for the approval is the gap between the two ticket scopes. The approval_verified mark records the approver, the note, and the time of the decision.

What a decision covers​

  • A decision covers one tool call, the one that tool_call_id names, and the retries of its Activity. If the model makes the same call again, the new call waits for a decision of its own.
  • A decision covers the arguments that the person saw. If the arguments have changed when the tool runs, for example because a deployment changed a default during the wait, the call is denied and the tool doesn't run. A Relay request intercept runs after the guardrails, so a person approves the arguments from before the rewrite, and the Activity runs with the rewritten arguments.
  • A decision covers only the approval guardrail. A call that another Relay guardrail rejects is denied, whether or not a person approved it.

Give a guardrail that blocks a call outright a lower priority number than the approval guardrail, because Relay runs guardrails in the order of their priority and stops at the first one that rejects. Otherwise a person is asked to approve a call that Relay then rejects.

See what a failure records​

The failure modes sample makes two tool calls go wrong. restart_node fails on its first attempt, and wipe_node never runs:

nemo_relay_plugin/failure_modes/activities.py

@activity.defn
async def restart_node(node_id: str) -> str:
"""Restart a node."""
attempt = activity.info().attempt
if attempt == 1:
# The first attempt fails. Temporal retries the Activity.
raise RuntimeError(f"{node_id} did not answer")
return f"restarted {node_id} on attempt {attempt}"


@activity.defn
async def wipe_node(node_id: str) -> str:
"""Erase the disks of a node."""
# A Relay guardrail blocks this tool, so the Activity's own code never runs.
return f"wiped {node_id}"

wipe_node never runs because a guardrail rejects every call of it:

nemo_relay_plugin/failure_modes/policy.py

def never_wipe(tool_name: str, args: Any) -> str | None:
"""Reject every call of wipe_node. Relay runs a tool when no guardrail returns a reason."""
if tool_name == "wipe_node":
return f"wiping {args.get('node_id', 'a node')} is never allowed"
return None


def register_policy() -> None:
# No approval changes what this guardrail answers, so nobody is asked for one.
guardrails.register_tool_conditional_execution(POLICY, 5, never_wipe)

The sample's starter reads the Workflow's Event History and prints how each tool call went:

Result: Restarted dgx-03. Policy did not allow the wipe.
nemo_relay.governed.restart_node: completed on attempt 2
nemo_relay.governed.wipe_node: failed with RelayGuardrailRejected on attempt 1, not retried

Temporal retries a failed Activity under its Retry Policy. Each attempt runs in a RunActivity scope of its own, tagged temporal.attempt, in the same trace. Event History shows one Activity that completed on attempt 2, and Relay shows both attempts. Relay turns an exception raised inside a managed call into a RuntimeError, and the plugin raises the Activity's original exception again, so a non-retryable ApplicationError stays non-retryable.

When a guardrail other than an approval guardrail rejects a governed tool, the Activity fails with a non-retryable ApplicationError of type RelayGuardrailRejected, and the Activity's own code doesn't run. The model gets Tool call rejected by a NeMo Relay guardrail: and the reason as the tool's output. With on_deny="raise", the tool call fails instead.

A replay records nothing. Relay never runs in the Workflow, where the plugin only builds a header from workflow.info(). All events come from Activities and the Client.

Runtime behavior and limitations​

  • An Activity doesn't wait for Relay's exporters. Relay publishes events in the background, and its flush waits for every managed call that is under way in the process. So the plugin doesn't flush when an Activity ends. A Worker flushes when it stops.
  • Signals, Updates, and Nexus Operations don't carry the context. On the Client, only start_workflow sends the caller's context.
  • Relay has one plugin host in a process. A second NeMoRelayPlugin with a Relay configuration of its own can't run a Worker in the same process while the first one's host is active. To own the host yourself, activate it in your application with nemo_relay.plugin.activate and give the plugin no plugins_toml or plugin_config.
  • The plugin adds two headers to an Activity and nothing to its inputs or results. The headers are the Relay context and, for a governed tool, the tool's name and call identifier. A guardrail rejection carries the tool's arguments in its failure details, and the tool_approvals Query returns them for each pending tool call.
  • Relay's redaction doesn't reach Event History. Use a Payload Codec for data that must not be stored in clear text. Relay's redaction applies to what Relay exports, and Event History keeps Activity inputs and results unchanged.
  • Relay's intercepts change what a governed tool does. A request intercept can rewrite the tool's arguments, and What a decision covers says what that means for an approval. A rewrite that doesn't fit the Activity, such as an added or removed argument, fails the Activity with a non-retryable ApplicationError of type RelayRewriteUnsupported. An execution intercept can answer for the tool or change its result, and the Activity returns what Relay returns.
  • The plugin sends Heartbeats for a governed tool. When the tool has a heartbeat_timeout, the plugin sends an Activity Heartbeat at intervals of half that timeout while the guardrails, Relay's intercepts, and the Activity run.

Roll out the plugin​

  • Workers can get the plugin one at a time. An Activity that arrives without Relay's header runs as it did before.
  • A governed tool runs only on a Worker that has the plugin. A Worker that has the Activity but not the plugin fails the Activity Task for the governed Activity Type as not registered, and Temporal retries it until a Worker with the plugin takes it. So during a rollout the call waits. It doesn't run without its guardrails, unless that Worker has a Dynamic Activity. Make an Activity a governed tool says how to prevent that.
  • The Worker that runs the Workflow needs the plugin too. Without it, the tool starts no Activity and the Workflow Task fails.

Samples​

The NeMo Relay plugin samples cover the four scenarios on this page: hello world, a LangGraph agent, a person's approval, and failure modes. The repository's tests run each one with stand-in models and no API key. The plugin's source and README are in the temporalio/ai-integrations repository.