-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase.py
More file actions
1916 lines (1662 loc) · 77.4 KB
/
base.py
File metadata and controls
1916 lines (1662 loc) · 77.4 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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import datetime
import logging
import random
from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum, StrEnum, auto
from typing import Any, ClassVar, Dict, List, Optional, Tuple, cast
from urllib.parse import urlparse
import uuid
import httpx
from llama_stack.apis.inference import (
CompletionMessage,
Message,
SystemMessage,
ToolResponseMessage,
UserMessage,
)
from llama_stack.apis.resource import ResourceType
from llama_stack.apis.safety import (
RunShieldResponse,
Safety,
SafetyViolation,
ShieldStore,
ViolationLevel,
)
try:
from llama_stack.apis.safety import ModerationObject, ModerationObjectResults
_HAS_MODERATION = True
except ImportError:
_HAS_MODERATION = False
from llama_stack.apis.shields import ListShieldsResponse, Shield, Shields
from llama_stack.providers.datatypes import ShieldsProtocolPrivate
from ..config import (
BaseDetectorConfig,
ContentDetectorConfig,
ChatDetectorConfig,
DetectorParams,
EndpointType,
)
# Configure logging
logger = logging.getLogger(__name__)
if not _HAS_MODERATION:
logger.warning(
"llama-stack version does not support ModerationObject/ModerationObjectResults. "
"The /v1/openai/v1/moderations endpoint will not be available. "
"Upgrade to llama-stack >= 0.2.18 for moderation support."
)
# Custom exceptions
class DetectorError(Exception):
"""Base exception for detector errors"""
pass
class DetectorConfigError(DetectorError):
"""Configuration related errors"""
pass
class DetectorRequestError(DetectorError):
"""HTTP request related errors"""
pass
class DetectorValidationError(DetectorError):
"""Validation related errors"""
pass
class DetectorNetworkError(DetectorError):
"""Network connectivity issues"""
class DetectorTimeoutError(DetectorError):
"""Request timeout errors"""
class DetectorRateLimitError(DetectorError):
"""Rate limiting errors"""
class DetectorAuthError(DetectorError):
"""Authentication errors"""
# Type aliases
MessageDict = Dict[str, Any]
DetectorResponse = Dict[str, Any]
Headers = Dict[str, str]
RequestPayload = Dict[str, Any]
class MessageTypes(Enum):
"""Message type constants"""
USER = auto()
SYSTEM = auto()
TOOL = auto()
COMPLETION = auto()
@classmethod
def to_str(cls, value: MessageTypes) -> str:
"""Convert enum to string representation"""
return value.name.lower()
@dataclass(frozen=True)
class DetectionResult:
"""Structured detection result"""
detection: str
detection_type: str
score: float
detector_id: str
text: str = ""
start: int = 0
end: int = 0
metadata: Optional[Dict[str, Any]] = None
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary representation"""
return {
"detection": self.detection,
"detection_type": self.detection_type,
"score": self.score,
"detector_id": self.detector_id,
"text": self.text,
"start": self.start,
"end": self.end,
**({"metadata": self.metadata} if self.metadata else {}),
}
class BaseDetector(Safety, ShieldsProtocolPrivate, ABC):
"""Base class for all safety detectors"""
# Class constants
VALID_SCHEMES: ClassVar[set] = {"http", "https"}
def __init__(self, config: BaseDetectorConfig) -> None:
"""Initialize detector with configuration"""
self.config = config
self.registered_shields: List[Shield] = []
self.score_threshold: float = config.confidence_threshold
self._http_client: Optional[httpx.AsyncClient] = None
self._shield_store: ShieldStore = SimpleShieldStore()
self._validate_config()
@property
def shield_store(self) -> ShieldStore:
"""Get shield store instance"""
if self._shield_store is None:
self._shield_store = SimpleShieldStore()
return self._shield_store
@shield_store.setter
def shield_store(self, value: ShieldStore) -> None:
"""Set shield store instance"""
self._shield_store = value
def _validate_config(self) -> None:
"""Validate detector configuration"""
if not self.config:
raise DetectorConfigError("Configuration is required")
if not isinstance(self.config, BaseDetectorConfig):
raise DetectorConfigError(f"Invalid config type: {type(self.config)}")
async def initialize(self) -> None:
"""Initialize detector resources"""
logger.info(f"Initializing {self.__class__.__name__}")
# Get SSL configuration from config
ssl_config = {}
if hasattr(self.config, 'get_ssl_config'):
ssl_config = self.config.get_ssl_config()
# Add debug logging here
logger.debug(f"[DEBUG] SSL config for {self.config.detector_id}: {ssl_config}")
logger.debug(f"[DEBUG] ssl_cert_path: {getattr(self.config, 'ssl_cert_path', None)}")
logger.debug(f"[DEBUG] verify_ssl: {getattr(self.config, 'verify_ssl', None)}")
# Create HTTP client with SSL configuration
self._http_client = httpx.AsyncClient(
timeout=self.config.request_timeout,
limits=httpx.Limits(
max_keepalive_connections=self.config.max_keepalive_connections,
max_connections=self.config.max_connections,
),
**ssl_config # Apply SSL configuration here
)
async def shutdown(self) -> None:
"""Clean up detector resources"""
logger.info(f"Shutting down {self.__class__.__name__}")
if self._http_client:
await self._http_client.aclose()
async def register_shield(self, shield: Shield) -> None:
"""Register a shield with the detector"""
if not shield or not shield.identifier:
raise DetectorValidationError("Invalid shield configuration")
logger.info(f"Registering shield {shield.identifier}")
self.registered_shields.append(shield)
def _should_process_message(self, message: Message) -> bool:
"""Check if this detector should process the given message type"""
# Get exact message type
if isinstance(message, UserMessage):
message_type = "user"
elif isinstance(message, SystemMessage):
message_type = "system"
elif isinstance(message, ToolResponseMessage):
message_type = "tool"
elif isinstance(message, CompletionMessage):
message_type = "completion"
else:
logger.warning(f"Unknown message type: {type(message)}")
return False
# Debug logging
logger.debug(
f"Message type check - type:'{message_type}', "
f"config_types:{self.config.message_types}, "
f"detector:{self.config.detector_id}"
)
# Explicit type check
is_supported = message_type in self.config.message_types
if not is_supported:
logger.warning(
f"Message type '{message_type}' not in configured types "
f"{self.config.message_types} for detector {self.config.detector_id}"
)
return is_supported
def _filter_messages(self, messages: List[Message]) -> List[Message]:
"""Filter messages based on configured message types"""
return [msg for msg in messages if self._should_process_message(msg)]
def _validate_url(self, url: str) -> None:
"""Validate URL format"""
parsed = urlparse(url)
if not all([parsed.scheme, parsed.netloc]):
raise DetectorConfigError(f"Invalid URL format: {url}")
if parsed.scheme not in self.VALID_SCHEMES:
raise DetectorConfigError(f"Invalid URL scheme: {parsed.scheme}")
def _construct_url(self) -> str:
"""Construct API URL based on configuration"""
if self.config.use_orchestrator_api:
if not self.config.orchestrator_url:
raise DetectorConfigError(
"orchestrator_url is required when use_orchestrator_api is True"
)
base_url = self.config.orchestrator_url
endpoint_info = (
EndpointType.ORCHESTRATOR_CHAT.value
if self.config.is_chat
else EndpointType.ORCHESTRATOR_CONTENT.value
)
else:
if not self.config.detector_url:
raise DetectorConfigError(
"detector_url is required when use_orchestrator_api is False"
)
base_url = self.config.detector_url
endpoint_info = (
EndpointType.DIRECT_CHAT.value
if self.config.is_chat
else EndpointType.DIRECT_CONTENT.value
)
url = f"{base_url.rstrip('/')}{endpoint_info['path']}"
self._validate_url(url)
logger.debug(
f"Constructed URL: {url} for {'chat' if self.config.is_chat else 'content'} endpoint"
)
return url
def _extract_detector_params(self) -> Dict[str, Any]:
"""Extract detector parameters from configuration"""
detector_params: Dict[str, Any] = {}
if (
hasattr(self.config, "detector_params")
and self.config.detector_params is not None
):
# For chat detectors, extract model_params and metadata directly
if hasattr(self.config.detector_params, "model_params"):
detector_params.update(self.config.detector_params.model_params)
if hasattr(self.config.detector_params, "metadata"):
detector_params.update(self.config.detector_params.metadata)
# Include any direct parameters
for k, v in vars(self.config.detector_params).items():
if v is not None and k not in [
"model_params",
"metadata",
"kwargs",
"params",
]:
if not (isinstance(v, (dict, list)) and len(v) == 0):
detector_params[k] = v
return detector_params
def _prepare_headers(self) -> Headers:
"""Prepare request headers based on configuration"""
headers: Headers = {
"accept": "application/json",
"Content-Type": "application/json",
}
if not self.config.use_orchestrator_api and self.config.detector_id:
headers["detector-id"] = self.config.detector_id
# Use the new get_auth_headers method from config
if hasattr(self.config, 'get_auth_headers'):
auth_headers = self.config.get_auth_headers()
headers.update(auth_headers)
elif self.config.auth_token:
headers["Authorization"] = f"Bearer {self.config.auth_token}"
return headers
def _prepare_request_payload(
self, messages: List[Message], params: Optional[Dict[str, Any]] = None
) -> RequestPayload:
"""Prepare request payload based on endpoint type and orchestrator mode"""
logger.debug(
f"Preparing payload - use_orchestrator: {self.config.use_orchestrator_api}, "
f"detector_id: {self.config.detector_id}"
)
if self.config.use_orchestrator_api:
payload: RequestPayload = {}
# NEW STRUCTURE: Handle detectors at top level instead of under detector_params
if hasattr(self.config, "detectors") and self.config.detectors:
# Process the new structure with detectors at top level
detector_config: Dict[str, Any] = {}
for detector_id, det_config in self.config.detectors.items():
detector_config[detector_id] = det_config.get("detector_params", {})
payload["detectors"] = detector_config
# BACKWARD COMPATIBILITY: Handle legacy structures
elif (
hasattr(self.config, "detector_params")
and self.config.detector_params is not None
):
# Create detector configuration
detector_config = {}
# Extract parameters directly without wrapping them
detector_params = {}
# For chat detectors, extract model_params and metadata properly
if hasattr(self.config.detector_params, "model_params"):
detector_params.update(self.config.detector_params.model_params)
if hasattr(self.config.detector_params, "metadata"):
detector_params.update(self.config.detector_params.metadata)
# Include direct parameters
for k, v in vars(self.config.detector_params).items():
if v is not None and k not in [
"model_params",
"metadata",
"kwargs",
"params",
"detectors",
]:
if not (isinstance(v, (dict, list)) and len(v) == 0):
detector_params[k] = v
# Handle composite detectors
if (
hasattr(self.config.detector_params, "detectors")
and self.config.detector_params.detectors
):
payload["detectors"] = self.config.detector_params.detectors
else:
# Add detector configuration to payload
detector_config[self.config.detector_id] = detector_params
payload["detectors"] = detector_config
# Add content or messages based on mode
if self.config.is_chat:
payload["messages"] = [msg.dict() for msg in messages]
else:
payload["content"] = messages[0].content
logger.debug(f"Prepared orchestrator payload: {payload}")
return payload
else:
# DIRECT MODE: Respect API-specific formats
detector_params = self._extract_detector_params()
# Extract parameters from nested containers if present
flattened_params = {}
# Handle complex parameter structures by flattening them for direct mode
if isinstance(detector_params, dict):
# First level: check for container structure
for container_name in ["metadata", "model_params", "kwargs"]:
if container_name in detector_params:
# Extract and flatten parameters from containers
container = detector_params.get(container_name, {})
if isinstance(container, dict):
flattened_params.update(container)
# If no container structure was found, use params directly
if not flattened_params:
flattened_params = detector_params
else:
flattened_params = detector_params
# Merge with any passed parameters
if params:
flattened_params.update(params)
# Remove empty params dictionary if present
if "params" in flattened_params and (
flattened_params["params"] == {} or flattened_params["params"] is None
):
del flattened_params["params"]
if self.config.is_chat:
payload = {
"messages": [msg.dict() for msg in messages],
"detector_params": flattened_params if flattened_params else {},
}
else:
# For content APIs in direct mode, use plural form for compatibility
payload = {
"contents": [
messages[0].content
], # Send as array for all content APIs
"detector_params": flattened_params if flattened_params else {},
}
logger.debug(f"Direct mode payload: {payload}")
return payload
async def _make_request(
self,
request: RequestPayload,
headers: Optional[Headers] = None,
timeout: Optional[float] = None,
) -> DetectorResponse:
"""Make HTTP request with error handling and retries"""
if not self._http_client:
raise DetectorError("HTTP client not initialized")
url = self._construct_url()
default_headers = self._prepare_headers()
headers = {**default_headers, **(headers or {})}
for attempt in range(self.config.max_retries):
try:
response = await self._http_client.post(
url,
json=request,
headers=headers,
timeout=timeout or self.config.request_timeout,
)
# Handle different error codes specifically
if response.status_code == 429:
# Rate limit handling
retry_after = int(
response.headers.get(
"Retry-After", self.config.backoff_factor * 2
)
)
logger.warning(f"Rate limited, waiting {retry_after}s before retry")
await asyncio.sleep(retry_after)
continue
elif response.status_code == 401:
raise DetectorAuthError(f"Authentication failed: {response.text}")
elif response.status_code == 503:
# Service unavailable - return informative error if this is our last retry
if attempt == self.config.max_retries - 1:
error_details = {
"timestamp": datetime.datetime.now(
datetime.timezone.utc
).isoformat(),
"service": urlparse(url).netloc,
"detector_id": self.config.detector_id,
"retries_attempted": self.config.max_retries,
"status_code": 503,
}
logger.error(
f"Service unavailable after {self.config.max_retries} attempts: "
f"{error_details['service']} for detector {self.config.detector_id}"
)
raise DetectorNetworkError(
f"Safety service is currently unavailable. The system attempted {self.config.max_retries}"
f"retries but couldn't connect to {error_details['service']}. Please try again "
f"later or contact your administrator if the problem persists."
)
# Continue with backoff if we have more retries
logger.warning(
f"Service unavailable (attempt {attempt+1}/{self.config.max_retries}), retrying..."
)
else:
# SUCCESS PATH: Return immediately for successful responses
response.raise_for_status()
return cast(DetectorResponse, response.json())
except httpx.TimeoutException as e:
logger.error(
f"Request timed out (attempt {attempt + 1}/{self.config.max_retries})"
)
if attempt == self.config.max_retries - 1:
raise DetectorTimeoutError(
f"Request timed out after {self.config.max_retries} attempts"
) from e
except httpx.HTTPStatusError as e:
# More specific error handling based on status code
logger.error(
f"HTTP error {e.response.status_code} (attempt {attempt + 1}/{self.config.max_retries}): {e.response.text}"
)
if attempt == self.config.max_retries - 1:
raise DetectorRequestError(
f"API Error after {self.config.max_retries} attempts: {e.response.text}"
) from e
# Exponential backoff
jitter = random.uniform(0.8, 1.2)
await asyncio.sleep((self.config.backoff_factor**attempt) * jitter)
raise DetectorRequestError(
f"Request failed after {self.config.max_retries} attempts"
)
def _process_detection(
self, detection: Dict[str, Any]
) -> Tuple[Optional[DetectionResult], float]:
"""Process detection result and return both result and score"""
score = detection.get("score", 0.0)
if "score" not in detection:
logger.warning("Detection missing score field")
return None, 0.0
if score > self.score_threshold:
return (
DetectionResult(
detection="Yes",
detection_type=detection["detection_type"],
score=score,
detector_id=detection.get("detector_id", self.config.detector_id),
text=detection.get("text", ""),
start=detection.get("start", 0),
end=detection.get("end", 0),
metadata=detection.get("metadata"),
),
score,
)
return None, score
def create_violation_response(
self,
detection: DetectionResult,
detector_id: str,
level: ViolationLevel = ViolationLevel.ERROR,
) -> RunShieldResponse:
"""Create standardized violation response"""
return RunShieldResponse(
violation=SafetyViolation(
user_message=f"Content flagged by {detector_id} as {detection.detection_type} with confidence {detection.score:.2f}",
violation_level=level,
metadata=detection.to_dict(),
)
)
def _validate_shield(self, shield: Shield) -> None:
"""Validate shield configuration"""
if not shield:
raise DetectorValidationError("Shield not found")
if not shield.identifier:
raise DetectorValidationError("Shield missing identifier")
@abstractmethod
async def _run_shield_impl(
self,
shield_id: str,
messages: List[Message],
params: Optional[Dict[str, Any]] = None,
) -> RunShieldResponse:
"""Implementation specific shield running logic"""
pass
async def run_shield(
self,
shield_id: str,
messages: List[Message],
params: Optional[Dict[str, Any]] = None,
) -> RunShieldResponse:
"""Run safety checks using configured shield"""
try:
if not messages:
return RunShieldResponse(
violation=SafetyViolation(
violation_level=ViolationLevel.INFO,
user_message="No messages to process",
metadata={"status": "skipped", "shield_id": shield_id},
)
)
supported_messages = []
unsupported_types = set()
for msg in messages:
if self._should_process_message(msg):
supported_messages.append(msg)
else:
msg_type = msg.type if hasattr(msg, "type") else type(msg).__name__
unsupported_types.add(msg_type)
logger.warning(
f"Message type '{msg_type}' not supported by shield {shield_id}. "
f"Allowed types: {list(self.config.message_types)}"
)
if not supported_messages:
return RunShieldResponse(
violation=SafetyViolation(
violation_level=ViolationLevel.WARN,
user_message=(
f"No supported message types to process. Shield {shield_id} only handles: "
f"{list(self.config.message_types)}"
),
metadata={
"status": "skipped",
"error_type": "no_supported_messages",
"message_type": list(unsupported_types),
"supported_types": list(self.config.message_types),
"shield_id": shield_id,
},
)
)
# Step 4: Process supported messages
return await self._run_shield_impl(shield_id, supported_messages, params)
except Exception as e:
logger.error(f"Shield execution failed: {str(e)}", exc_info=True)
return RunShieldResponse(
violation=SafetyViolation(
violation_level=ViolationLevel.ERROR,
user_message=f"Shield execution error: {str(e)}",
metadata={
"status": "error",
"error_type": "execution_error",
"shield_id": shield_id,
"error": str(e),
},
)
)
class SimpleShieldStore(ShieldStore):
"""Simplified shield store with caching"""
def __init__(self):
self._shields: Dict[str, Shield] = {}
self._detector_configs = {}
self._pending_configs = {} # Add this to store configs before initialization
self._store_id = id(self)
self._initialized = False
self._lock = asyncio.Lock() # Add lock
logger.info(f"Created SimpleShieldStore: {self._store_id}")
async def register_detector_config(self, detector_id: str, config: Any) -> None:
"""Register detector configuration"""
async with self._lock:
if self._initialized:
self._detector_configs[detector_id] = config
else:
self._pending_configs[detector_id] = config
logger.info(
f"Shield store {self._store_id} registered config for: {detector_id}"
)
async def update_shield_params(
self, shield_id: str, params: Dict[str, Any]
) -> None:
"""Update shield parameters in the store"""
shield = self._shields.get(shield_id)
if shield:
shield.params = params
logger.debug(
f"Shield store {self._store_id} updated params for shield {shield_id}: {params}"
)
async def initialize(self) -> None:
"""Initialize store and process pending configurations"""
if self._initialized:
return
async with self._lock:
# Process any pending configurations
self._detector_configs.update(self._pending_configs)
self._pending_configs.clear()
self._initialized = True
logger.info(
f"Shield store {self._store_id} initialized with {len(self._detector_configs)} configs"
)
def _generate_params_for_shield(self, shield_id, config):
"""Helper method to generate shield parameters from config"""
params = {}
# For content detectors with multiple sub-detectors
if hasattr(config, "detectors") and config.detectors:
detectors_config = {}
for det_id, det_config in config.detectors.items():
det_params = {}
if "detector_params" in det_config:
det_params = det_config["detector_params"]
detectors_config[det_id] = det_params
params["detectors"] = detectors_config
# For chat detectors with model parameters
elif hasattr(config, "detector_params") and config.detector_params:
if (
hasattr(config.detector_params, "model_params")
and config.detector_params.model_params
):
params["model_params"] = dict(config.detector_params.model_params)
# Add metadata fields
if (
hasattr(config.detector_params, "metadata")
and config.detector_params.metadata
):
if "model_params" not in params:
params["model_params"] = {}
# Add all metadata fields
for key, value in config.detector_params.metadata.items():
params["model_params"][key] = value
# Add common shield information
params.update(
{
"display_name": f"{shield_id} Shield",
"display_description": f"Safety shield for {shield_id}",
"detector_type": "content" if not config.is_chat else "chat",
"message_types": list(config.message_types),
"confidence_threshold": config.confidence_threshold,
}
)
return params
async def get_shield(self, identifier: str) -> Shield:
"""Get or create shield by identifier"""
await self.initialize()
# Convert to string if needed
identifier = str(identifier)
if identifier in self._shields:
logger.debug(
f"Shield store {self._store_id} found existing shield: {identifier}"
)
return self._shields[identifier]
config = self._detector_configs.get(identifier)
if config:
logger.info(
f"Shield store {self._store_id} creating shield for {identifier} using config"
)
# Create shield params dictionary
params = {}
# For content detectors with multiple sub-detectors (email_hap)
if hasattr(config, "detectors") and config.detectors:
detectors_config = {}
for det_id, det_config in config.detectors.items():
det_params = {}
if "detector_params" in det_config:
# Include all parameters from detector_params
det_params = det_config["detector_params"]
detectors_config[det_id] = det_params
# Add detectors to params
params["detectors"] = detectors_config
# For chat detectors like granite with model parameters
elif hasattr(config, "detector_params") and config.detector_params:
if (
hasattr(config.detector_params, "model_params")
and config.detector_params.model_params
):
params["model_params"] = dict(config.detector_params.model_params)
# Add metadata fields as part of model_params for chat detectors
if (
hasattr(config.detector_params, "metadata")
and config.detector_params.metadata
):
if "model_params" not in params:
params["model_params"] = {}
# Add all metadata fields
for key, value in config.detector_params.metadata.items():
params["model_params"][key] = value
# Add common shield information
params.update(
{
"display_name": f"{identifier} Shield",
"display_description": f"Safety shield for {identifier}",
"detector_type": "content" if not config.is_chat else "chat",
"message_types": list(config.message_types),
"confidence_threshold": config.confidence_threshold,
}
)
# Create shield with proper params
shield = Shield(
identifier=identifier,
provider_id="trustyai_fms",
provider_resource_id=identifier,
type=ResourceType.shield.value,
params=params,
)
logger.info(
f"Shield store {self._store_id} created shield: {identifier} with params: {params}"
)
self._shields[identifier] = shield
return shield
else:
# Fail explicitly if no config found
logger.error(
f"Shield store {self._store_id} failed to create shield: no configuration found for {identifier}"
)
raise DetectorValidationError(
f"Cannot create shield '{identifier}': no detector configuration found. "
"Shields must have a valid detector configuration to ensure proper safety checks."
)
async def create_dynamic_shield(
self, shield_id: str, params: Dict[str, Any]
) -> None:
"""Create a dynamic shield configuration from API parameters"""
# Extract shield configuration from API params
shield_type = params.get("type", "content")
confidence_threshold = params.get("confidence_threshold", 0.5)
message_types = params.get("message_types", ["system"])
# Create detector params
detector_params = DetectorParams()
# Handle detectors configuration (like your email_hap example)
if "detectors" in params:
detector_params.detectors = params["detectors"]
# Set orchestrator URL from provider config if available
orchestrator_url = None
if hasattr(self, "_provider_config") and self._provider_config.orchestrator_url:
orchestrator_url = self._provider_config.orchestrator_url
# Create appropriate config based on type
if shield_type == "content":
config = ContentDetectorConfig(
detector_id=shield_id,
confidence_threshold=confidence_threshold,
message_types=set(message_types), # Convert to set as expected
detector_params=detector_params,
# Runtime parameters (all valid from BaseDetectorConfig)
request_timeout=30.0,
max_retries=3,
backoff_factor=1.5,
max_keepalive_connections=5,
max_connections=10,
max_concurrency=10,
# URL configuration
orchestrator_url=orchestrator_url,
detector_url=None, # Will be set if needed
auth_token=None,
verify_ssl=params.get("verify_ssl", True),
ssl_cert_path=params.get("ssl_cert_path"),
ssl_client_cert=params.get("ssl_client_cert"),
ssl_client_key=params.get("ssl_client_key"),
)
elif shield_type == "chat":
config = ChatDetectorConfig(
detector_id=shield_id,
confidence_threshold=confidence_threshold,
message_types=set(message_types), # Convert to set as expected
detector_params=detector_params,
# Runtime parameters (all valid from BaseDetectorConfig)
request_timeout=30.0,
max_retries=3,
backoff_factor=1.5,
max_keepalive_connections=5,
max_connections=10,
max_concurrency=10,
# URL configuration
orchestrator_url=orchestrator_url,
detector_url=None,
auth_token=None,
verify_ssl=params.get("verify_ssl", True),
ssl_cert_path=params.get("ssl_cert_path"),
ssl_client_cert=params.get("ssl_client_cert"),
ssl_client_key=params.get("ssl_client_key"),
)
else:
raise DetectorValidationError(f"Unknown shield type: {shield_type}")
# Register the configuration
await self.register_detector_config(shield_id, config)
logger.info(
f"Successfully created dynamic configuration for shield: {shield_id}"
)
async def list_shields(self) -> ListShieldsResponse:
"""List all registered shields with their parameters"""
if not self._initialized:
# Ensure provider is initialized, which populates self._shields
# with Shield instances that include their parameters.
logger.info( # Changed to INFO
f"Provider {self._provider_id} - list_shields: Not initialized, calling initialize()."
)
await self.initialize()
else:
logger.info(
f"Provider {self._provider_id} - list_shields: Already initialized."
)
# Get all shield instances directly from the _shields dictionary values.
shields_to_return = list(self._shields.values())
logger.info(
f"Provider {self._provider_id} - list_shields: Retrieved {len(shields_to_return)} shields from self._shields.values()."
)
# Log what we're returning for debugging purposes
shield_ids = [s.identifier for s in shields_to_return]
logger.info(
f"Provider {self._provider_id} listing {len(shields_to_return)} shields: {shield_ids}"
)
# Detailed debug log for each shield being returned, specifically checking params
if not shields_to_return:
logger.info(
f"Provider {self._provider_id} - list_shields: No shields to return."
)
# Detailed debug log for each shield being returned, specifically checking params
if not shields_to_return:
logger.info(
f"Provider {self._provider_id} - list_shields: No shields to return."
)
else: # Added else to ensure the detailed check log title always appears if there are shields
logger.info(
f"Provider {self._provider_id} - list_shields - DETAILED PARAM CHECK BEFORE RESPONSE:"
)
for shield_debug_loop in shields_to_return:
logger.info(
f"Provider {self._provider_id} - Shield ID='{shield_debug_loop.identifier}', Params='{shield_debug_loop.params}', Object ID='{id(shield_debug_loop)}'"
)
return ListShieldsResponse(data=shields_to_return)
class DetectorProvider(Safety, Shields):
"""Provider for managing safety detectors and shields"""
def __init__(
self, detectors: Dict[str, BaseDetector], config: Optional[Any] = None
) -> None:
self.detectors = detectors
self._shield_store: ShieldStore = SimpleShieldStore()
if config:
self._shield_store._provider_config = config
self._shields: Dict[str, Shield] = {}
self._initialized = False
self._provider_id = id(self)
self._detector_key_to_id = {} # Add mapping dict
self._pending_configs = [] # Store configurations for later registration