Skip to content

Commit 4b8f40e

Browse files
authored
fix: fallback to function name for unnamed output_guardrail decorators (#1133)
**Overview:** This PR improves the output_guardrail behavior by ensuring a valid name is always assigned to the guardrail, even when the decorator is used without parentheses or without explicitly providing a name. **Problem:** Previously, when the decorator @output_guardrail was used without a name (and without parentheses), the name attribute of the guardrail remained None. This resulted in issues during runtime — specifically, the guardrail name did not appear in result.input_guardrail_results, making it harder to trace or debug guardrail outputs. While the OutputGuardrail.get_name() method correctly defaults to the function name when name is None, this method is not used inside the decorator. Hence, unless a name is provided explicitly, the OutputGuardrail instance holds None for its name internally. **Solution:** This PR updates the decorator logic to: Automatically fallback to the function name if the name parameter is not provided. Ensure that the guardrail always has a meaningful identifier, which improves downstream behavior such as logging, debugging, and result tracing. **Example Behavior Before:** @output_guardrail def validate_output(...): Name remains None **Example Behavior After:** @output_guardrail def validate_output(...): Name becomes "validate_output" automatically **Why it matters:** This small change avoids hidden bugs or inconsistencies in downstream systems (like guardrail_results) that rely on guardrail names being defined. It also brings consistent behavior whether or not parentheses are used in the decorator.
1 parent 9046577 commit 4b8f40e

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

src/agents/guardrail.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,11 @@ async def my_async_guardrail(...): ...
314314
def decorator(
315315
f: _OutputGuardrailFuncSync[TContext_co] | _OutputGuardrailFuncAsync[TContext_co],
316316
) -> OutputGuardrail[TContext_co]:
317-
return OutputGuardrail(guardrail_function=f, name=name)
317+
return OutputGuardrail(
318+
guardrail_function=f,
319+
# Guardrail name defaults to function name when not specified (None).
320+
name=name if name else f.__name__,
321+
)
318322

319323
if func is not None:
320324
# Decorator was used without parentheses

0 commit comments

Comments
 (0)