Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ Some examples require extra dependencies. See each sample's directory for specif
* [message_passing/safe_message_handlers](message_passing/safe_message_handlers/) - Safely handling updates and signals.
* [message_passing/update_with_start/lazy_initialization](message_passing/update_with_start/lazy_initialization/) - Use update-with-start to update a Shopping Cart, starting it if it does not exist.
* [microsoft_agent_framework_plugin](microsoft_agent_framework_plugin) - Run Microsoft Agent Framework agents as durable Temporal Workflows (model calls, tools, MCP, approvals, streaming, Continue-As-New).
* [nemo_relay_plugin](nemo_relay_plugin) - Record a Workflow run as one NVIDIA NeMo Relay trace, and wait for a person's approval when a Relay guardrail asks for one (LangGraph, OpenAI Agents SDK, NVIDIA NIM).
* [nexus_cancel](nexus_cancel) - Fan out concurrent Nexus operations, take the first result, and cancel the rest.
* [nexus_messaging](nexus_messaging): Demonstrates how to send signal, update and query messages through Nexus.
This contains two samples, one sending messages to an existing workflow and a second that creates a workflow through Nexus
Expand Down
77 changes: 77 additions & 0 deletions nemo_relay_plugin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# NeMo Relay plugin samples

These samples show the [Temporal plugin for NVIDIA NeMo Relay](https://github.com/temporalio/ai-integrations/tree/main/python/nemo_relay). [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. On Temporal each step of an agent runs as an Activity, often in another process, so Relay records every step as a trace of its own. `NeMoRelayPlugin` tells each Activity which Workflow run it belongs to. The run then shows up as one Relay trace, and the trace ID is the Workflow's first Run ID without the dashes. With the OpenAI Agents SDK, a tool call that a Relay guardrail blocks can also wait for a person's approval. The docs page is [NVIDIA NeMo Relay](https://docs.temporal.io/develop/python/integrations/nemo-relay).

> **Pre-release.** The `temporalio-nemo-relay` package and its interfaces may change before General Availability.

`NeMoRelayPlugin` goes on the Client, before the agent framework's plugin. Workers built from that Client inherit it.

## Samples

| Sample | Description |
|--------|-------------|
| [hello_world](hello_world) | Two Activities that record their work with Relay, and one Relay trace for the Workflow run. Start here. |
| [langgraph_agent](langgraph_agent) | A LangGraph agent whose three nodes run as Activities on two Task Queues: one trace with the plugin, three without it. |
| [human_in_the_loop](human_in_the_loop) | An OpenAI Agents SDK agent on NVIDIA NIM. A Relay guardrail asks for a person's approval before a tool runs, and the Workflow waits for the decision. |
| [failure_modes](failure_modes) | A tool that fails once and is retried, and a tool that a guardrail blocks, with what Relay and Event History record for each. |

## Prerequisites

1. Python 3.11 or later on Linux, Windows or Apple silicon macOS. NeMo Relay publishes no wheel for Intel macOS, so there the `nemo-relay` dependency group leaves the plugin out and the tests are not collected.

2. Install the dependencies from the repository root:

```bash
uv sync --group nemo-relay
```

This installs `temporalio-nemo-relay` with its `openai-agents` extra, `temporalio-langgraph` and `langgraph`.

3. A local Temporal Service from the [Temporal CLI](https://docs.temporal.io/cli):

```bash
temporal server start-dev
```

4. For `human_in_the_loop` only, an NVIDIA API key from [build.nvidia.com](https://build.nvidia.com/):

```bash
export NVIDIA_API_KEY=...
```

The other three samples use stand-in models and need no key.

## Running a sample

Each sample has two scripts. Start the Worker first, then the starter in a second terminal, both from the repository root:

```bash
# Terminal 1: start the Worker
uv run nemo_relay_plugin/<sample>/run_worker.py

# Terminal 2: start the Workflow
uv run nemo_relay_plugin/<sample>/run_workflow.py
```

Each Worker prints the Relay events it emits. A line names the event and ends with the root of the event's trace, which is the Workflow's first Run ID:

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

The lines come from the Relay subscriber in [`relay_events.py`](relay_events.py). To send the events to a backend instead, give `NeMoRelayPlugin` a Relay plugin configuration with `plugins_toml` or `plugin_config`. The plugin then runs Relay's exporters while a Worker runs.

## Tests

The tests run every sample against a local dev server, with stand-in models and no API key:

```bash
uv run --group nemo-relay pytest tests/nemo_relay_plugin
```

## Related

- [Temporal plugin for NVIDIA NeMo Relay](https://github.com/temporalio/ai-integrations/tree/main/python/nemo_relay)
- [NVIDIA NeMo Relay](https://github.com/NVIDIA/NeMo-Relay)
- [NVIDIA NeMo Relay docs page](https://docs.temporal.io/develop/python/integrations/nemo-relay)
Empty file added nemo_relay_plugin/__init__.py
Empty file.
51 changes: 51 additions & 0 deletions nemo_relay_plugin/failure_modes/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Failure modes

An agent whose two tool calls go wrong in two different ways, so you can see what Temporal and NeMo Relay record for each. `restart_node` fails on its first attempt, and Temporal retries it. A Relay guardrail never allows `wipe_node`, so that Activity fails with an error that Temporal does not retry, and the model gets the rejection as the tool's output. The model is scripted, so both failures happen on every run and the sample needs no API key.

## What this sample demonstrates

- A retry in the same Relay trace as the first attempt. Each attempt has its own `RunActivity:` scope, tagged `temporal.attempt`.
- A guardrail rejection. The Activity fails with an `ApplicationError` of type `RelayGuardrailRejected`, and its own code never runs.
- The Activity type of a governed tool, `nemo_relay.governed.<activity name>`
- A Workflow that completes after both failures, because the model gets the rejection as the tool's output

## Running the sample

Prerequisites: `uv sync --group nemo-relay` and a running Temporal dev server (`temporal server start-dev`).

```bash
# Terminal 1
uv run nemo_relay_plugin/failure_modes/run_worker.py

# Terminal 2
uv run nemo_relay_plugin/failure_modes/run_workflow.py
```

The starter prints the agent's answer, then how each governed tool call went, read from the Workflow's Event History:

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

The Worker prints the Relay events and logs both failures. The scope `RunActivity:nemo_relay.governed.restart_node` appears twice, once per attempt, with the first attempt's `RuntimeError` between them. For `wipe_node` the guardrail `never-wipe-a-node` runs and no `tool start` line follows, because Relay stops at the rejection:

```
[relay] function start RunActivity:nemo_relay.governed.wipe_node trace root 01a23d37-1414-71f4-8e9b-bed8bdb033d6
[relay] guardrail start never-wipe-a-node trace root 01a23d37-1414-71f4-8e9b-bed8bdb033d6
[relay] guardrail end never-wipe-a-node trace root 01a23d37-1414-71f4-8e9b-bed8bdb033d6
[relay] mark wipe_node trace root 01a23d37-1414-71f4-8e9b-bed8bdb033d6
[relay] function end RunActivity:nemo_relay.governed.wipe_node trace root 01a23d37-1414-71f4-8e9b-bed8bdb033d6
```

## Files

| File | Description |
|------|-------------|
| `activities.py` | `restart_node`, which fails on its first attempt, and `wipe_node` |
| `policy.py` | The Relay guardrail that rejects every call of `wipe_node` |
| `model.py` | The scripted model that asks for both tools |
| `workflow.py` | `FailureModesWorkflow`, with both Activities as governed tools |
| `run_worker.py` | Puts `NeMoRelayPlugin` and `OpenAIAgentsPlugin` on the Client, registers the guardrail, starts the Worker |
| `run_workflow.py` | Starts the Workflow, prints the result and how each governed tool call went |
Empty file.
24 changes: 24 additions & 0 deletions nemo_relay_plugin/failure_modes/activities.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""Two tools that do not go well: one fails once, and policy never allows the other."""

from temporalio import activity


# @@@SNIPSTART python-nemo-relay-failure-modes-activities
@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
77 changes: 77 additions & 0 deletions nemo_relay_plugin/failure_modes/model.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"""A scripted model, so the same two failures happen on every run and no API key is needed."""

import json
from collections.abc import AsyncIterator
from typing import Any

from agents import (
AgentOutputSchemaBase,
Handoff,
Model,
ModelProvider,
ModelResponse,
ModelSettings,
ModelTracing,
Tool,
TResponseInputItem,
)
from agents.items import TResponseStreamEvent
from temporalio.openai_agents.testing import ResponseBuilders

NODE = json.dumps({"node_id": "dgx-03"})


class ScriptedModel(Model):
"""Ask for a restart, then for a wipe, then sum up.

The model picks its next step from the tool results in its input, so a retried model
Activity gets the same answer.
"""

async def get_response(
self,
system_instructions: str | None,
input: str | list[TResponseInputItem],
model_settings: ModelSettings,
tools: list[Tool],
output_schema: AgentOutputSchemaBase | None,
handoffs: list[Handoff],
tracing: ModelTracing,
**kwargs: Any,
) -> ModelResponse:
tool_results = 0
if not isinstance(input, str):
tool_results = sum(
1 for item in input if item.get("type") == "function_call_output"
)
if tool_results == 0:
return ResponseBuilders.tool_call(
NODE, "restart_node", call_id="call_restart", item_id="item_restart"
)
if tool_results == 1:
return ResponseBuilders.tool_call(
NODE, "wipe_node", call_id="call_wipe", item_id="item_wipe"
)
return ResponseBuilders.output_message(
"Restarted dgx-03. Policy did not allow the wipe."
)

def stream_response(
self,
system_instructions: str | None,
input: str | list[TResponseInputItem],
model_settings: ModelSettings,
tools: list[Tool],
output_schema: AgentOutputSchemaBase | None,
handoffs: list[Handoff],
tracing: ModelTracing,
**kwargs: Any,
) -> AsyncIterator[TResponseStreamEvent]:
raise NotImplementedError("This sample does not stream.")


class ScriptedModelProvider(ModelProvider):
"""Give every agent the scripted model, whatever model name it asks for."""

def get_model(self, model_name: str | None) -> Model:
return ScriptedModel()
27 changes: 27 additions & 0 deletions nemo_relay_plugin/failure_modes/policy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""The NeMo Relay policy of this sample: nobody may wipe a node."""

from typing import Any

from nemo_relay import guardrails

POLICY = "never-wipe-a-node"


# @@@SNIPSTART python-nemo-relay-failure-modes-policy
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


def deregister_policy() -> None:
guardrails.deregister_tool_conditional_execution(POLICY)
49 changes: 49 additions & 0 deletions nemo_relay_plugin/failure_modes/run_worker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""Worker for the failure modes sample."""

import asyncio
import os
from datetime import timedelta

from temporalio.client import Client
from temporalio.nemo_relay import NeMoRelayPlugin
from temporalio.openai_agents import ModelActivityParameters, OpenAIAgentsPlugin
from temporalio.worker import Worker

from nemo_relay_plugin.failure_modes.activities import restart_node, wipe_node
from nemo_relay_plugin.failure_modes.model import ScriptedModelProvider
from nemo_relay_plugin.failure_modes.policy import register_policy
from nemo_relay_plugin.failure_modes.workflow import TASK_QUEUE, FailureModesWorkflow
from nemo_relay_plugin.relay_events import print_relay_events


async def main() -> None:
# The model is scripted, so turn off the OpenAI Agents SDK's own trace export.
os.environ["OPENAI_AGENTS_DISABLE_TRACING"] = "1"

client = await Client.connect(
os.environ.get("TEMPORAL_ADDRESS", "localhost:7233"),
plugins=[
NeMoRelayPlugin(),
OpenAIAgentsPlugin(
model_params=ModelActivityParameters(
start_to_close_timeout=timedelta(seconds=30)
),
model_provider=ScriptedModelProvider(),
),
],
)
register_policy()
print_relay_events()

worker = Worker(
client,
task_queue=TASK_QUEUE,
workflows=[FailureModesWorkflow],
activities=[restart_node, wipe_node],
)
print("Worker started. Ctrl+C to exit.")
await worker.run()


if __name__ == "__main__":
asyncio.run(main())
58 changes: 58 additions & 0 deletions nemo_relay_plugin/failure_modes/run_workflow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""Run the agent, then show how each tool call went, as Event History recorded it."""

import asyncio
import os

from temporalio.client import Client, WorkflowHandle

from nemo_relay_plugin.failure_modes.workflow import TASK_QUEUE, FailureModesWorkflow


async def tool_calls(handle: WorkflowHandle) -> list[str]:
"""Describe each governed tool call: its Activity type, its attempts and how it ended."""
scheduled: dict[int, str] = {}
attempts: dict[int, int] = {}
lines: list[str] = []
async for event in handle.fetch_history_events():
if event.HasField("activity_task_scheduled_event_attributes"):
name = event.activity_task_scheduled_event_attributes.activity_type.name
if name.startswith("nemo_relay.governed."):
scheduled[event.event_id] = name
elif event.HasField("activity_task_started_event_attributes"):
started = event.activity_task_started_event_attributes
attempts[started.scheduled_event_id] = started.attempt
elif event.HasField("activity_task_completed_event_attributes"):
done = event.activity_task_completed_event_attributes.scheduled_event_id
if done in scheduled:
lines.append(
f"{scheduled[done]}: completed on attempt {attempts[done]}"
)
elif event.HasField("activity_task_failed_event_attributes"):
failed = event.activity_task_failed_event_attributes
if failed.scheduled_event_id in scheduled:
error = failed.failure.application_failure_info.type
lines.append(
f"{scheduled[failed.scheduled_event_id]}: failed with {error} "
f"on attempt {attempts[failed.scheduled_event_id]}, not retried"
)
return lines


async def main() -> None:
client = await Client.connect(os.environ.get("TEMPORAL_ADDRESS", "localhost:7233"))

handle = await client.start_workflow(
FailureModesWorkflow.run,
"dgx-03 is stuck. Restart it, then wipe it.",
id="nemo-relay-failure-modes",
task_queue=TASK_QUEUE,
)
result = await handle.result()

print(f"Result: {result}")
for line in await tool_calls(handle):
print(line)


if __name__ == "__main__":
asyncio.run(main())
Loading
Loading