Skip to content

[Bug] custom_patterns in PIIDetectionGuardrail does not accept raw regex strings #7770

@Soulaimene

Description

@Soulaimene

Description

When defining custom_patternsin PIIDetectionGuardrail, passing a raw regex string does not work as expected. The guardrail appears to require compiled regex patterns (re.compile(...)), but this is not documented and leads to silent failure or incorrect behavior.

Steps to Reproduce

guardrail = PIIDetectionGuardrail(
    custom_patterns={
        "bank_account_number": r"\b\d{10}\b",
    }
)

The pattern above should detect 10-digit bank account numbers, but it does not work unless explicitly compiled.

Agent Configuration (if applicable)

No response

Expected Behavior

The guardrail should accept raw regex strings and internally compile them, or clearly document that compiled patterns are required.

Actual Behavior

Raw regex strings are ignored or fail to match unless wrapped with re.compile

agno\guardrails\pii.py", line 53, in check                                                                          
             if pattern.search(content):                                                                                                                                                     
                ^^^^^^^^^^^^^^                                                                                                                                                               
         AttributeError: 'str' object has no attribute 'search'      

Screenshots or Logs (if applicable)

No response

Environment

- agno version : 2.5.16
- os: Windows 11
- python 3.12.12

Possible Solutions (optional)

  • Automatically compile string patterns internally:
    compiled_patterns = {
        name: re.compile(pattern) if isinstance(pattern, str) else pattern
        for name, pattern in custom_patterns.items()
    }
  • Optionally, validate inputs to prevent unexpected types:
    compiled_patterns = {}
    for name, pattern in custom_patterns.items():
        if isinstance(pattern, str):
            compiled_patterns[name] = re.compile(pattern)
        elif isinstance(pattern, re.Pattern):
            compiled_patterns[name] = pattern
        else:
            raise TypeError("Pattern must be a string or compiled regex")
  • Or explicitly enforce and document that only compiled regex patterns are supported.

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions