docs: fix guardrail documentation usage

This commit is contained in:
Lucas Gomide
2025-04-17 11:04:19 -03:00
parent a2f3566cd9
commit 1202df822d

View File

@@ -288,26 +288,20 @@ To add a guardrail to a task, provide a validation function through the `guardra
```python Code ```python Code
from typing import Tuple, Union, Dict, Any from typing import Tuple, Union, Dict, Any
from crewai import TaskOutput
def validate_blog_content(result: str) -> Tuple[bool, Union[Dict[str, Any], str]]: def validate_blog_content(result: TaskOutput) -> Tuple[bool, Any]:
"""Validate blog content meets requirements.""" """Validate blog content meets requirements."""
try: try:
# Check word count # Check word count
word_count = len(result.split()) word_count = len(result.split())
if word_count > 200: if word_count > 200:
return (False, { return (False, "Blog content exceeds 200 words")
"error": "Blog content exceeds 200 words",
"code": "WORD_COUNT_ERROR",
"context": {"word_count": word_count}
})
# Additional validation logic here # Additional validation logic here
return (True, result.strip()) return (True, result.strip())
except Exception as e: except Exception as e:
return (False, { return (False, "Unexpected error during validation")
"error": "Unexpected error during validation",
"code": "SYSTEM_ERROR"
})
blog_task = Task( blog_task = Task(
description="Write a blog post about AI", description="Write a blog post about AI",
@@ -325,29 +319,24 @@ blog_task = Task(
- Type hints are recommended but optional - Type hints are recommended but optional
2. **Return Values**: 2. **Return Values**:
- Success: Return `(True, validated_result)` - On success: it returns a tuple of `(bool, Any)`. For example: `(True, validated_result)`
- Failure: Return `(False, error_details)` - On Failure: it returns a tuple of `(bool, str)`. For example: `(False, "Error message explain the failure")`
### Error Handling Best Practices ### Error Handling Best Practices
1. **Structured Error Responses**: 1. **Structured Error Responses**:
```python Code ```python Code
def validate_with_context(result: str) -> Tuple[bool, Union[Dict[str, Any], str]]: from crewai import TaskOutput
def validate_with_context(result: TaskOutput) -> Tuple[bool, Any]:
try: try:
# Main validation logic # Main validation logic
validated_data = perform_validation(result) validated_data = perform_validation(result)
return (True, validated_data) return (True, validated_data)
except ValidationError as e: except ValidationError as e:
return (False, { return (False, f"VALIDATION_ERROR: {str(e)}")
"error": str(e),
"code": "VALIDATION_ERROR",
"context": {"input": result}
})
except Exception as e: except Exception as e:
return (False, { return (False, str(e))
"error": "Unexpected error",
"code": "SYSTEM_ERROR"
})
``` ```
2. **Error Categories**: 2. **Error Categories**:
@@ -358,28 +347,25 @@ def validate_with_context(result: str) -> Tuple[bool, Union[Dict[str, Any], str]
3. **Validation Chain**: 3. **Validation Chain**:
```python Code ```python Code
from typing import Any, Dict, List, Tuple, Union from typing import Any, Dict, List, Tuple, Union
from crewai import TaskOutput
def complex_validation(result: str) -> Tuple[bool, Union[str, Dict[str, Any]]]: def complex_validation(result: TaskOutput) -> Tuple[bool, Any]:
"""Chain multiple validation steps.""" """Chain multiple validation steps."""
# Step 1: Basic validation # Step 1: Basic validation
if not result: if not result:
return (False, {"error": "Empty result", "code": "EMPTY_INPUT"}) return (False, "Empty result")
# Step 2: Content validation # Step 2: Content validation
try: try:
validated = validate_content(result) validated = validate_content(result)
if not validated: if not validated:
return (False, {"error": "Invalid content", "code": "CONTENT_ERROR"}) return (False, "Invalid content")
# Step 3: Format validation # Step 3: Format validation
formatted = format_output(validated) formatted = format_output(validated)
return (True, formatted) return (True, formatted)
except Exception as e: except Exception as e:
return (False, { return (False, str(e))
"error": str(e),
"code": "VALIDATION_ERROR",
"context": {"step": "content_validation"}
})
``` ```
### Handling Guardrail Results ### Handling Guardrail Results
@@ -394,19 +380,16 @@ When a guardrail returns `(False, error)`:
Example with retry handling: Example with retry handling:
```python Code ```python Code
from typing import Optional, Tuple, Union from typing import Optional, Tuple, Union
from crewai import TaskOutput, Task
def validate_json_output(result: str) -> Tuple[bool, Union[Dict[str, Any], str]]: def validate_json_output(result: TaskOutput) -> Tuple[bool, Any]:
"""Validate and parse JSON output.""" """Validate and parse JSON output."""
try: try:
# Try to parse as JSON # Try to parse as JSON
data = json.loads(result) data = json.loads(result)
return (True, data) return (True, data)
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
return (False, { return (False, "Invalid JSON format")
"error": "Invalid JSON format",
"code": "JSON_ERROR",
"context": {"line": e.lineno, "column": e.colno}
})
task = Task( task = Task(
description="Generate a JSON report", description="Generate a JSON report",