콘텐츠로 이동

Decorators

Public decorators for defining Agents SDK components.

tool is an alias for function_tool.

input_guardrail

input_guardrail(
    func: _InputGuardrailFuncSync[TContext_co],
) -> InputGuardrail[TContext_co]
input_guardrail(
    func: _InputGuardrailFuncAsync[TContext_co],
) -> InputGuardrail[TContext_co]
input_guardrail(
    *, name: str | None = None, run_in_parallel: bool = True
) -> Callable[
    [
        _InputGuardrailFuncSync[TContext_co]
        | _InputGuardrailFuncAsync[TContext_co]
    ],
    InputGuardrail[TContext_co],
]
input_guardrail(
    func: _InputGuardrailFuncSync[TContext_co]
    | _InputGuardrailFuncAsync[TContext_co]
    | None = None,
    *,
    name: str | None = None,
    run_in_parallel: bool = True,
) -> (
    InputGuardrail[TContext_co]
    | Callable[
        [
            _InputGuardrailFuncSync[TContext_co]
            | _InputGuardrailFuncAsync[TContext_co]
        ],
        InputGuardrail[TContext_co],
    ]
)

Decorator that transforms a sync or async function into an InputGuardrail. It can be used directly (no parentheses) or with keyword args, e.g.:

@input_guardrail
def my_sync_guardrail(...): ...

@input_guardrail(name="guardrail_name", run_in_parallel=False)
async def my_async_guardrail(...): ...

引数:

名前 タイプ デスクリプション デフォルト
func _InputGuardrailFuncSync[TContext_co] | _InputGuardrailFuncAsync[TContext_co] | None

The guardrail function to wrap.

None
name str | None

Optional name for the guardrail. If not provided, uses the function's name.

None
run_in_parallel bool

Whether to run the guardrail concurrently with the agent (True, default) or before the agent starts (False).

True
ソースコード位置: src/agents/guardrail.py
def input_guardrail(
    func: _InputGuardrailFuncSync[TContext_co]
    | _InputGuardrailFuncAsync[TContext_co]
    | None = None,
    *,
    name: str | None = None,
    run_in_parallel: bool = True,
) -> (
    InputGuardrail[TContext_co]
    | Callable[
        [_InputGuardrailFuncSync[TContext_co] | _InputGuardrailFuncAsync[TContext_co]],
        InputGuardrail[TContext_co],
    ]
):
    """
    Decorator that transforms a sync or async function into an `InputGuardrail`.
    It can be used directly (no parentheses) or with keyword args, e.g.:

        @input_guardrail
        def my_sync_guardrail(...): ...

        @input_guardrail(name="guardrail_name", run_in_parallel=False)
        async def my_async_guardrail(...): ...

    Args:
        func: The guardrail function to wrap.
        name: Optional name for the guardrail. If not provided, uses the function's name.
        run_in_parallel: Whether to run the guardrail concurrently with the agent (True, default)
            or before the agent starts (False).
    """

    def decorator(
        f: _InputGuardrailFuncSync[TContext_co] | _InputGuardrailFuncAsync[TContext_co],
    ) -> InputGuardrail[TContext_co]:
        return InputGuardrail(
            guardrail_function=f,
            # If not set, guardrail name uses the function’s name by default.
            name=name if name else f.__name__,
            run_in_parallel=run_in_parallel,
        )

    if func is not None:
        # Decorator was used without parentheses
        return decorator(func)

    # Decorator used with keyword arguments
    return decorator

output_guardrail

output_guardrail(
    func: _OutputGuardrailFuncSync[TContext_co],
) -> OutputGuardrail[TContext_co]
output_guardrail(
    func: _OutputGuardrailFuncAsync[TContext_co],
) -> OutputGuardrail[TContext_co]
output_guardrail(
    *, name: str | None = None
) -> Callable[
    [
        _OutputGuardrailFuncSync[TContext_co]
        | _OutputGuardrailFuncAsync[TContext_co]
    ],
    OutputGuardrail[TContext_co],
]
output_guardrail(
    func: _OutputGuardrailFuncSync[TContext_co]
    | _OutputGuardrailFuncAsync[TContext_co]
    | None = None,
    *,
    name: str | None = None,
) -> (
    OutputGuardrail[TContext_co]
    | Callable[
        [
            _OutputGuardrailFuncSync[TContext_co]
            | _OutputGuardrailFuncAsync[TContext_co]
        ],
        OutputGuardrail[TContext_co],
    ]
)

