Elffuss BraidHub

kikocis/llama-stack public

Another attempt at a proper bugfix for safety violations
Changeset9fefaaef1108e26035a7aa734305a164d981aae552ddbcdb13a01341decc881d
AuthorAshwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-23 19:06 -07:00
CommitterAshwin Bharambe <ashwin.bharambe@gmail.com> · 2024-09-23 19:06 -07:00
Parentsa2f7f2d716e2

Browse the files at this changeset

2 files changed

modified llama_stack/providers/impls/meta_reference/agents/safety.py +15 −3
@@ -32,14 +32,26 @@
3232 self.output_shields = output_shields
3333
3434 async def run_multiple_shields(
35- self, messages: List[Message], shields: List[str]
35+ self, messages: List[Message], shield_types: List[str]
3636 ) -> None:
37- await asyncio.gather(
37+ responses = await asyncio.gather(
3838 *[
3939 self.safety_api.run_shield(
4040 shield_type=shield_type,
4141 messages=messages,
4242 )
43- for shield_type in shields
43+ for shield_type in shield_types
4444 ]
4545 )
46+ for shield_type, response in zip(shields, responses):
47+ if not response.violation:
48+ continue
49+
50+ violation = response.violation
51+ if violation.violation_level == ViolationLevel.ERROR:
52+ raise SafetyException(violation)
53+ elif violation.violation_level == ViolationLevel.WARN:
54+ cprint(
55+ f"[Warn]{shield_type} raised a warning",
56+ color="red",
57+ )
modified llama_stack/providers/impls/meta_reference/safety/safety.py +6 −11
@@ -10,7 +10,6 @@
1010 from llama_stack.apis.safety import * # noqa: F403
1111 from llama_models.llama3.api.datatypes import * # noqa: F403
1212
13-from llama_stack.providers.impls.meta_reference.agents.safety import SafetyException
1413 from llama_stack.providers.impls.meta_reference.safety.shields.base import (
1514 OnViolationAction,
1615 )
@@ -74,23 +73,19 @@
7473 # TODO: we can refactor ShieldBase, etc. to be inline with the API types
7574 res = await shield.run(messages)
7675 violation = None
77- if res.is_violation:
76+ if res.is_violation and shield.on_violation_action != OnViolationAction.IGNORE:
7877 violation = SafetyViolation(
79- violation_level=ViolationLevel.ERROR,
78+ violation_level=(
79+ ViolationLevel.ERROR
80+ if shield.on_violation_action == OnViolationAction.RAISE
81+ else ViolationLevel.WARN
82+ ),
8083 user_message=res.violation_return_message,
8184 metadata={
8285 "violation_type": res.violation_type,
8386 },
8487 )
8588
86- if shield.on_violation_action == OnViolationAction.RAISE:
87- raise SafetyException(violation)
88- elif shield.on_violation_action == OnViolationAction.WARN:
89- cprint(
90- f"[Warn]{shield.__class__.__name__} raised a warning",
91- color="red",
92- )
93-
9489 return RunShieldResponse(violation=violation)
9590
9691 def get_shield_impl(self, typ: MetaReferenceShieldType) -> ShieldBase: