-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsentinel_protocol_adapters.py
More file actions
295 lines (250 loc) · 9.06 KB
/
sentinel_protocol_adapters.py
File metadata and controls
295 lines (250 loc) · 9.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
"""Single-file Python adapters for local Sentinel prompt scanning.
This module intentionally duplicates the callback implementations so reviewers and
developers can import one file directly from `python/` with zero packaging steps.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.request
from typing import Any, Callable, Dict, List, Optional
DEFAULT_PLAYGROUND_ENDPOINT = "http://127.0.0.1:8787/_sentinel/playground/analyze"
class SentinelScanError(RuntimeError):
"""Raised when local Sentinel scan request fails."""
EventSink = Callable[[Dict[str, Any]], None]
def _safe_str(value: Any) -> str:
if value is None:
return ""
if isinstance(value, str):
return value
try:
return json.dumps(value, ensure_ascii=True)
except Exception:
return str(value)
def scan_prompt(
prompt: str,
endpoint: str = DEFAULT_PLAYGROUND_ENDPOINT,
timeout_seconds: float = 3.0,
correlation_id: str = "",
) -> Dict[str, Any]:
"""Run local Sentinel playground analysis for a prompt string."""
body = {
"prompt": _safe_str(prompt),
}
data = json.dumps(body).encode("utf-8")
request = urllib.request.Request(
endpoint,
data=data,
headers={
"content-type": "application/json",
**({"x-sentinel-correlation-id": correlation_id} if correlation_id else {}),
},
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=timeout_seconds) as response:
text = response.read().decode("utf-8")
return json.loads(text) if text else {}
except urllib.error.HTTPError as error:
raw = error.read().decode("utf-8", errors="replace")
raise SentinelScanError(f"sentinel_scan_http_error:{error.code}:{raw}") from error
except urllib.error.URLError as error:
raise SentinelScanError(f"sentinel_scan_unreachable:{error.reason}") from error
class _BaseAdapter:
def __init__(
self,
endpoint: str = DEFAULT_PLAYGROUND_ENDPOINT,
timeout_seconds: float = 3.0,
on_event: Optional[EventSink] = None,
fail_open: bool = True,
) -> None:
self.endpoint = endpoint
self.timeout_seconds = float(timeout_seconds)
self.on_event = on_event
self.fail_open = bool(fail_open)
def _emit(self, event: Dict[str, Any]) -> None:
if self.on_event is not None:
self.on_event(event)
def _scan(self, prompt: str, correlation_id: str = "") -> Dict[str, Any]:
return scan_prompt(
prompt=prompt,
endpoint=self.endpoint,
timeout_seconds=self.timeout_seconds,
correlation_id=correlation_id,
)
def _scan_safe(self, prompt: str, correlation_id: str = "") -> Dict[str, Any]:
try:
return self._scan(prompt, correlation_id=correlation_id)
except SentinelScanError:
if self.fail_open:
return {
"summary": {
"risk": "unknown",
"engines_evaluated": 0,
"detections": 0,
"block_eligible": 0,
},
"error": "scan_failed_fail_open",
}
raise
class LangChainSentinelCallbackHandler(_BaseAdapter):
"""LangChain-style callback handler."""
def handleLLMStart(self, llm: Any, prompts: Optional[List[str]] = None, runId: Optional[str] = None) -> None:
payload = {
"framework": "langchain",
"event": "agent.start",
"run_id": _safe_str(runId),
"model": _safe_str(getattr(llm, "modelName", None) or getattr(llm, "model", None)),
"prompt_count": len(prompts or []),
}
if prompts:
payload["scan"] = self._scan_safe("\n".join(_safe_str(item) for item in prompts), correlation_id=_safe_str(runId))
self._emit(payload)
def handleLLMEnd(self, output: Any, runId: Optional[str] = None) -> None:
self._emit(
{
"framework": "langchain",
"event": "agent.complete",
"run_id": _safe_str(runId),
"output_preview": _safe_str(output)[:512],
}
)
def handleLLMError(self, error: Exception, runId: Optional[str] = None) -> None:
self._emit(
{
"framework": "langchain",
"event": "agent.error",
"run_id": _safe_str(runId),
"error": _safe_str(error),
}
)
class LlamaIndexSentinelCallback(_BaseAdapter):
"""LlamaIndex-style callback hook."""
def on_start(self, meta: Optional[Dict[str, Any]] = None) -> None:
meta = meta or {}
prompt = _safe_str(meta.get("prompt", ""))
payload = {
"framework": "llamaindex",
"event": "agent.start",
"run_id": _safe_str(meta.get("runId", "")),
}
if prompt:
payload["scan"] = self._scan_safe(prompt, correlation_id=payload["run_id"])
self._emit(payload)
def on_complete(self, meta: Optional[Dict[str, Any]] = None) -> None:
meta = meta or {}
self._emit(
{
"framework": "llamaindex",
"event": "agent.complete",
"run_id": _safe_str(meta.get("runId", "")),
}
)
def on_error(self, error: Exception, meta: Optional[Dict[str, Any]] = None) -> None:
meta = meta or {}
self._emit(
{
"framework": "llamaindex",
"event": "agent.error",
"run_id": _safe_str(meta.get("runId", "")),
"error": _safe_str(error),
}
)
class CrewAISentinelHook(_BaseAdapter):
"""CrewAI-style lifecycle hook adapter."""
def on_task_start(self, task_description: str, run_id: str = "") -> None:
scan = self._scan_safe(task_description, correlation_id=run_id)
self._emit(
{
"framework": "crewai",
"event": "task.start",
"run_id": _safe_str(run_id),
"scan": scan,
}
)
def on_task_end(self, result: Any, run_id: str = "") -> None:
self._emit(
{
"framework": "crewai",
"event": "task.complete",
"run_id": _safe_str(run_id),
"result_preview": _safe_str(result)[:512],
}
)
def on_task_error(self, error: Exception, run_id: str = "") -> None:
self._emit(
{
"framework": "crewai",
"event": "task.error",
"run_id": _safe_str(run_id),
"error": _safe_str(error),
}
)
class AutoGenSentinelHook(_BaseAdapter):
"""AutoGen-style lifecycle hook adapter."""
def on_turn_start(self, message: Any, run_id: str = "") -> None:
scan = self._scan_safe(_safe_str(message), correlation_id=run_id)
self._emit(
{
"framework": "autogen",
"event": "turn.start",
"run_id": _safe_str(run_id),
"scan": scan,
}
)
def on_turn_complete(self, result: Any, run_id: str = "") -> None:
self._emit(
{
"framework": "autogen",
"event": "turn.complete",
"run_id": _safe_str(run_id),
"result_preview": _safe_str(result)[:512],
}
)
def on_turn_error(self, error: Exception, run_id: str = "") -> None:
self._emit(
{
"framework": "autogen",
"event": "turn.error",
"run_id": _safe_str(run_id),
"error": _safe_str(error),
}
)
class LangGraphSentinelHook(_BaseAdapter):
"""LangGraph-style lifecycle hook adapter."""
def on_node_start(self, node: Any, run_id: str = "") -> None:
scan = self._scan_safe(_safe_str(node), correlation_id=run_id)
self._emit(
{
"framework": "langgraph",
"event": "node.start",
"run_id": _safe_str(run_id),
"scan": scan,
}
)
def on_node_complete(self, result: Any, run_id: str = "") -> None:
self._emit(
{
"framework": "langgraph",
"event": "node.complete",
"run_id": _safe_str(run_id),
"result_preview": _safe_str(result)[:512],
}
)
def on_node_error(self, error: Exception, run_id: str = "") -> None:
self._emit(
{
"framework": "langgraph",
"event": "node.error",
"run_id": _safe_str(run_id),
"error": _safe_str(error),
}
)
__all__ = [
"scan_prompt",
"SentinelScanError",
"LangChainSentinelCallbackHandler",
"LlamaIndexSentinelCallback",
"CrewAISentinelHook",
"AutoGenSentinelHook",
"LangGraphSentinelHook",
]