Principle:Openai Openai agents python Function Tool Definition
Template:Openai Openai agents python Sidebar
Overview
Function Tool Definition is the foundational pattern in the OpenAI Agents Python SDK for exposing arbitrary Python functions as callable tools that an LLM agent can invoke during execution. The function_tool decorator converts a typed Python function into a FunctionTool dataclass, complete with an automatically generated JSON schema derived from the function's type hints and docstring.
| Property | Value |
|---|---|
| Category | Tool Integration |
| Source | src/agents/tool.py (lines 811-989)
|
| API | function_tool(func, *, name_override, description_override, docstring_style, use_docstring_info, failure_error_function, strict_mode, is_enabled, needs_approval, tool_input_guardrails, tool_output_guardrails)
|
| Import | from agents import function_tool
|
| Related Implementation | Function Tool Decorator |
Description
In agentic LLM applications, the model needs a structured way to invoke user-defined code. The tool-use pattern establishes a protocol where:
- The LLM generates a structured tool call (function name plus JSON arguments).
- The framework intercepts the tool call, deserializes arguments, and executes the corresponding Python function.
- The function's return value is serialized and sent back to the model as a tool result.
- The model incorporates the result into its next response.
The function_tool decorator automates the boilerplate of this protocol. It inspects the Python function's signature, type annotations, and docstring to build a complete JSON schema that the LLM uses to produce well-formed tool calls.
Theoretical Basis
Automatic JSON Schema Generation
The decorator leverages Python's type hints and optional docstrings to produce a JSON schema without requiring the developer to write schema definitions manually. The process works as follows:
- Type hint introspection: The function's parameter annotations (e.g.,
str,int,list[str], custom Pydantic models) are converted into corresponding JSON schema types. - Docstring parsing: If
use_docstring_info=True(the default), the function's docstring is parsed to extract the overall tool description and per-parameter descriptions. The SDK supports multiple docstring styles (Google, Sphinx, Numpy) and can auto-detect the format. - Pydantic model generation: Internally, a Pydantic model is synthesized from the parameters, providing robust validation of LLM-supplied arguments before the function is called.
Strict JSON Schema Mode
By default, strict_mode=True enables OpenAI's strict structured output mode. This constrains the LLM to produce JSON that exactly matches the schema, significantly reducing malformed tool calls. When strict mode is active:
- All parameters without defaults become required.
- Additional properties are disallowed.
- The schema conforms to OpenAI's supported subset for strict structured outputs.
Context Injection
Tools can optionally accept a RunContextWrapper or ToolContext as their first argument. This gives the tool access to the current run's state, including:
- The user-defined context object (typed generically).
- Usage tracking information.
- The specific tool call ID and agent name via
ToolContext.
The framework detects the context parameter automatically and injects it at call time, so tools that do not need run state can omit it entirely.
Error Handling and Resilience
The function_tool decorator wraps execution in an error handler. By default, if the tool function raises an exception, a failure_error_function converts the error into a string message that is sent back to the LLM rather than crashing the entire run. This allows the model to recover gracefully (e.g., by retrying with corrected arguments). The developer can override this behavior by:
- Providing a custom
failure_error_function. - Setting it to
Noneto propagate exceptions directly.
Dynamic Enablement and Approval
Tools support runtime control through two mechanisms:
is_enabled: A boolean or callable that determines whether the tool is visible to the LLM on a given turn. Disabled tools are omitted from the tool list entirely.needs_approval: A boolean or callable that gates execution behind a human-in-the-loop approval step. When approval is required, the run is interrupted and must be explicitly resumed.
Guardrails
Function tools support both input and output guardrails:
tool_input_guardrails: Validated before the tool executes, allowing the framework to reject dangerous or out-of-scope inputs.tool_output_guardrails: Validated after the tool returns, ensuring the output meets quality or safety constraints before being sent to the model.
Usage
The function_tool decorator can be applied in two ways:
# 1. Direct decoration (no options)
@function_tool
def get_weather(city: str) -> str:
"""Get the current weather for a city."""
return f"The weather in {city} is sunny."
# 2. Decoration with options
@function_tool(name_override="lookup_weather", strict_mode=True)
def get_weather(city: str, units: str = "celsius") -> str:
"""Get weather information.
Args:
city: The city name
units: Temperature units (celsius or fahrenheit)
"""
return f"Weather in {city}: 22 degrees"
The resulting FunctionTool is then passed to an agent's tools list:
from agents import Agent
agent = Agent(
name="weather_bot",
instructions="Answer weather questions using the tools provided.",
tools=[get_weather],
)
Related Pages
- Implementation:Openai_Openai_agents_python_Function_Tool_Decorator
- Implementation: Function Tool Decorator -- the concrete implementation of the
function_tooldecorator - Principle: Tool Execution Loop -- how tool calls are executed within the agent run cycle
- Principle: Hosted Tool Configuration -- server-side hosted tools as an alternative to function tools