-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Lorenze/adding guardrails #3711
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
+525
−78
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c0e49e8
Enhance Task Class with Guardrail Support
lorenzejay 636584a
Refactor Task Class Guardrail Type Annotation
lorenzejay 884236f
properly set this for async
lorenzejay d40846e
fix test
lorenzejay 594c21a
Enhance Task Class Guardrail Validation Logic
lorenzejay File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,7 +5,7 @@ | |
import threading | ||
import uuid | ||
import warnings | ||
from collections.abc import Callable | ||
from collections.abc import Callable, Sequence | ||
from concurrent.futures import Future | ||
from copy import copy as shallow_copy | ||
from hashlib import md5 | ||
|
@@ -152,6 +152,15 @@ class Task(BaseModel): | |
default=None, | ||
description="Function or string description of a guardrail to validate task output before proceeding to next task", | ||
) | ||
guardrails: ( | ||
Sequence[Callable[[TaskOutput], tuple[bool, Any]] | str] | ||
| Callable[[TaskOutput], tuple[bool, Any]] | ||
| str | ||
| None | ||
) = Field( | ||
default=None, | ||
description="List of guardrails to validate task output before proceeding to next task. Also supports a single guardrail function or string description of a guardrail to validate task output before proceeding to next task", | ||
) | ||
max_retries: int | None = Field( | ||
default=None, | ||
description="[DEPRECATED] Maximum number of retries when guardrail fails. Use guardrail_max_retries instead. Will be removed in v1.0.0", | ||
|
@@ -268,6 +277,44 @@ def ensure_guardrail_is_callable(self) -> "Task": | |
|
||
return self | ||
|
||
@model_validator(mode="after") | ||
def ensure_guardrails_is_list_of_callables(self) -> "Task": | ||
guardrails = [] | ||
if self.guardrails is not None and ( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. did you want to check for empty lists here? |
||
not isinstance(self.guardrails, (list, tuple)) or len(self.guardrails) > 0 | ||
): | ||
if self.agent is None: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think the agent check is too early maybe, only string-based guardrails need an agent, right? |
||
raise ValueError("Agent is required to use guardrails") | ||
|
||
if callable(self.guardrails): | ||
guardrails.append(self.guardrails) | ||
elif isinstance(self.guardrails, str): | ||
from crewai.tasks.llm_guardrail import LLMGuardrail | ||
|
||
guardrails.append( | ||
LLMGuardrail(description=self.guardrails, llm=self.agent.llm) | ||
) | ||
|
||
if isinstance(self.guardrails, list): | ||
for guardrail in self.guardrails: | ||
if callable(guardrail): | ||
guardrails.append(guardrail) | ||
elif isinstance(guardrail, str): | ||
from crewai.tasks.llm_guardrail import LLMGuardrail | ||
|
||
guardrails.append( | ||
LLMGuardrail(description=guardrail, llm=self.agent.llm) | ||
) | ||
else: | ||
raise ValueError("Guardrail must be a callable or a string") | ||
|
||
self._guardrails = guardrails | ||
if self._guardrails: | ||
self.guardrail = None | ||
self._guardrail = None | ||
|
||
return self | ||
|
||
@field_validator("id", mode="before") | ||
@classmethod | ||
def _deny_user_set_id(cls, v: UUID4 | None) -> None: | ||
|
@@ -456,48 +503,23 @@ def _execute_core( | |
output_format=self._get_output_format(), | ||
) | ||
|
||
if self._guardrails: | ||
for guardrail in self._guardrails: | ||
task_output = self._invoke_guardrail_function( | ||
task_output=task_output, | ||
agent=agent, | ||
tools=tools, | ||
guardrail=guardrail, | ||
) | ||
|
||
# backwards support | ||
if self._guardrail: | ||
guardrail_result = process_guardrail( | ||
output=task_output, | ||
task_output = self._invoke_guardrail_function( | ||
task_output=task_output, | ||
agent=agent, | ||
tools=tools, | ||
guardrail=self._guardrail, | ||
retry_count=self.retry_count, | ||
event_source=self, | ||
from_task=self, | ||
from_agent=agent, | ||
) | ||
if not guardrail_result.success: | ||
if self.retry_count >= self.guardrail_max_retries: | ||
raise Exception( | ||
f"Task failed guardrail validation after {self.guardrail_max_retries} retries. " | ||
f"Last error: {guardrail_result.error}" | ||
) | ||
|
||
self.retry_count += 1 | ||
context = self.i18n.errors("validation_error").format( | ||
guardrail_result_error=guardrail_result.error, | ||
task_output=task_output.raw, | ||
) | ||
printer = Printer() | ||
printer.print( | ||
content=f"Guardrail blocked, retrying, due to: {guardrail_result.error}\n", | ||
color="yellow", | ||
) | ||
return self._execute_core(agent, context, tools) | ||
|
||
if guardrail_result.result is None: | ||
raise Exception( | ||
"Task guardrail returned None as result. This is not allowed." | ||
) | ||
|
||
if isinstance(guardrail_result.result, str): | ||
task_output.raw = guardrail_result.result | ||
pydantic_output, json_output = self._export_output( | ||
guardrail_result.result | ||
) | ||
task_output.pydantic = pydantic_output | ||
task_output.json_dict = json_output | ||
elif isinstance(guardrail_result.result, TaskOutput): | ||
task_output = guardrail_result.result | ||
|
||
self.output = task_output | ||
self.end_time = datetime.datetime.now() | ||
|
@@ -789,3 +811,55 @@ def fingerprint(self) -> Fingerprint: | |
Fingerprint: The fingerprint of the task | ||
""" | ||
return self.security_config.fingerprint | ||
|
||
def _invoke_guardrail_function( | ||
self, | ||
task_output: TaskOutput, | ||
agent: BaseAgent, | ||
tools: list[BaseTool], | ||
guardrail: Callable | None, | ||
) -> TaskOutput: | ||
if guardrail: | ||
guardrail_result = process_guardrail( | ||
output=task_output, | ||
guardrail=guardrail, | ||
retry_count=self.retry_count, | ||
event_source=self, | ||
from_task=self, | ||
from_agent=agent, | ||
) | ||
if not guardrail_result.success: | ||
if self.retry_count >= self.guardrail_max_retries: | ||
raise Exception( | ||
f"Task failed guardrail validation after {self.guardrail_max_retries} retries. " | ||
f"Last error: {guardrail_result.error}" | ||
) | ||
|
||
self.retry_count += 1 | ||
context = self.i18n.errors("validation_error").format( | ||
guardrail_result_error=guardrail_result.error, | ||
task_output=task_output.raw, | ||
) | ||
printer = Printer() | ||
printer.print( | ||
content=f"Guardrail blocked, retrying, due to: {guardrail_result.error}\n", | ||
color="yellow", | ||
) | ||
return self._execute_core(agent, context, tools) | ||
|
||
if guardrail_result.result is None: | ||
raise Exception( | ||
"Task guardrail returned None as result. This is not allowed." | ||
) | ||
|
||
if isinstance(guardrail_result.result, str): | ||
task_output.raw = guardrail_result.result | ||
pydantic_output, json_output = self._export_output( | ||
guardrail_result.result | ||
) | ||
task_output.pydantic = pydantic_output | ||
task_output.json_dict = json_output | ||
elif isinstance(guardrail_result.result, TaskOutput): | ||
task_output = guardrail_result.result | ||
|
||
return task_output |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.