Decorator that transforms a sync or async function into an OutputGuardrail. It can be used directly (no parentheses) or with keyword args, e.g.:

@output_guardrail
def my_sync_guardrail(...): ...

@output_guardrail(name="guardrail_name")
async def my_async_guardrail(...): ...
ソースコード位置: src/agents/guardrail.py
def output_guardrail(
    func: _OutputGuardrailFuncSync[TContext_co]
    | _OutputGuardrailFuncAsync[TContext_co]
    | None = None,
    *,
    name: str | None = None,
) -> (
    OutputGuardrail[TContext_co]
    | Callable[
        [_OutputGuardrailFuncSync[TContext_co] | _OutputGuardrailFuncAsync[TContext_co]],
        OutputGuardrail[TContext_co],
    ]
):
    """
    Decorator that transforms a sync or async function into an `OutputGuardrail`.
    It can be used directly (no parentheses) or with keyword args, e.g.:

        @output_guardrail
        def my_sync_guardrail(...): ...

        @output_guardrail(name="guardrail_name")
        async def my_async_guardrail(...): ...
    """

    def decorator(
        f: _OutputGuardrailFuncSync[TContext_co] | _OutputGuardrailFuncAsync[TContext_co],
    ) -> OutputGuardrail[TContext_co]:
        return OutputGuardrail(
            guardrail_function=f,
            # Guardrail name defaults to function's name when not specified (None).
            name=name if name else f.__name__,
        )

    if func is not None:
        # Decorator was used without parentheses
        return decorator(func)

    # Decorator used with keyword arguments
    return decorator

function_tool

function_tool(
    func: ToolFunction[...],
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    docstring_style: DocstringStyle | None = None,
    use_docstring_info: bool = True,
    failure_error_function: ToolErrorFunction | None = None,
    strict_mode: bool = True,
    is_enabled: bool
    | Callable[
        [RunContextWrapper[Any], AgentBase],
        MaybeAwaitable[bool],
    ] = True,
    needs_approval: bool
    | Callable[
        [RunContextWrapper[Any], dict[str, Any], str],
        Awaitable[bool],
    ] = False,
    tool_input_guardrails: list[ToolInputGuardrail[Any]]
    | None = None,
    tool_output_guardrails: list[ToolOutputGuardrail[Any]]
    | None = None,
    timeout: float | None = None,
    timeout_behavior: ToolTimeoutBehavior = "error_as_result",
    timeout_error_function: ToolErrorFunction | None = None,
    defer_loading: bool = False,
    custom_data_extractor: FunctionToolCustomDataExtractor
    | None = None,
    allowed_callers: list[ToolCaller] | None = None,
    output_type: Any | None = None,
    output_json_schema: dict[str, Any] | None = None,
) -> FunctionTool
function_tool(
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    docstring_style: DocstringStyle | None = None,
    use_docstring_info: bool = True,
    failure_error_function: ToolErrorFunction | None = None,
    strict_mode: bool = True,
    is_enabled: bool
    | Callable[
        [RunContextWrapper[Any], AgentBase],
        MaybeAwaitable[bool],
    ] = True,
    needs_approval: bool
    | Callable[
        [RunContextWrapper[Any], dict[str, Any], str],
        Awaitable[bool],
    ] = False,
    tool_input_guardrails: list[ToolInputGuardrail[Any]]
    | None = None,
    tool_output_guardrails: list[ToolOutputGuardrail[Any]]
    | None = None,
    timeout: float | None = None,
    timeout_behavior: ToolTimeoutBehavior = "error_as_result",
    timeout_error_function: ToolErrorFunction | None = None,
    defer_loading: bool = False,
    custom_data_extractor: FunctionToolCustomDataExtractor
    | None = None,
    allowed_callers: list[ToolCaller] | None = None,
    output_type: Any | None = None,
    output_json_schema: dict[str, Any] | None = None,
) -> Callable[[ToolFunction[...]], FunctionTool]
function_tool(
    func: ToolFunction[...] | None = None,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    docstring_style: DocstringStyle | None = None,
    use_docstring_info: bool = True,
    failure_error_function: ToolErrorFunction
    | None
    | object = _UNSET_FAILURE_ERROR_FUNCTION,
    strict_mode: bool = True,
    is_enabled: bool
    | Callable[
        [RunContextWrapper[Any], AgentBase],
        MaybeAwaitable[bool],
    ] = True,
    needs_approval: bool
    | Callable[
        [RunContextWrapper[Any], dict[str, Any], str],
        Awaitable[bool],
    ] = False,
    tool_input_guardrails: list[ToolInputGuardrail[Any]]
    | None = None,
    tool_output_guardrails: list[ToolOutputGuardrail[Any]]
    | None = None,
    timeout: float | None = None,
    timeout_behavior: ToolTimeoutBehavior = "error_as_result",
    timeout_error_function: ToolErrorFunction | None = None,
    defer_loading: bool = False,
    custom_data_extractor: FunctionToolCustomDataExtractor
    | None = None,
    allowed_callers: list[ToolCaller] | None = None,
    output_type: Any | None = None,
    output_json_schema: dict[str, Any] | None = None,
) -> (
    FunctionTool
    | Callable[[ToolFunction[...]], FunctionTool]
)

