|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +"""Example Python worker plugin using the nemo-relay-plugin SDK.""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +from typing import Any |
| 9 | + |
| 10 | +from nemo_relay_plugin import ConfigDiagnostic, DiagnosticLevel, Json, PluginContext, WorkerPlugin, serve_plugin |
| 11 | + |
| 12 | + |
| 13 | +class ExamplePythonWorker(WorkerPlugin): |
| 14 | + """Small worker plugin that tags tool request JSON and emits a host mark.""" |
| 15 | + |
| 16 | + plugin_id = "examples.python_grpc_worker" |
| 17 | + |
| 18 | + def validate(self, config: Json) -> list[ConfigDiagnostic | dict[str, Any]]: |
| 19 | + if isinstance(config, dict) and config.get("reject") is True: |
| 20 | + return [ |
| 21 | + ConfigDiagnostic( |
| 22 | + level=DiagnosticLevel.ERROR, |
| 23 | + code="examples.python_grpc_worker.rejected", |
| 24 | + component=self.plugin_id, |
| 25 | + field="reject", |
| 26 | + message="Python gRPC worker rejection requested", |
| 27 | + ) |
| 28 | + ] |
| 29 | + if isinstance(config, dict) and "tag" in config and not isinstance(config["tag"], str): |
| 30 | + return [ |
| 31 | + ConfigDiagnostic( |
| 32 | + level=DiagnosticLevel.ERROR, |
| 33 | + code="examples.python_grpc_worker.invalid_tag", |
| 34 | + component=self.plugin_id, |
| 35 | + field="tag", |
| 36 | + message="tag must be a string", |
| 37 | + ) |
| 38 | + ] |
| 39 | + return [] |
| 40 | + |
| 41 | + def register(self, ctx: PluginContext, config: Json) -> None: |
| 42 | + tag = config.get("tag", "python_grpc_worker") if isinstance(config, dict) else "python_grpc_worker" |
| 43 | + |
| 44 | + async def tag_tool_request(tool_name: str, args: Json) -> Json: |
| 45 | + tagged_args = _tag_json(args, tag) |
| 46 | + await ctx.runtime.emit_mark( |
| 47 | + "examples.python_grpc_worker.tool_request", |
| 48 | + {"tool_name": tool_name, "source": "python-grpc-worker", "tag": tag}, |
| 49 | + ) |
| 50 | + return tagged_args |
| 51 | + |
| 52 | + ctx.register_tool_request_intercept("tag_tool_request", tag_tool_request) |
| 53 | + |
| 54 | + |
| 55 | +def _tag_json(value: Json, tag: str) -> Json: |
| 56 | + if not isinstance(value, dict): |
| 57 | + raise TypeError("configured tool request tagging requires a JSON object") |
| 58 | + if tag in value: |
| 59 | + raise ValueError(f"tool request already contains configured tag {tag!r}") |
| 60 | + return {**value, tag: True} |
| 61 | + |
| 62 | + |
| 63 | +async def main() -> None: |
| 64 | + """Entrypoint referenced by relay-plugin.toml.""" |
| 65 | + await serve_plugin(ExamplePythonWorker()) |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + import asyncio |
| 70 | + |
| 71 | + asyncio.run(main()) |
0 commit comments