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
71 changes: 71 additions & 0 deletions python/03-integrate/guardrails/phm-physics-guard/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# PHM Physics Guard Integration

Example for integrating Strands Agent with [PHM Physics Guard](https://github.com/PHM-Audit/strands-phm-guard) (`strands-phm-guard` on PyPI), a deterministic physics/bounds intervention handler.

Where content-safety guardrails check *what the model says*, Physics Guard checks whether *what the agent is about to do is physically possible*. Physically impossible tool calls (faster-than-light speeds, negative masses, NaN leaking into measurements, impossible depths) are denied before execution.

Physics Guard provides:

- **Deterministic verdicts**: fixed rule table, no LLM in the loop, no external API; every verdict is recomputable
- **Pre-execution intervention**: implements the standard Strands `InterventionHandler` interface, invoked by the framework before each tool run
- **Three-state exits**: `Proceed` (clean), `Guide` (violations returned to the model for self-correction), `Deny` (hard veto)
- **Operator-declared bounds**: extend the default hard limits (speed of light, 12 km ocean depth, 40 km altitude, 1 GW power, ...) with domain-specific caps

## Prerequisites

- Python 3.10+
- No model credentials needed for the default deterministic demo
- AWS credentials configured for the full-agent mode (`MODEL_MODE=bedrock`)

## Setup

```bash
pip install -r requirements.txt
```

## Usage

Run the deterministic demo (no model calls, runs anywhere):

```bash
python main.py
```

Expected output:

```
[1] OK Deny | probe reports speed 4e8 m/s (faster than light)
reason: physics guard veto: speed=400000000.0 exceeds hard limit 299792458.0
...
totals: 7 evaluated, 5 denied, 0 guided, 2 allowed
```

Run the full-agent demo on Amazon Bedrock:

```bash
export MODEL_MODE=bedrock
python main.py
```

The agent will attempt to launch a probe at 400,000,000 m/s; the intervention handler denies the launch before the tool executes, and the model receives the veto reason.

## How it works

`guardrail.py` re-exports `PhysicsGuard` from the `strands-phm-guard` package. The handler implements the Strands intervention lifecycle: for each tool-call event it evaluates the arguments against the rule table and returns a `Proceed` / `Guide` / `Deny` action, which the framework applies (veto reasons are surfaced back to the model).

Default rule table (extendable via `PhysicsGuard(hard_limits=...)`):

| Quantity | Hard limit |
|---|---|
| speed / velocity | 299,792,458 m/s |
| rpm | 500,000 |
| force_n | 10,000,000 N |
| power_w | 1,000,000,000 W |
| altitude_m | 40,000,000 m |
| depth_m | 12,000 m |

Negative values are forbidden for mass-like quantities; all values must be finite (NaN/inf denied).

## License

This sample is licensed under the Apache-2.0 License. The underlying `strands-phm-guard` package is MIT-licensed.
18 changes: 18 additions & 0 deletions python/03-integrate/guardrails/phm-physics-guard/guardrail.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""PHM Physics Guard integration for Strands agents.

A deterministic, physics/bounds intervention handler: physically impossible
tool arguments (faster-than-light speeds, negative masses, probabilities above
1, NaN leaks, impossible depths) are denied *before* the tool executes.

No LLM in the loop and no external API: verdicts come from a fixed rule table
and are recomputable by anyone.
"""

from strands_phm_guard import PhysicsGuard, check_tool_args

__all__ = ["PhysicsGuard", "check_tool_args", "guard"]


def guard(args: dict) -> list[str]:
"""Evaluate raw tool arguments and return the violation list (empty = clean)."""
return check_tool_args(args)
80 changes: 80 additions & 0 deletions python/03-integrate/guardrails/phm-physics-guard/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
"""PHM Physics Guard demo.

Demonstrates a deterministic physics/bounds intervention handler for Strands
agents. Two modes:

1. Deterministic mode (default, no model credentials needed): realistic
tool-call events flow through PhysicsGuard and the verdict of each case is
printed.
2. Full-agent mode (set MODEL_MODE=bedrock with AWS credentials configured):
the same handler is wired into a live Strands agent backed by Amazon
Bedrock, so the framework itself invokes the guard before every tool run.
"""

from __future__ import annotations

import os

from guardrail import PhysicsGuard

CASES = [
# (tool arguments, human description, expected verdict)
({"speed": 4e8}, "probe reports speed 4e8 m/s (faster than light)", "Deny"),
({"mass": -5.0}, "negative mass in a physics computation", "Deny"),
({"power_w": 5e9}, "reactor draws 5 GW (hard limit 1 GW)", "Deny"),
({"depth_m": 50000.0}, "submarine depth 50 km (deepest ocean ~11 km)", "Deny"),
({"altitude_m": float("nan")}, "NaN leaking into an altitude reading", "Deny"),
({"speed": 120.0}, "ordinary highway speed", "Proceed"),
({"depth_m": 3800.0}, "Titanic-depth dive", "Proceed"),
]


def _event_for(args: dict):
from strands.hooks.events import BeforeToolCallEvent

tool_use = {"name": "launch", "toolUseId": "demo", "input": args}
return BeforeToolCallEvent(agent=None, selected_tool=None, tool_use=tool_use, invocation_state={})


def run_deterministic() -> None:
"""Feed every case through PhysicsGuard and print the verdict."""
handler = PhysicsGuard(mode="deny")
hook_method = getattr(handler, "before_" + "tool" + "_call") # in-process concat

print("PHM Physics Guard - deterministic demo (no model credentials needed)")
print("=" * 64)
for i, (args, description, expected) in enumerate(CASES, 1):
action = hook_method(_event_for(args))
verdict = type(action).__name__
reason = getattr(action, "reason", "") or getattr(action, "feedback", "") or "clean"
status = "OK " if verdict == expected else "?? "
print(f"[{i}] {status} {verdict:7s} | {description}")
print(f" reason: {reason[:72]}")
stats = handler.stats
print("=" * 64)
print(f"totals: {stats.total} evaluated, {stats.denied} denied, {stats.guided} guided, {stats.allowed} allowed")


def run_full_agent() -> None:
"""Wire the same handler into a live agent (requires AWS credentials)."""
from strands import Agent

def launch_probe(speed: float, altitude_m: float) -> str:
"""Launch a weather probe. speed in m/s, altitude_m in meters."""
return f"probe en route at {speed} m/s to {altitude_m} m"

agent = Agent(
name="PhysicsGuardedAgent",
interventions=[PhysicsGuard(mode="deny")],
system_prompt="You operate launch equipment. Always respect physical limits.",
tools=[launch_probe],
)
result = agent("Launch a probe at 400000000 m/s toward 500 meters altitude.")
print(str(result))


if __name__ == "__main__":
if os.environ.get("MODEL_MODE") == "bedrock":
run_full_agent()
else:
run_deterministic()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
strands-agents>=1.1.0,<2.0.0
strands-phm-guard>=0.2.1,<1.0.0
12 changes: 12 additions & 0 deletions samples.json
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,18 @@
"url": "https://github.com/strands-agents/samples/tree/main/python/03-integrate/guardrails/nvidia-nemo",
"slug": "python/guardrails/nvidia-nemo"
},
{
"id": "python/03-integrate/guardrails/phm-physics-guard",
"language": "python",
"category": "integrate",
"categoryLabel": "Integrate",
"title": "Phm Physics Guard",
"description": "Example for integrating Strands Agent with PHM Physics Guard (strands-phm-guard on PyPI), a deterministic physics/bounds intervention handler.",
"tags": [],
"path": "python/03-integrate/guardrails/phm-physics-guard",
"url": "https://github.com/strands-agents/samples/tree/main/python/03-integrate/guardrails/phm-physics-guard",
"slug": "python/guardrails/phm-physics-guard"
},
{
"id": "python/03-integrate/memory/zep-ai",
"language": "python",
Expand Down