Skip to main content
Guardrails enforce safety, compliance, and quality rules on agent outputs. They run after the LLM generates a response but before tool execution, allowing you to validate or modify content before it’s acted upon.

What are guardrails?

Guardrails intercept agent responses and can:
  • Stop execution - Reject responses that violate rules
  • Modify content - Filter, redact, or transform responses before they continue
Guardrails run synchronously after each LLM call, giving you fine-grained control over agent behavior.

String guardrails

The simplest guardrails are natural language rules. Polos uses an LLM (the same model used by the agent) to evaluate these rules and returns pass/fail:
How it works:
  1. LLM generates a response
  2. Guardrail LLM evaluates the response against each rule
  3. If any rule fails, Polos feeds the error to the LLM to attempt correction (up to guardrail_max_retries times, default: 2)
  4. If all rules pass, the response continues to tool execution or final output
String guardrails return:

Function guardrails

For complex logic or content modification, use function guardrails:

Guardrail results

Function guardrails return GuardrailResult with three options:

1. Continue without changes

2. Continue with modifications

3. Fail and stop execution

Guardrail context

Guardrails receive a GuardrailContext with the current agent state:

Guardrail retries

Configure guardrail retry behavior on the agent:
When a guardrail fails:
  • Polos feeds the guardrail error message to the LLM
  • The LLM attempts to correct the response based on the error
  • This process repeats up to guardrail_max_retries times
  • If all retries fail, execution stops with the guardrail error

Modifying tool calls

Guardrails can also filter or modify tool calls:

Multiple guardrails

Guardrails execute in order. If any guardrail fails, execution stops:
Execution order:
  1. content_length_limit - Truncates if needed
  2. no_external_links - Checks for URLs (fails if found)
  3. redact_sensitive_data - Redacts PII
If no_external_links fails, redact_sensitive_data never runs.

Mixing string and function guardrails

You can combine both types:

Use cases

Content safety

Data privacy

Quality assurance

Key takeaways

  • Guardrails run after LLM responses but before tool execution
  • String guardrails use LLM evaluation for pass/fail checks
  • Function guardrails provide custom logic and content modification
  • GuardrailResult.continue_with() - Pass (optionally with modifications)
  • GuardrailResult.fail() - Stop execution with error
  • When guardrails fail, Polos retries by feeding the error to the LLM (up to guardrail_max_retries times, default: 2)
  • Multiple guardrails run in sequence; first failure stops execution
  • Modify content or tool calls before they’re acted upon