redloop 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- redloop/__init__.py +5 -0
- redloop/__main__.py +3 -0
- redloop/cli.py +431 -0
- redloop/config.py +130 -0
- redloop/converters.py +273 -0
- redloop/crosswalk.py +63 -0
- redloop/data/aixwalk/README.md +8 -0
- redloop/data/aixwalk/crosswalk.json +452 -0
- redloop/data/aixwalk/frameworks/iso-42001-annex-a.json +45 -0
- redloop/data/aixwalk/frameworks/mitre-atlas.json +949 -0
- redloop/data/aixwalk/frameworks/nist-ai-rmf-1.0.json +369 -0
- redloop/data/aixwalk/frameworks/owasp-agentic-2026.json +49 -0
- redloop/data/aixwalk/frameworks/owasp-llm-2025.json +49 -0
- redloop/data/maturity-model.json +425 -0
- redloop/data/templates/assessment.toml +41 -0
- redloop/data/templates/redloop.toml +41 -0
- redloop/data/templates/risk-acceptances.toml +11 -0
- redloop/data/templates/threatmodel.toml +136 -0
- redloop/detectors.py +138 -0
- redloop/evidence.py +140 -0
- redloop/governance.py +106 -0
- redloop/maturity.py +340 -0
- redloop/probes/__init__.py +48 -0
- redloop/probes/base.py +194 -0
- redloop/probes/catalog.py +383 -0
- redloop/py.typed +0 -0
- redloop/report/__init__.py +22 -0
- redloop/report/jsonout.py +13 -0
- redloop/report/md.py +98 -0
- redloop/report/sarif.py +103 -0
- redloop/report/text.py +90 -0
- redloop/results.py +253 -0
- redloop/runner.py +99 -0
- redloop/sandbox.py +207 -0
- redloop/targets/__init__.py +59 -0
- redloop/targets/base.py +109 -0
- redloop/targets/http.py +132 -0
- redloop/targets/mock.py +254 -0
- redloop/targets/openai.py +145 -0
- redloop/targets/transport.py +125 -0
- redloop/threats.py +485 -0
- redloop/util.py +135 -0
- redloop-0.1.0.dist-info/METADATA +278 -0
- redloop-0.1.0.dist-info/RECORD +48 -0
- redloop-0.1.0.dist-info/WHEEL +4 -0
- redloop-0.1.0.dist-info/entry_points.txt +2 -0
- redloop-0.1.0.dist-info/licenses/LICENSE +202 -0
- redloop-0.1.0.dist-info/licenses/NOTICE +16 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Adapter for any OpenAI-compatible Chat Completions endpoint (stdlib urllib only)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import time
|
|
8
|
+
import urllib.request
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from ..util import ConfigError, redact_headers
|
|
12
|
+
from .base import Capabilities, Exchange, Response, Target, TargetError, ToolCall
|
|
13
|
+
from .transport import Transport
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class OpenAICompatibleTarget(Target):
|
|
17
|
+
kind = "openai"
|
|
18
|
+
|
|
19
|
+
def __init__(self, cfg: dict[str, Any]) -> None:
|
|
20
|
+
try:
|
|
21
|
+
self.base_url = str(cfg["base_url"]).rstrip("/")
|
|
22
|
+
self.model = str(cfg["model"])
|
|
23
|
+
except KeyError as exc:
|
|
24
|
+
raise ConfigError(f"[target] type=openai requires {exc.args[0]!r}") from exc
|
|
25
|
+
self.api_key_env = cfg.get("api_key_env")
|
|
26
|
+
self.system_prompt = str(cfg.get("system_prompt", ""))
|
|
27
|
+
self.temperature = float(cfg.get("temperature", 0))
|
|
28
|
+
self.max_tokens = int(cfg.get("max_tokens", 512))
|
|
29
|
+
self.timeout_s = float(cfg.get("timeout_s", 60))
|
|
30
|
+
self.transport = Transport(cfg)
|
|
31
|
+
self.use_tools = bool(cfg.get("tools", True))
|
|
32
|
+
self.document_placement = str(cfg.get("document_placement", "user"))
|
|
33
|
+
if self.document_placement not in ("user", "system"):
|
|
34
|
+
raise ConfigError("[target] document_placement must be 'user' or 'system'")
|
|
35
|
+
self.extra_headers: dict[str, str] = {str(k): str(v) for k, v in cfg.get("headers", {}).items()}
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def capabilities(self) -> Capabilities:
|
|
39
|
+
return Capabilities(
|
|
40
|
+
controls_system_prompt=True, accepts_documents=True, supports_tools=self.use_tools
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def default_system_prompt(self) -> str:
|
|
45
|
+
return self.system_prompt
|
|
46
|
+
|
|
47
|
+
def _api_key(self) -> str | None:
|
|
48
|
+
if not self.api_key_env:
|
|
49
|
+
return None
|
|
50
|
+
key = os.environ.get(str(self.api_key_env))
|
|
51
|
+
if key is None:
|
|
52
|
+
raise ConfigError(f"environment variable {self.api_key_env} is not set")
|
|
53
|
+
return key
|
|
54
|
+
|
|
55
|
+
def secrets(self) -> list[str]:
|
|
56
|
+
key = os.environ.get(str(self.api_key_env)) if self.api_key_env else None
|
|
57
|
+
return [key] if key else []
|
|
58
|
+
|
|
59
|
+
def describe(self) -> dict[str, Any]:
|
|
60
|
+
return {
|
|
61
|
+
"type": "openai",
|
|
62
|
+
"base_url": self.base_url,
|
|
63
|
+
"model": self.model,
|
|
64
|
+
"api_key_env": self.api_key_env,
|
|
65
|
+
"tools": self.use_tools,
|
|
66
|
+
"document_placement": self.document_placement,
|
|
67
|
+
"headers": redact_headers(self.extra_headers),
|
|
68
|
+
**self.transport.describe(),
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
def build_payload(self, ex: Exchange) -> dict[str, Any]:
|
|
72
|
+
system = ex.system if ex.system is not None else self.system_prompt
|
|
73
|
+
messages: list[dict[str, Any]] = []
|
|
74
|
+
context = ""
|
|
75
|
+
if ex.documents:
|
|
76
|
+
context = "Context documents:\n" + "\n".join(
|
|
77
|
+
f"<document>\n{d}\n</document>" for d in ex.documents
|
|
78
|
+
)
|
|
79
|
+
if system or (context and self.document_placement == "system"):
|
|
80
|
+
sys_text = system
|
|
81
|
+
if context and self.document_placement == "system":
|
|
82
|
+
sys_text = f"{system}\n\n{context}".strip()
|
|
83
|
+
messages.append({"role": "system", "content": sys_text})
|
|
84
|
+
for i, m in enumerate(ex.messages):
|
|
85
|
+
content = m.content
|
|
86
|
+
if context and self.document_placement == "user" and i == 0 and m.role == "user":
|
|
87
|
+
content = f"{context}\n\n{content}"
|
|
88
|
+
messages.append({"role": m.role, "content": content})
|
|
89
|
+
payload: dict[str, Any] = {
|
|
90
|
+
"model": self.model,
|
|
91
|
+
"messages": messages,
|
|
92
|
+
"temperature": self.temperature,
|
|
93
|
+
"max_tokens": self.max_tokens,
|
|
94
|
+
}
|
|
95
|
+
if ex.tools and self.use_tools:
|
|
96
|
+
payload["tools"] = [
|
|
97
|
+
{
|
|
98
|
+
"type": "function",
|
|
99
|
+
"function": {"name": t.name, "description": t.description, "parameters": t.parameters},
|
|
100
|
+
}
|
|
101
|
+
for t in ex.tools
|
|
102
|
+
]
|
|
103
|
+
return payload
|
|
104
|
+
|
|
105
|
+
def send(self, exchange: Exchange) -> Response:
|
|
106
|
+
payload = self.build_payload(exchange)
|
|
107
|
+
headers = {"Content-Type": "application/json", **self.extra_headers}
|
|
108
|
+
key = self._api_key()
|
|
109
|
+
if key:
|
|
110
|
+
headers["Authorization"] = f"Bearer {key}"
|
|
111
|
+
req = urllib.request.Request(
|
|
112
|
+
f"{self.base_url}/chat/completions",
|
|
113
|
+
data=json.dumps(payload).encode("utf-8"),
|
|
114
|
+
headers=headers,
|
|
115
|
+
method="POST",
|
|
116
|
+
)
|
|
117
|
+
start = time.perf_counter()
|
|
118
|
+
body = self.transport.request_json(req, self.timeout_s, self.base_url)
|
|
119
|
+
latency = (time.perf_counter() - start) * 1000
|
|
120
|
+
return parse_chat_completion(body, latency)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def parse_chat_completion(body: dict[str, Any], latency_ms: float = 0.0) -> Response:
|
|
124
|
+
try:
|
|
125
|
+
message = body["choices"][0]["message"]
|
|
126
|
+
except (KeyError, IndexError, TypeError) as exc:
|
|
127
|
+
raise TargetError("unexpected response shape (no choices[0].message)") from exc
|
|
128
|
+
text = message.get("content") or ""
|
|
129
|
+
calls = []
|
|
130
|
+
for call in message.get("tool_calls") or []:
|
|
131
|
+
fn = call.get("function", call)
|
|
132
|
+
calls.append(ToolCall(str(fn.get("name", "")), _parse_args(fn.get("arguments"))))
|
|
133
|
+
return Response(text=str(text), tool_calls=calls, raw=body, latency_ms=latency_ms)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _parse_args(args: Any) -> dict[str, Any]:
|
|
137
|
+
if isinstance(args, dict):
|
|
138
|
+
return args
|
|
139
|
+
if isinstance(args, str):
|
|
140
|
+
try:
|
|
141
|
+
parsed = json.loads(args)
|
|
142
|
+
except json.JSONDecodeError:
|
|
143
|
+
return {"_raw": args}
|
|
144
|
+
return parsed if isinstance(parsed, dict) else {"_value": parsed}
|
|
145
|
+
return {}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Shared HTTP transport for network targets: client-side pacing and polite retries.
|
|
2
|
+
|
|
3
|
+
Real endpoints rate-limit. ``requests_per_minute`` spaces requests out before they are sent,
|
|
4
|
+
and responses with status 429 or 5xx (and transient network errors) are retried with
|
|
5
|
+
exponential backoff, honouring a numeric ``Retry-After`` header when one is present.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import gzip
|
|
11
|
+
import json
|
|
12
|
+
import time
|
|
13
|
+
import zlib
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.request
|
|
16
|
+
from collections.abc import Callable
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from ..util import ConfigError
|
|
20
|
+
from .base import TargetError
|
|
21
|
+
|
|
22
|
+
RETRY_STATUSES = frozenset({429, 500, 502, 503, 504})
|
|
23
|
+
MAX_SLEEP_S = 120.0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Transport:
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
cfg: dict[str, Any],
|
|
30
|
+
*,
|
|
31
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
32
|
+
clock: Callable[[], float] = time.monotonic,
|
|
33
|
+
) -> None:
|
|
34
|
+
try:
|
|
35
|
+
self.requests_per_minute = float(cfg.get("requests_per_minute", 0))
|
|
36
|
+
self.max_retries = int(cfg.get("max_retries", 3))
|
|
37
|
+
self.backoff_s = float(cfg.get("backoff_s", 2.0))
|
|
38
|
+
except (TypeError, ValueError) as exc:
|
|
39
|
+
raise ConfigError(f"[target] invalid retry/pacing setting: {exc}") from exc
|
|
40
|
+
if self.requests_per_minute < 0 or self.max_retries < 0 or self.backoff_s < 0:
|
|
41
|
+
raise ConfigError("[target] requests_per_minute, max_retries and backoff_s must be >= 0")
|
|
42
|
+
self._sleep = sleep
|
|
43
|
+
self._clock = clock
|
|
44
|
+
self._next_slot = 0.0
|
|
45
|
+
self.retries = 0 # total retries performed, for evidence
|
|
46
|
+
|
|
47
|
+
def describe(self) -> dict[str, Any]:
|
|
48
|
+
return {
|
|
49
|
+
"requests_per_minute": self.requests_per_minute,
|
|
50
|
+
"max_retries": self.max_retries,
|
|
51
|
+
"backoff_s": self.backoff_s,
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
def _pace(self) -> None:
|
|
55
|
+
if self.requests_per_minute <= 0:
|
|
56
|
+
return
|
|
57
|
+
interval = 60.0 / self.requests_per_minute
|
|
58
|
+
now = self._clock()
|
|
59
|
+
if now < self._next_slot:
|
|
60
|
+
self._sleep(self._next_slot - now)
|
|
61
|
+
now = self._next_slot
|
|
62
|
+
self._next_slot = now + interval
|
|
63
|
+
|
|
64
|
+
def _retry_delay(self, attempt: int, retry_after: str | None) -> float:
|
|
65
|
+
if retry_after:
|
|
66
|
+
try:
|
|
67
|
+
return min(max(float(retry_after), 0.0), MAX_SLEEP_S)
|
|
68
|
+
except ValueError:
|
|
69
|
+
pass # HTTP-date form: fall back to exponential backoff
|
|
70
|
+
return min(self.backoff_s * (2**attempt), MAX_SLEEP_S)
|
|
71
|
+
|
|
72
|
+
def request_json(self, req: urllib.request.Request, timeout: float, label: str) -> Any:
|
|
73
|
+
"""Send ``req`` and return the decoded JSON body, retrying transient failures."""
|
|
74
|
+
attempt = 0
|
|
75
|
+
while True:
|
|
76
|
+
self._pace()
|
|
77
|
+
try:
|
|
78
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
79
|
+
raw = resp.read()
|
|
80
|
+
status = getattr(resp, "status", None)
|
|
81
|
+
headers = getattr(resp, "headers", None)
|
|
82
|
+
content_type = headers.get("Content-Type", "") if headers else ""
|
|
83
|
+
encoding = (headers.get("Content-Encoding", "") if headers else "").lower()
|
|
84
|
+
except urllib.error.HTTPError as exc:
|
|
85
|
+
if exc.code in RETRY_STATUSES and attempt < self.max_retries:
|
|
86
|
+
delay = self._retry_delay(attempt, exc.headers.get("Retry-After") if exc.headers else None)
|
|
87
|
+
attempt += 1
|
|
88
|
+
self.retries += 1
|
|
89
|
+
self._sleep(delay)
|
|
90
|
+
continue
|
|
91
|
+
raise TargetError(f"HTTP {exc.code} from {label}") from exc
|
|
92
|
+
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
|
93
|
+
if attempt < self.max_retries:
|
|
94
|
+
delay = self._retry_delay(attempt, None)
|
|
95
|
+
attempt += 1
|
|
96
|
+
self.retries += 1
|
|
97
|
+
self._sleep(delay)
|
|
98
|
+
continue
|
|
99
|
+
raise TargetError(f"cannot reach {label}: {exc}") from exc
|
|
100
|
+
raw = _decompress(raw, encoding)
|
|
101
|
+
try:
|
|
102
|
+
return json.loads(raw.decode("utf-8-sig"))
|
|
103
|
+
except (json.JSONDecodeError, UnicodeDecodeError) as exc:
|
|
104
|
+
raise TargetError(_not_json_message(status, content_type, raw)) from exc
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _decompress(raw: bytes, encoding: str) -> bytes:
|
|
108
|
+
try:
|
|
109
|
+
if encoding == "gzip" or raw[:2] == b"\x1f\x8b":
|
|
110
|
+
return gzip.decompress(raw)
|
|
111
|
+
if encoding == "deflate":
|
|
112
|
+
return zlib.decompress(raw)
|
|
113
|
+
except (OSError, zlib.error, EOFError):
|
|
114
|
+
return raw
|
|
115
|
+
return raw
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _not_json_message(status: int | None, content_type: str, raw: bytes) -> str:
|
|
119
|
+
snippet = " ".join(raw[:200].decode("utf-8", "replace").split())
|
|
120
|
+
if not snippet:
|
|
121
|
+
snippet = "<empty body>"
|
|
122
|
+
return (
|
|
123
|
+
f"response was not JSON (HTTP {status if status is not None else '?'}, "
|
|
124
|
+
f"content-type {content_type or 'unset'}): {snippet!r}"
|
|
125
|
+
)
|