---
title: NVIDIA NeMo Relay integration - Python SDK
description: Record a Workflow Execution as one NVIDIA NeMo Relay trace with the Python SDK, and wait for a person's approval when a Relay guardrail asks for one.
canonical: https://docs.temporal.io/develop/python/integrations/nemo-relay
last-updated: '2026-12-03'
---

# NVIDIA NeMo Relay integration

> For the complete documentation index, see [llms.txt](https://docs.temporal.io/llms.txt).
> Any documentation page is available as raw Markdown by appending `.md` to its URL.
> For related questions, query `https://docs.temporal.io/api/retrieve?q=<question>&jtb=<job-to-be-done>&src=md-page&agent=<your-name>` (no auth; returns JSON `{content, source_url, page_url}`, with `source_url` pointing to Markdown for docs pages). Don't include personal data or credentials.
> If this page is wrong or missing something you needed, or Temporal behaves differently from what it says, report it with `https://docs.temporal.io/api/feedback?title=<summary>&message=<what-happened>&category=documentation&page_url=/develop/python/integrations/nemo-relay&src=md-page&agent=<your-name>` (use `category=product` when the product, not the page, is wrong). Report only a specific problem you hit, send it once, and don't include personal data or credentials.

[NVIDIA NeMo Relay](https://github.com/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](/develop/plugins-guide) 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](/activities), 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.

> **Pre-release**

Code snippets in this guide are taken from the
[NeMo Relay plugin samples](https://github.com/temporalio/samples-python/tree/main/nemo_relay_plugin). 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](https://docs.nvidia.com/nemo/relay).
- If you are new to Temporal, read [Understanding Temporal](/evaluate/understanding-temporal) or take the
  [Temporal 101](https://learn.temporal.io/courses/temporal_101/) course.
- Set up your local development environment by following
  [Set up your local development environment](/develop/python/set-up-your-local-python). 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](https://build.nvidia.com/). The other samples use stand-in models and need no key.

## Install the plugin

Install the `temporalio-nemo-relay` package:

```bash
uv add temporalio-nemo-relay
```

or with pip:

```bash
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](/develop/python/integrations/openai-agents), which the `openai-agents` extra installs:

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

Refer to the
[package requirements](https://github.com/temporalio/ai-integrations/blob/main/python/nemo_relay/pyproject.toml) 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.

<!--SNIPSTART python-nemo-relay-hello-world-worker-->
[nemo_relay_plugin/hello_world/run_worker.py](https://github.com/temporalio/samples-python/blob/main/nemo_relay_plugin/hello_world/run_worker.py)
```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],
)
```
<!--SNIPEND-->

`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:

<!--SNIPSTART python-nemo-relay-hello-world-activities-->
[nemo_relay_plugin/hello_world/activities.py](https://github.com/temporalio/samples-python/blob/main/nemo_relay_plugin/hello_world/activities.py)
```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())
```
<!--SNIPEND-->

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

<!--SNIPSTART python-nemo-relay-hello-world-workflow-->
[nemo_relay_plugin/hello_world/workflow.py](https://github.com/temporalio/samples-python/blob/main/nemo_relay_plugin/hello_world/workflow.py)
```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])
```
<!--SNIPEND-->

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](/workflow-execution/workflowid-runid#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 key | Value |
| --- | --- |
| `temporal.workflow_id` and `session.id` | The Workflow ID |
| `temporal.run_id` | The Run ID of the run that started the Activity |
| `temporal.task_queue` | The Task Queue of the Activity |
| `temporal.activity_type` | The Activity Type |
| `temporal.activity_id` | The Activity ID |
| `temporal.attempt` | The attempt number, starting at 1 |

Activities on any Worker, in any process, and on any retry join the same trace. A
[Child Workflow](/child-workflows) joins the trace of its parent. The root stays the same across
[Continue-As-New](/workflow-execution/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](/develop/python/integrations/langgraph) 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:

```bash
uv add temporalio-nemo-relay temporalio-langgraph
```

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

<!--SNIPSTART python-nemo-relay-langgraph-agent-nodes-->
[nemo_relay_plugin/langgraph_agent/workflow.py](https://github.com/temporalio/samples-python/blob/main/nemo_relay_plugin/langgraph_agent/workflow.py)
```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)}
```
<!--SNIPEND-->

`_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](/task-queue):

<!--SNIPSTART python-nemo-relay-langgraph-agent-graph-->
[nemo_relay_plugin/langgraph_agent/workflow.py](https://github.com/temporalio/samples-python/blob/main/nemo_relay_plugin/langgraph_agent/workflow.py)
```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
```
<!--SNIPEND-->

Both plugins go on the Client:

<!--SNIPSTART python-nemo-relay-langgraph-agent-worker-->
[nemo_relay_plugin/langgraph_agent/run_worker.py](https://github.com/temporalio/samples-python/blob/main/nemo_relay_plugin/langgraph_agent/run_worker.py)
```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()}),
    ],
)
```
<!--SNIPEND-->

`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](https://docs.nvidia.com/nemo/relay/supported-integrations/langgraph) 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](/develop/python/integrations/openai-agents), 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`:

<!--SNIPSTART python-nemo-relay-human-in-the-loop-worker-->
[nemo_relay_plugin/human_in_the_loop/run_worker.py](https://github.com/temporalio/samples-python/blob/main/nemo_relay_plugin/human_in_the_loop/run_worker.py)
```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],
)
```
<!--SNIPEND-->

`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`](/develop/python/integrations/openai-agents#activity-backed-tools) with Relay's governance added.
The Worker runs the Activity through `nemo_relay.tools.execute`, so Relay's tool guardrails and intercepts apply.

<!--SNIPSTART python-nemo-relay-human-in-the-loop-workflow-->
[nemo_relay_plugin/human_in_the_loop/workflow.py](https://github.com/temporalio/samples-python/blob/main/nemo_relay_plugin/human_in_the_loop/workflow.py)
```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)
```
<!--SNIPEND-->

`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](/develop/python/workflows/message-passing#set-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`:

<!--SNIPSTART python-nemo-relay-human-in-the-loop-policy-->
[nemo_relay_plugin/human_in_the_loop/policy.py](https://github.com/temporalio/samples-python/blob/main/nemo_relay_plugin/human_in_the_loop/policy.py)
```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",
        ),
    )
```
<!--SNIPEND-->

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](/develop/python/workflows/message-passing#queries).
3. The Workflow waits for the `approve_tool` [Update](/develop/python/workflows/message-passing#updates).
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](/develop/python/workflows/message-passing#send-query), 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:

<!--SNIPSTART python-nemo-relay-human-in-the-loop-decide-->
[nemo_relay_plugin/human_in_the_loop/run_workflow.py](https://github.com/temporalio/samples-python/blob/main/nemo_relay_plugin/human_in_the_loop/run_workflow.py)
```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",
            ),
        )
```
<!--SNIPEND-->

The Temporal CLI works too:

```bash
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:

<!--SNIPSTART python-nemo-relay-failure-modes-activities-->
[nemo_relay_plugin/failure_modes/activities.py](https://github.com/temporalio/samples-python/blob/main/nemo_relay_plugin/failure_modes/activities.py)
```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}"
```
<!--SNIPEND-->

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

<!--SNIPSTART python-nemo-relay-failure-modes-policy-->
[nemo_relay_plugin/failure_modes/policy.py](https://github.com/temporalio/samples-python/blob/main/nemo_relay_plugin/failure_modes/policy.py)
```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)
```
<!--SNIPEND-->

The sample's starter reads the Workflow's [Event History](/encyclopedia/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](/encyclopedia/retry-policies). 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](/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](#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](/encyclopedia/detecting-activity-failures#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](/troubleshooting/execution-failures#unregistered-activity-invocation) 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](#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](https://github.com/temporalio/samples-python/tree/main/nemo_relay_plugin) 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](https://github.com/temporalio/ai-integrations/tree/main/python/nemo_relay).
