Metadata-Version: 2.4
Name: temporalio-nemo-relay
Version: 0.0.1
Summary: Temporal integration for NVIDIA NeMo Relay
Author: Temporal Technologies Inc
Author-email: Temporal Technologies Inc <sdk@temporal.io>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Typing :: Typed
Requires-Dist: temporalio>=1.36.0,<2
Requires-Dist: nemo-relay>=0.11,<0.12
Requires-Dist: httpx2>=2.12,<3
Requires-Dist: temporalio-openai-agents>=2,<3 ; extra == 'openai-agents'
Requires-Python: >=3.11
Project-URL: Homepage, https://github.com/temporalio/ai-integrations/tree/main/python/nemo_relay
Project-URL: Repository, https://github.com/temporalio/ai-integrations
Project-URL: Documentation, https://docs.temporal.io/develop/python/integrations/nemo-relay
Provides-Extra: openai-agents
Description-Content-Type: text/markdown

# Temporal NeMo Relay integration

> Release stage: **Pre-release**.

Temporal integration for [NVIDIA NeMo Relay](https://github.com/NVIDIA/NeMo-Relay), published as
[`temporalio-nemo-relay`](https://pypi.org/project/temporalio-nemo-relay/) and imported as
`temporalio.nemo_relay`.

NeMo Relay records what an agent does, every model call and tool call, and applies guardrails to
it. On Temporal, each step of an agent runs as an Activity.

## The problem

Relay code inside a Workflow's Activities is not enough. Relay tracks an agent run in memory, but
each Activity runs separately, often on another machine, without that memory. So Relay records
every step as its own run: a five-node LangGraph agent looks like five runs, and you cannot see
the run as a whole.

The plugin tells each Activity which run it belongs to. The Workflow then shows up as one trace,
with no change to agent code. With the OpenAI Agents SDK, a tool call that a Relay guardrail
blocks can also wait for a person's approval instead of failing.

## Who it is for

Use the plugin if your agents run on Temporal and use NeMo Relay, with any agent framework.

Skip it if the whole agent runs in one Activity. Relay already sees that as one run.

## What you get

| Capability | How |
|---|---|
| One Relay trace per Workflow run | Every Activity rebuilds a Relay scope stack from a context rooted at the Workflow's first Run Id. Activities on any Worker, in any process and on any retry join the same trace. Child Workflows and continue-as-new join it too. |
| Any agent framework | The context travels in Temporal headers, so it reaches an Activity whichever plugin started it. That covers [LangGraph](#langgraph) nodes and tasks, OpenAI Agents SDK model and tool calls, and Activities you start yourself. |
| Relay-managed model calls | `relay_openai_client()` returns an `AsyncOpenAI` whose chat completion and response calls run through `nemo_relay.llm.execute`, so Relay's guardrails, request intercepts, sanitizers and pricing apply. It works with OpenAI-compatible endpoints such as NVIDIA NIM. |
| Relay-managed tool calls | `governed_activity_as_tool(fn)` is `activity_as_tool` plus governance. The Worker runs the Activity through `nemo_relay.tools.execute`, so Relay's tool guardrails and intercepts apply. The call has its own Activity type, `nemo_relay.governed.<activity name>`, which only a Worker with the plugin registers. |
| Durable approvals | When a guardrail built with `requires_temporal_approval` rejects a governed tool, the Activity fails with a non-retryable `ApplicationError` of type `RelayApprovalRequired`. The Workflow records a pending approval, shows it through the `tool_approvals` Query and waits for the `approve_tool` Update. No process has to stay alive while it waits. On approval the tool runs again. A decision covers one tool call. |
| Relay asks Temporal | `requires_temporal_approval(predicate)` builds a Relay tool guardrail that queries the Workflow's approval ledger before it allows a call. The approval never travels in arguments or headers, so neither the model nor an Activity input can forge it. |

## Install

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

The package needs only `temporalio`, `nemo-relay` and `httpx2`, which is enough to carry the Relay
context to any Activity. `governed_activity_as_tool` and `relay_openai_client` need the OpenAI
Agents plugin:

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

## Use

Add `NeMoRelayPlugin` to the Client. Workers created from that Client inherit it. Put it before
the agent framework's plugin:

```python
from temporalio.client import Client
from temporalio.nemo_relay import NeMoRelayPlugin

client = await Client.connect(
    "localhost:7233",
    plugins=[NeMoRelayPlugin(plugins_toml="plugins.toml")],
)
```

`plugins_toml` and `plugin_config` are optional. With one of them, the plugin activates Relay's
plugin host (exporters, redaction, pricing, your own policy components) while a Worker of the
plugin runs. Workers that share the plugin share the host. Without them, events still reach the
subscribers your application registers.

Each Activity attempt runs in a Relay scope named `RunActivity:<activity type>`, tagged with the
Workflow Id, Run Id, Task Queue and attempt. What the Activity records with Relay nests under
that scope. Relay derives the OpenTelemetry trace id from the root, so the trace id of a run is
its first Run Id without the dashes.

## LangGraph

Temporal's LangGraph plugin runs each node as its own Activity, so every node starts a separate
Relay trace, also when two nodes run on the same Worker. Add `NeMoRelayPlugin` before
`LangGraphPlugin` and the run is one trace. Graph state and node code stay as they are.

```bash
uv add temporalio-nemo-relay temporalio-langgraph "nemo-relay[langgraph]"
```

```python
from temporalio.client import Client
from temporalio.langgraph import LangGraphPlugin
from temporalio.nemo_relay import NeMoRelayPlugin

client = await Client.connect(
    "localhost:7233",
    plugins=[
        NeMoRelayPlugin(agent_activities=True, plugins_toml="plugins.toml"),
        LangGraphPlugin(graphs={"research-agent": build_graph()}),
    ],
)
```

`agent_activities=True` runs every Activity attempt in a Relay `Agent` scope, the type Relay's own
LangGraph integration gives a node. Relay's ATIF exporter then writes one trajectory per Activity,
each with the Workflow's Run Id as its `session_id`. Pass a list of Activity types to select some.

Inside a node, Relay's LangGraph integration works as its guide shows: `NemoRelayCallbackHandler`,
`create_tool_node` and `NemoRelayMiddleware` record under the Activity's scope. Nodes with
`execute_in="workflow"` and routing functions are not traced, because Relay never runs in Workflow
code.

[`tests/test_langgraph.py`](https://github.com/temporalio/ai-integrations/blob/main/python/nemo_relay/tests/test_langgraph.py)
runs a three-node graph on two Task Queues: three trace ids without the plugin, one with it.

## OpenAI Agents SDK

Worker:

```python
import os
from datetime import timedelta

from agents import OpenAIProvider
from temporalio.client import Client
from temporalio.nemo_relay import NeMoRelayPlugin, relay_openai_client
from temporalio.openai_agents import ModelActivityParameters, OpenAIAgentsPlugin

client = await Client.connect(
    "localhost:7233",
    plugins=[
        NeMoRelayPlugin(plugins_toml="plugins.toml"),
        OpenAIAgentsPlugin(
            model_params=ModelActivityParameters(start_to_close_timeout=timedelta(minutes=2)),
            model_provider=OpenAIProvider(
                openai_client=relay_openai_client(
                    base_url="https://integrate.api.nvidia.com/v1",
                    api_key=os.environ["NVIDIA_API_KEY"],
                ),
                use_responses=False,
            ),
        ),
    ],
)
```

Workflow:

```python
from datetime import timedelta

from agents import Agent
from temporalio.nemo_relay.workflow import governed_activity_as_tool
from temporalio.openai_agents.workflow import activity_as_tool

agent = Agent(
    name="triage",
    tools=[
        activity_as_tool(get_gpu_fleet_status, start_to_close_timeout=timedelta(seconds=10)),
        governed_activity_as_tool(
            open_maintenance_ticket,
            start_to_close_timeout=timedelta(seconds=10),
            approval_timeout=timedelta(days=1),
        ),
    ],
)
```

Policy, registered from a Relay plugin or with
`nemo_relay.guardrails.register_tool_conditional_execution`:

```python
from nemo_relay import guardrails
from temporalio.nemo_relay import requires_temporal_approval

guardrails.register_tool_conditional_execution(
    "p0_requires_human_approval",
    10,
    requires_temporal_approval(
        lambda tool, args: tool == "open_maintenance_ticket" and args.get("priority") == "P0"
    ),
)
```

A human approves or denies with the Temporal CLI, or any Client:

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

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.

A decision is for the one tool call that `tool_call_id` names. If the model makes the same call
again, the new call shows up as a pending approval of its own.

Only a guardrail built with `requires_temporal_approval` asks for a decision. No decision changes
the rejection of any other Relay guardrail, so nobody is asked about it: the Activity fails with
type `RelayGuardrailRejected` and the call is denied at once. A call that a guardrail rejects
after its approval is denied too. For these calls the model gets the rejection as the tool's
output, and with `on_deny="raise"` the Activity's failure fails the tool call.

Relay runs guardrails in the order of their priority and stops at the first one that rejects.
Give a guardrail that blocks a call outright a lower priority number than the approval guardrail.
Otherwise a person is asked about a call that is rejected after the approval.

## How it works

- **Nothing from Relay runs in the Workflow.** `nemo_relay` is a native extension with
  process-wide registries. Workflow code only builds a header from `workflow.info()`. All events
  come from Activities and the Client, so replay emits nothing. A retried attempt gets a new scope
  tagged `temporal.attempt`.
- **The root is the first Run Id.** It stays the same across continue-as-new and Workflow
  retries. `NeMoRelayPlugin(propagate_client_context=True)` makes `start_workflow` send the
  caller's Relay scope instead, so the run continues the caller's trace. The caller's context
  reaches every Activity as it came, with its W3C `traceparent` and `tracestate`.
- **Workers can get the plugin one at a time.** An Activity that arrives without the header runs
  as before.
- **A governed tool runs only on a Worker that has the plugin.** For each Activity a Worker is
  given, 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 type. A Worker
  that has the Activity but not the plugin fails the task as not registered, and Temporal retries
  it until a Worker with the plugin takes it. So during a rollout the call waits. It does not run
  without its guardrails, unless that Worker has a dynamic Activity (see [Limits](#limits)). The
  Worker that runs the Workflow needs the plugin too: without it the tool starts no Activity and
  the Workflow Task fails.
- **Errors keep their type.** Relay turns an exception raised inside a managed call into a
  `RuntimeError`. The plugin raises the Activity's original exception again, so a non-retryable
  `ApplicationError` stays non-retryable. Only a guardrail rejection becomes
  `RelayGuardrailRejected`, or `RelayApprovalRequired` when the guardrail is one built with
  `requires_temporal_approval`. For a model call the transport answers `403` with
  `x-should-retry: false`, which the OpenAI Agents plugin maps to a non-retryable error.
- **A model answer comes back only when Relay is done with it.** An HTTP error from the endpoint
  reaches the OpenAI SDK as it came. If Relay fails after the endpoint answered, for example in an
  execution intercept, the call fails with that error and the answer is not returned.
- **Relay's intercepts change a model call.** A request intercept gets the normalized request and
  can rewrite it. A header that it removes does not reach the endpoint. Relay never sees the
  credential headers, and they always go out. The caller gets the result Relay returns, also when
  an execution intercept replaced the endpoint's answer.
- **Tool arguments get their names.** An Activity gets positional arguments. The plugin binds them
  to parameter names before it hands them to Relay, so a guardrail sees
  `{"node_id": ..., "priority": ...}`. The arguments that `*args` takes are bound to its name as a
  list.
- **Relay's intercepts change what a governed tool does.** A request intercept runs after the
  guardrails, so a person approves the arguments from before the rewrite. The Activity runs with
  the rewritten arguments, each converted to its parameter's type. A rewrite that does not fit the
  Activity (an argument added or removed, a value of another type) 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.
- **A governed tool heartbeats on a timer.** When the tool has a `heartbeat_timeout`, the plugin
  sends a heartbeat at half of it while the guardrails, Relay's intercepts and the Activity run.
  Its heartbeats repeat the details of the Activity's own last heartbeat, so a retry still finds
  them.
- **An Activity does not 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
  does not flush when an Activity ends: a slow model call of another Workflow would hold the
  Activity back past its Start-to-Close Timeout, and Temporal would run it again. A Worker
  flushes when it stops.
- **A decision covers one tool call.** The Workflow records it under the tool call's id, and the
  guardrail allows only that call, the retries of its Activity included. The same call made again
  waits for its own decision, whether the first one was approved or denied.
- **An approval holds for the arguments a person saw.** The Worker computes a key from the tool
  name and the arguments the Activity got, defaults included, and sends both with the rejection.
  The guardrail computes the key again before it allows the approved call. If the arguments have
  changed, for example because a deployment changed a default during the wait, the call does not
  run and is denied.
- **Payloads stay small.** The plugin adds two headers to an Activity: the Relay context, and for
  a governed tool its name and call id. It adds nothing to Activity inputs or results. A guardrail
  rejection carries the tool's arguments in its failure details, and the `tool_approvals` Query
  returns them for each pending tool call.

## Limits

- Relay's redaction applies to what Relay exports. Event History keeps Activity inputs and
  results as they are, so use a payload codec for data that must not be stored in clear text.
- One ATIF trajectory covers one Activity, not the whole run. Relay writes a trajectory per
  top-level `Agent` scope, and under the run's root that is an Activity.
- The run has no scope of its own. Activity scopes are siblings under the root.
- The transport manages `chat/completions` and `responses` calls that do not stream. Streaming
  calls and other requests pass through to the endpoint without Relay. A request body that
  Relay's codec cannot read, such as a Responses request with no `input`, goes through Relay
  without the normalized request.
- Signals, Updates and Nexus operations do not carry the context. On the Client only
  `start_workflow` sends the caller's context.
- A Query needs a running Worker, so `tool_approvals` and guardrails built with
  `requires_temporal_approval` need one polling the Workflow's Task Queue.
- `requires_temporal_approval` can approve only tools made with `governed_activity_as_tool`. For
  any other tool call that its predicate selects, the guardrail raises and Relay does not run the
  tool.
- `requires_temporal_approval` needs an `async def` Activity. The guardrail queries the Workflow
  with the Activity's Client, and a sync Activity has none. There the guardrail raises on the
  first attempt, before anyone is asked.
- A governed entry point exists for the Activities a Worker has when `NeMoRelayPlugin` configures
  it. An Activity that a later plugin adds has none, and neither does a dynamic Activity.
- A dynamic Activity takes every Activity type that its Worker does not have by name, the
  governed ones too. A Worker without the plugin that has a dynamic Activity would run a governed
  tool call in it, with no guardrail. Keep such a Worker off the Task Queue of a governed tool:
  `governed_activity_as_tool(fn, task_queue=...)` puts the tool on a Task Queue of its own, which
  only Workers with the plugin should poll. Or make the dynamic Activity refuse the types that
  start with `nemo_relay.governed.`.
- Relay has one plugin host in a process. A second `NeMoRelayPlugin` with a Relay configuration
  of its own cannot run a Worker in the same process while the first one's host is active: Relay
  refuses the second activation, and that Worker's `run()` raises. 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`.

## Documentation

- NeMo Relay: https://github.com/NVIDIA/NeMo-Relay
- Repository conventions: [`AGENTS.md`](https://github.com/temporalio/ai-integrations/blob/main/AGENTS.md)

## Develop

```bash
make sync   # install (non-editable) into .venv
make lint
make test
```