Decorator to create a FunctionTool from a function. By default, we will: 1. Parse the function signature to create a JSON schema for the tool's parameters. 2. Use the function's docstring to populate the tool's description. 3. Use the function's docstring to populate argument descriptions. The docstring style is detected automatically, but you can override it.

If the function takes a RunContextWrapper as the first argument, it must match the context type of the agent that uses the tool.

引数:

名前 タイプ デスクリプション デフォルト
func ToolFunction[...] | None

The function to wrap.

None
name_override str | None

If provided, use this name for the tool instead of the function's name.

None
description_override str | None

If provided, use this description for the tool instead of the function's docstring.

None
docstring_style DocstringStyle | None

If provided, use this style for the tool's docstring. If not provided, we will attempt to auto-detect the style.

None
use_docstring_info bool

If True, use the function's docstring to populate the tool's description and argument descriptions.

True
failure_error_function ToolErrorFunction | None | object

If provided, use this function to generate an error message when the tool call fails. The error message is sent to the LLM. If you pass None, then no error message will be sent and instead an Exception will be raised.

_UNSET_FAILURE_ERROR_FUNCTION
strict_mode bool

Whether to enable strict mode for the tool's JSON schema. We strongly recommend setting this to True, as it increases the likelihood of correct JSON input. If False, it allows non-strict JSON schemas. For example, if a parameter has a default value, it will be optional, additional properties are allowed, etc. See here for more: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#supported-schemas

True
is_enabled bool | Callable[[RunContextWrapper[Any], AgentBase], MaybeAwaitable[bool]]

Whether the tool is enabled. Can be a bool or a callable that takes the run context and agent and returns whether the tool is enabled. Disabled tools are hidden from the LLM at runtime.

True
needs_approval bool | Callable[[RunContextWrapper[Any], dict[str, Any], str], Awaitable[bool]]

Whether the tool needs approval before execution. If True, the run will be interrupted and the tool call will need to be approved using RunState.approve() or rejected using RunState.reject() before continuing. Can be a bool (always/never needs approval) or a function that takes (run_context, tool_parameters, call_id) and returns whether this specific call needs approval.

False
tool_input_guardrails list[ToolInputGuardrail[Any]] | None

Optional list of guardrails to run before invoking the tool.

None
tool_output_guardrails list[ToolOutputGuardrail[Any]] | None

Optional list of guardrails to run after the tool returns.

None
timeout float | None

Optional timeout in seconds for each tool call.

