Implementing validators for agents and tools.
field_validator
: Validate individual fields independently.model_validator
: Perform complex checks involving multiple fields.response_validator
: Validate the response before sending it to the user or other agents.llm_validator
: Validate outputs against specified natural language rules.response_validator
method inside your Agent class to validate responses before sending them to the user or other agents. This method should raise an error if the response is invalid, allowing the agent to handle the error and generate a corrected response.
Example:
CustomerSupportAgent
checks the response for the presence of “bad word” and raises a ValueError
if it is found. The error is passed to the Agent to generate a corrected response.
validation_attempts
parameter controls how many times an agent can retry when validation fails. Default is 1 (one retry). Set validation_attempts=0
for immediate fail-fast behavior.
validation_attempts
:
validation_attempts=2-3
validation_attempts=2
validation_attempts=0
to disable retriesType | Purpose | Usage |
---|---|---|
Field Validators | Validate individual fields independently. | Use the @field_validator decorator on methods, specifying the field(s) to validate. |
Model Validators | Validate the entire model, allowing checks involving multiple fields. | Use the @model_validator decorator on methods. |
username
field does not contain spaces using a field validator:llm_validator
is a powerful way to validate outputs against specified natural language rules.
Example:
llm_validator
will throw an error if the message is not related to customer support. The caller agent will then have to fix the recipient or the message and send it again.
llm_validator
uses LLMs for validation, it may incur additional costs and latency due to extra API calls. Use it for fields that require complex validation beyond simple checks.