AIFunction Class
A tool that wraps a Python function to make it callable by AI models.
This class wraps a Python function to make it callable by AI models with automatic parameter validation and JSON schema generation.
Initialize the AIFunction.
Constructor
AIFunction()
Keyword-Only Parameters
| Name | Description |
|---|---|
|
name
|
The name of the function. |
|
description
|
A description of the function. |
|
approval_mode
|
Whether or not approval is required to run this tool. Default is that approval is not needed. Default value: None
|
|
max_invocations
|
The maximum number of times this function can be invoked. If None, there is no limit. Should be at least 1. Default value: None
|
|
max_invocation_exceptions
|
The maximum number of exceptions allowed during invocations. If None, there is no limit. Should be at least 1. Default value: None
|
|
additional_properties
|
Additional properties to set on the function. Default value: None
|
|
func
|
The function to wrap. Default value: None
|
|
input_model
|
The Pydantic model that defines the input parameters for the function. This can also be a JSON schema dictionary. If not provided, it will be inferred from the function signature. Default value: None
|
|
**kwargs
|
Additional keyword arguments. |
Examples
from typing import Annotated
from pydantic import BaseModel, Field
from agent_framework import AIFunction, ai_function
# Using the decorator with string annotations
@ai_function
def get_weather(
location: Annotated[str, "The city name"],
unit: Annotated[str, "Temperature unit"] = "celsius",
) -> str:
'''Get the weather for a location.'''
return f"Weather in {location}: 22°{unit[0].upper()}"
# Using direct instantiation with Field
class WeatherArgs(BaseModel):
location: Annotated[str, Field(description="The city name")]
unit: Annotated[str, Field(description="Temperature unit")] = "celsius"
weather_func = AIFunction(
name="get_weather",
description="Get the weather for a location",
func=lambda location, unit="celsius": f"Weather in {location}: 22°{unit[0].upper()}",
approval_mode="never_require",
input_model=WeatherArgs,
)
# Invoke the function
result = await weather_func.invoke(arguments=WeatherArgs(location="Seattle"))
Methods
| __init__ |
Initialize the AIFunction. |
| __new__ | |
| from_dict |
Create an instance from a dictionary with optional dependency injection. This method reconstructs an object from its dictionary representation, automatically handling type conversion and dependency injection. It supports three patterns of dependency injection to handle different scenarios where external dependencies need to be provided at deserialization time. |
| from_json |
Create an instance from a JSON string. This is a convenience method that parses the JSON string using |
| invoke |
Run the AI function with the provided arguments as a Pydantic model. |
| parameters |
Create the JSON schema of the parameters. |
| to_dict | |
| to_json |
Convert the instance to a JSON string. This is a convenience method that calls |
| to_json_schema_spec |
Convert a AIFunction to the JSON Schema function specification format. |
__init__
Initialize the AIFunction.
__init__(*, name: str, description: str = '', approval_mode: Literal['always_require', 'never_require'] | None = None, max_invocations: int | None = None, max_invocation_exceptions: int | None = None, additional_properties: dict[str, Any] | None = None, func: Callable[[...], Awaitable[ReturnT] | ReturnT] | None = None, input_model: type[ArgsT] | Mapping[str, Any] | None = None, **kwargs: Any) -> None
Parameters
| Name | Description |
|---|---|
|
name
Required
|
|
|
description
Required
|
|
|
approval_mode
Required
|
Literal['always_require', 'never_require'] | None
|
|
max_invocations
Required
|
|
|
max_invocation_exceptions
Required
|
|
|
additional_properties
Required
|
|
|
func
Required
|
Callable[[...], Awaitable[<xref:agent_framework._tools.ReturnT>] | <xref:agent_framework._tools.ReturnT>] | None
|
|
input_model
Required
|
|
|
kwargs
Required
|
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
name
|
The name of the function. |
|
description
|
A description of the function. Default value: ""
|
|
approval_mode
|
Whether or not approval is required to run this tool. Default is that approval is not needed. Default value: None
|
|
max_invocations
|
The maximum number of times this function can be invoked. If None, there is no limit. Should be at least 1. Default value: None
|
|
max_invocation_exceptions
|
The maximum number of exceptions allowed during invocations. If None, there is no limit. Should be at least 1. Default value: None
|
|
additional_properties
|
Additional properties to set on the function. Default value: None
|
|
func
|
The function to wrap. Default value: None
|
|
input_model
|
The Pydantic model that defines the input parameters for the function. This can also be a JSON schema dictionary. If not provided, it will be inferred from the function signature. Default value: None
|
|
**kwargs
|
Additional keyword arguments. |
Returns
| Type | Description |
|---|---|
__new__
__new__(**kwargs)
from_dict
Create an instance from a dictionary with optional dependency injection.
This method reconstructs an object from its dictionary representation, automatically handling type conversion and dependency injection. It supports three patterns of dependency injection to handle different scenarios where external dependencies need to be provided at deserialization time.
from_dict()
Positional-Only Parameters
| Name | Description |
|---|---|
|
value
Required
|
|
Parameters
| Name | Description |
|---|---|
|
value
Required
|
The dictionary containing the instance data (positional-only). Must include a 'type' field matching the class type identifier. |
|
dependencies
Required
|
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
dependencies
|
A nested dictionary mapping type identifiers to their injectable dependencies. The structure varies based on injection pattern:
Default value: None
|
Returns
| Type | Description |
|---|---|
|
<xref:agent_framework._serialization.TClass>
|
New instance of the class with injected dependencies. |
Exceptions
| Type | Description |
|---|---|
|
If the 'type' field in the data doesn't match the class type identifier. |
Examples
Simple Client Injection - OpenAI client dependency injection:
from agent_framework.openai import OpenAIChatClient
from openai import AsyncOpenAI
# OpenAI chat client requires an AsyncOpenAI client instance
# The client is marked as INJECTABLE = {"client"} in OpenAIBase
# Serialized data contains only the model configuration
client_data = {
"type": "open_ai_chat_client",
"model_id": "gpt-4o-mini",
# client is excluded from serialization
}
# Provide the OpenAI client during deserialization
openai_client = AsyncOpenAI(api_key="your-api-key")
dependencies = {"open_ai_chat_client": {"client": openai_client}}
# The chat client is reconstructed with the OpenAI client injected
chat_client = OpenAIChatClient.from_dict(client_data, dependencies=dependencies)
# Now ready to make API calls with the injected client
Function Injection for Tools - AIFunction runtime dependency:
from agent_framework import AIFunction
from typing import Annotated
# Define a function to be wrapped
async def get_current_weather(location: Annotated[str, "The city name"]) -> str:
# In real implementation, this would call a weather API
return f"Current weather in {location}: 72°F and sunny"
# AIFunction has INJECTABLE = {"func"}
function_data = {
"type": "ai_function",
"name": "get_weather",
"description": "Get current weather for a location",
# func is excluded from serialization
}
# Inject the actual function implementation during deserialization
dependencies = {"ai_function": {"func": get_current_weather}}
# Reconstruct the AIFunction with the callable injected
weather_func = AIFunction.from_dict(function_data, dependencies=dependencies)
# The function is now callable and ready for agent use
Middleware Context Injection - Agent execution context:
from agent_framework._middleware import AgentRunContext
from agent_framework import BaseAgent
# AgentRunContext has INJECTABLE = {"agent", "result"}
context_data = {
"type": "agent_run_context",
"messages": [{"role": "user", "text": "Hello"}],
"is_streaming": False,
"metadata": {"session_id": "abc123"},
# agent and result are excluded from serialization
}
# Inject agent and result during middleware processing
my_agent = BaseAgent(name="test-agent")
dependencies = {
"agent_run_context": {
"agent": my_agent,
"result": None, # Will be populated during execution
}
}
# Reconstruct context with agent dependency for middleware chain
context = AgentRunContext.from_dict(context_data, dependencies=dependencies)
# Middleware can now access context.agent and process the execution
This injection system allows the agent framework to maintain clean separation between serializable configuration and runtime dependencies like API clients, functions, and execution contexts that cannot or should not be persisted.
from_json
Create an instance from a JSON string.
This is a convenience method that parses the JSON string using json.loads()
and then calls from_dict() to reconstruct the object. All dependency injection
capabilities are available through the dependencies parameter.
from_json()
Positional-Only Parameters
| Name | Description |
|---|---|
|
value
Required
|
|
Parameters
| Name | Description |
|---|---|
|
value
Required
|
The JSON string containing the instance data (positional-only). Must be valid JSON that deserializes to a dictionary with a 'type' field. |
|
dependencies
Required
|
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
dependencies
|
A nested dictionary mapping type identifiers to their injectable dependencies. See from_dict for detailed structure and examples of the three injection patterns (simple, dict parameter, and instance-specific). Default value: None
|
Returns
| Type | Description |
|---|---|
|
<xref:agent_framework._serialization.TClass>
|
New instance of the class with any specified dependencies injected. |
Exceptions
| Type | Description |
|---|---|
|
If the JSON string is malformed. |
|
|
If the parsed data doesn't contain a valid 'type' field. |
invoke
Run the AI function with the provided arguments as a Pydantic model.
async invoke(*, arguments: ArgsT | None = None, **kwargs: Any) -> ReturnT
Parameters
| Name | Description |
|---|---|
|
arguments
Required
|
<xref:agent_framework._tools.ArgsT> | None
|
|
kwargs
Required
|
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
arguments
|
A Pydantic model instance containing the arguments for the function. Default value: None
|
|
kwargs
|
Keyword arguments to pass to the function, will not be used if |
Returns
| Type | Description |
|---|---|
|
<xref:agent_framework._tools.ReturnT>
|
The result of the function execution. |
Exceptions
| Type | Description |
|---|---|
|
If arguments is not an instance of the expected input model. |
parameters
to_dict
to_dict(*, exclude: set[str] | None = None, exclude_none: bool = True) -> dict[str, Any]
Parameters
| Name | Description |
|---|---|
|
exclude
Required
|
|
|
exclude_none
Required
|
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
exclude
|
Default value: None
|
|
exclude_none
|
Default value: True
|
Returns
| Type | Description |
|---|---|
to_json
Convert the instance to a JSON string.
This is a convenience method that calls to_dict() and then serializes
the result using json.dumps(). All the same serialization rules apply
as in to_dict(), including automatic exclusion of injectable dependencies
and deep serialization of nested objects.
to_json(*, exclude: set[str] | None = None, exclude_none: bool = True, **kwargs: Any) -> str
Parameters
| Name | Description |
|---|---|
|
exclude
Required
|
|
|
exclude_none
Required
|
|
|
kwargs
Required
|
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
exclude
|
Additional field names to exclude from serialization. Default value: None
|
|
exclude_none
|
Whether to exclude None values from the output. Defaults to True. Default value: True
|
|
**kwargs
|
Additional keyword arguments passed through to |
Returns
| Type | Description |
|---|---|
|
JSON string representation of the instance. |
to_json_schema_spec
Attributes
declaration_only
Indicate whether the function is declaration only (i.e., has no implementation).
DEFAULT_EXCLUDE
DEFAULT_EXCLUDE: ClassVar[set[str]] = {'_invocation_duration_histogram', 'input_model'}
INJECTABLE
INJECTABLE: ClassVar[set[str]] = {'func'}