None
timeout_behavior ToolTimeoutBehavior

Timeout handling mode. "error_as_result" returns a model-visible message, while "raise_exception" raises ToolTimeoutError and fails the run.

'error_as_result'
timeout_error_function ToolErrorFunction | None

Optional formatter used for timeout messages when timeout_behavior="error_as_result".

None
defer_loading bool

Whether to hide this tool definition until Responses API tool search explicitly loads it.

False
custom_data_extractor FunctionToolCustomDataExtractor | None

Optional callback that returns SDK-only custom data to attach to the emitted ToolCallOutputItem. The returned mapping is not sent to the model.

None
allowed_callers list[ToolCaller] | None

Callers that may invoke the tool on OpenAI Responses models. Include "programmatic" to allow generated programs to call it.

None
output_type Any | None

Optional Python output type used to generate and validate a strict output schema. For programmatic tools this is inferred from a structured return annotation when omitted. Use this override when the callable has no usable return annotation.

None
output_json_schema dict[str, Any] | None

Optional JSON Schema describing the tool's output for programmatic callers. This low-level escape hatch is mutually exclusive with output_type.

None
ソースコード位置: src/agents/tool.py
def function_tool(
    func: ToolFunction[...] | None = None,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    docstring_style: DocstringStyle | None = None,
    use_docstring_info: bool = True,
    failure_error_function: ToolErrorFunction | None | object = _UNSET_FAILURE_ERROR_FUNCTION,
    strict_mode: bool = True,
    is_enabled: bool | Callable[[RunContextWrapper[Any], AgentBase], MaybeAwaitable[bool]] = True,
    needs_approval: bool
    | Callable[[RunContextWrapper[Any], dict[str, Any], str], Awaitable[bool]] = False,
    tool_input_guardrails: list[ToolInputGuardrail[Any]] | None = None,
    tool_output_guardrails: list[ToolOutputGuardrail[Any]] | None = None,
    timeout: float | None = None,
    timeout_behavior: ToolTimeoutBehavior = "error_as_result",
    timeout_error_function: ToolErrorFunction | None = None,
    defer_loading: bool = False,
    custom_data_extractor: FunctionToolCustomDataExtractor | None = None,
    allowed_callers: list[ToolCaller] | None = None,
    output_type: Any | None = None,
    output_json_schema: dict[str, Any] | None = None,
) -> FunctionTool | Callable[[ToolFunction[...]], FunctionTool]:
    """
    Decorator to create a FunctionTool from a function. By default, we will:
    1. Parse the function signature to create a JSON schema for the tool's parameters.
    2. Use the function's docstring to populate the tool's description.
    3. Use the function's docstring to populate argument descriptions.
    The docstring style is detected automatically, but you can override it.

    If the function takes a `RunContextWrapper` as the first argument, it *must* match the
    context type of the agent that uses the tool.

    Args:
        func: The function to wrap.
        name_override: If provided, use this name for the tool instead of the function's name.
        description_override: If provided, use this description for the tool instead of the
            function's docstring.
        docstring_style: If provided, use this style for the tool's docstring. If not provided,
            we will attempt to auto-detect the style.
        use_docstring_info: If True, use the function's docstring to populate the tool's
            description and argument descriptions.
        failure_error_function: If provided, use this function to generate an error message when
            the tool call fails. The error message is sent to the LLM. If you pass None, then no
            error message will be sent and instead an Exception will be raised.
        strict_mode: Whether to enable strict mode for the tool's JSON schema. We *strongly*
            recommend setting this to True, as it increases the likelihood of correct JSON input.
            If False, it allows non-strict JSON schemas. For example, if a parameter has a default
            value, it will be optional, additional properties are allowed, etc. See here for more:
            https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#supported-schemas
        is_enabled: Whether the tool is enabled. Can be a bool or a callable that takes the run
            context and agent and returns whether the tool is enabled. Disabled tools are hidden
            from the LLM at runtime.
        needs_approval: Whether the tool needs approval before execution. If True, the run will
            be interrupted and the tool call will need to be approved using RunState.approve() or
            rejected using RunState.reject() before continuing. Can be a bool (always/never needs
            approval) or a function that takes (run_context, tool_parameters, call_id) and returns
            whether this specific call needs approval.
        tool_input_guardrails: Optional list of guardrails to run before invoking the tool.
        tool_output_guardrails: Optional list of guardrails to run after the tool returns.
        timeout: Optional timeout in seconds for each tool call.
        timeout_behavior: Timeout handling mode. "error_as_result" returns a model-visible message,
            while "raise_exception" raises ToolTimeoutError and fails the run.
        timeout_error_function: Optional formatter used for timeout messages when
            timeout_behavior="error_as_result".
        defer_loading: Whether to hide this tool definition until Responses API tool search
            explicitly loads it.
        custom_data_extractor: Optional callback that returns SDK-only custom data to attach to
            the emitted ``ToolCallOutputItem``. The returned mapping is not sent to the model.
        allowed_callers: Callers that may invoke the tool on OpenAI Responses models. Include
            ``"programmatic"`` to allow generated programs to call it.
        output_type: Optional Python output type used to generate and validate a strict output
            schema. For programmatic tools this is inferred from a structured return annotation
            when omitted. Use this override when the callable has no usable return annotation.
        output_json_schema: Optional JSON Schema describing the tool's output for programmatic
            callers. This low-level escape hatch is mutually exclusive with ``output_type``.
    """

    def _create_function_tool(the_func: ToolFunction[...]) -> FunctionTool:
        the_func, callable_description = _normalize_function_tool_callable(
            the_func,
            docstring_style,
            name_override,
            use_docstring_info,
        )
        is_sync_function_tool = not inspect.iscoroutinefunction(the_func)
        schema = function_schema(
            func=the_func,
            name_override=name_override,
            description_override=description_override
            or (callable_description if use_docstring_info else None),
            docstring_style=docstring_style,
            use_docstring_info=use_docstring_info,
            strict_json_schema=strict_mode,
        )
        resolved_output_json_schema, output_type_adapter = _resolve_function_tool_output(
            return_annotation=schema.return_annotation,
            allowed_callers=allowed_callers,
            output_type=output_type,
            output_json_schema=output_json_schema,
        )

        async def _on_invoke_tool_impl(ctx: ToolContext[Any], input: str) -> Any:
            tool_name = ctx.tool_name
            json_data = _parse_function_tool_json_input(tool_name=tool_name, input_json=input)
            _log_function_tool_invocation(tool_name=tool_name, input_json=input)

            try:
                parsed = (
                    schema.params_pydantic_model(**json_data)
                    if json_data
                    else schema.params_pydantic_model()
                )
            except ValidationError as e:
                raise ModelBehaviorError(f"Invalid JSON input for tool {tool_name}: {e}") from e

            args, kwargs_dict = schema.to_call_args(parsed)

            if not _debug.DONT_LOG_TOOL_DATA:
                logger.debug("Tool call args: %s, kwargs: %s", args, kwargs_dict)

            if not is_sync_function_tool:
                if schema.takes_context:
                    result = await the_func(ctx, *args, **kwargs_dict)
                else:
                    result = await the_func(*args, **kwargs_dict)
            else:
                if schema.takes_context:
                    result = await asyncio.to_thread(the_func, ctx, *args, **kwargs_dict)
                else:
                    result = await asyncio.to_thread(the_func, *args, **kwargs_dict)

            result = _validate_function_tool_output(
                tool_name=tool_name,
                output=result,
                output_type_adapter=output_type_adapter,
            )

            if _debug.DONT_LOG_TOOL_DATA:
                logger.debug("Tool %s completed.", tool_name)
            else:
                logger.debug("Tool %s returned %s", tool_name, result)

            return result

        function_tool = _build_wrapped_function_tool(
            name=schema.name,
            description=schema.description or "",
            params_json_schema=schema.params_json_schema,
            invoke_tool_impl=_on_invoke_tool_impl,
            on_handled_error=_build_handled_function_tool_error_handler(
                span_message="Error running tool (non-fatal)",
                span_message_for_json_decode_error="Error running tool",
                log_label="Tool",
            ),
            failure_error_function=failure_error_function,
            strict_json_schema=strict_mode,
            is_enabled=is_enabled,
            needs_approval=needs_approval,
            tool_input_guardrails=tool_input_guardrails,
            tool_output_guardrails=tool_output_guardrails,
            timeout_seconds=timeout,
            timeout_behavior=timeout_behavior,
            timeout_error_function=timeout_error_function,
            defer_loading=defer_loading,
            custom_data_extractor=custom_data_extractor,
            allowed_callers=allowed_callers,
            output_json_schema=resolved_output_json_schema,
            output_type_adapter=output_type_adapter,
            sync_invoker=is_sync_function_tool,
        )
        return function_tool

    # If func is actually a callable, we were used as @function_tool with no parentheses
    if callable(func):
        return _create_function_tool(func)

    # Otherwise, we were used as @function_tool(...), so return a decorator
    def decorator(real_func: ToolFunction[...]) -> FunctionTool:
        return _create_function_tool(real_func)

    return decorator

tool_input_guardrail

tool_input_guardrail(func: _ToolInputFuncSync)
tool_input_guardrail(func: _ToolInputFuncAsync)
tool_input_guardrail(
    *, name: str | None = None
) -> Callable[
    [_ToolInputFuncSync | _ToolInputFuncAsync],
    ToolInputGuardrail[Any],
]
tool_input_guardrail(
    func: _ToolInputFuncSync
    | _ToolInputFuncAsync
    | None = None,
    *,
    name: str | None = None,
) -> (
    ToolInputGuardrail[Any]
    | Callable[
        [_ToolInputFuncSync | _ToolInputFuncAsync],
        ToolInputGuardrail[Any],
    ]
)

Decorator to create a ToolInputGuardrail from a function.

ソースコード位置: src/agents/tool_guardrails.py
def tool_input_guardrail(
    func: _ToolInputFuncSync | _ToolInputFuncAsync | None = None,
    *,
    name: str | None = None,
) -> (
    ToolInputGuardrail[Any]
    | Callable[[_ToolInputFuncSync | _ToolInputFuncAsync], ToolInputGuardrail[Any]]
):
    """Decorator to create a ToolInputGuardrail from a function."""

    def decorator(f: _ToolInputFuncSync | _ToolInputFuncAsync) -> ToolInputGuardrail[Any]:
        return ToolInputGuardrail(guardrail_function=f, name=name or f.__name__)

    if func is not None:
        return decorator(func)
    return decorator

tool_output_guardrail

tool_output_guardrail(func: _ToolOutputFuncSync)
tool_output_guardrail(func: _ToolOutputFuncAsync)
tool_output_guardrail(
    *, name: str | None = None
) -> Callable[
    [_ToolOutputFuncSync | _ToolOutputFuncAsync],
    ToolOutputGuardrail[Any],
]
tool_output_guardrail(
    func: _ToolOutputFuncSync
    | _ToolOutputFuncAsync
    | None = None,
    *,
    name: str | None = None,
) -> (
    ToolOutputGuardrail[Any]
    | Callable[
        [_ToolOutputFuncSync | _ToolOutputFuncAsync],
        ToolOutputGuardrail[Any],
    ]
)

Decorator to create a ToolOutputGuardrail from a function.

ソースコード位置: src/agents/tool_guardrails.py
def tool_output_guardrail(
    func: _ToolOutputFuncSync | _ToolOutputFuncAsync | None = None,
    *,
    name: str | None = None,
) -> (
    ToolOutputGuardrail[Any]
    | Callable[[_ToolOutputFuncSync | _ToolOutputFuncAsync], ToolOutputGuardrail[Any]]
):
    """Decorator to create a ToolOutputGuardrail from a function."""

    def decorator(f: _ToolOutputFuncSync | _ToolOutputFuncAsync) -> ToolOutputGuardrail[Any]:
        return ToolOutputGuardrail(guardrail_function=f, name=name or f.__name__)

    if func is not None:
        return decorator(func)
    return decorator