FunctionInvocationConfiguration Class

Configuration for function invocation in chat clients.

This class is created automatically on every chat client that supports function invocation. This means that for most cases you can just alter the attributes on the instance, rather then creating a new one.

Initialize FunctionInvocationConfiguration.

Constructor

FunctionInvocationConfiguration()

Parameters

Name Description
enabled

Whether function invocation is enabled.

Default value: True
max_iterations

Maximum number of function invocation iterations.

Default value: 40
max_consecutive_errors_per_request

Maximum consecutive errors allowed per request.

Default value: 3
terminate_on_unknown_calls

Whether to terminate on unknown function calls.

Default value: False
additional_tools

Additional tools to include for function execution.

Default value: None
include_detailed_errors

Whether to include detailed error information in function results.

Default value: False

Methods

__init__

Initialize FunctionInvocationConfiguration.

__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 json.loads() and then calls from_dict() to reconstruct the object. All dependency injection capabilities are available through the dependencies parameter.

to_dict

Convert the instance and any nested objects to a dictionary.

This method performs deep serialization, automatically converting nested SerializationProtocol objects, lists, and dictionaries containing serializable objects. Non-serializable objects are skipped with debug logging.

Fields marked in DEFAULT_EXCLUDE and INJECTABLE are automatically excluded from the output, as are any private attributes (starting with '_').

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.

__init__

Initialize FunctionInvocationConfiguration.

__init__(enabled: bool = True, max_iterations: int = DEFAULT_MAX_ITERATIONS, max_consecutive_errors_per_request: int = DEFAULT_MAX_CONSECUTIVE_ERRORS_PER_REQUEST, terminate_on_unknown_calls: bool = False, additional_tools: Sequence[ToolProtocol] | None = None, include_detailed_errors: bool = False) -> None

Parameters

Name Description
enabled

Whether function invocation is enabled.

Default value: True
max_iterations
int

Maximum number of function invocation iterations.

Default value: DEFAULT_MAX_ITERATIONS
max_consecutive_errors_per_request
int

Maximum consecutive errors allowed per request.

Default value: DEFAULT_MAX_CONSECUTIVE_ERRORS_PER_REQUEST
terminate_on_unknown_calls

Whether to terminate on unknown function calls.

Default value: False
additional_tools

Additional tools to include for function execution.

Default value: None
include_detailed_errors

Whether to include detailed error information in function results.

Default value: False

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:

  • Simple injection: {"<type>": {"<parameter>": value}}

  • Dict parameter injection: {"<type>": {"<dict-parameter>": {"<key>": value}}}

  • Instance-specific injection: {"<type>": {"<field>:<value>": {"<parameter>": value}}}

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
str

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.

to_dict

Convert the instance and any nested objects to a dictionary.

This method performs deep serialization, automatically converting nested SerializationProtocol objects, lists, and dictionaries containing serializable objects. Non-serializable objects are skipped with debug logging.

Fields marked in DEFAULT_EXCLUDE and INJECTABLE are automatically excluded from the output, as are any private attributes (starting with '_').

to_dict(*, exclude: set[str] | None = None, exclude_none: bool = True) -> dict[str, Any]

Parameters

Name Description
exclude
Required
set[str] | None
exclude_none
Required

Keyword-Only Parameters

Name Description
exclude

Additional field names to exclude from serialization beyond the default exclusions (DEFAULT_EXCLUDE and INJECTABLE).

Default value: None
exclude_none

Whether to exclude None values from the output. When True, None values are omitted from the dictionary. Defaults to True.

Default value: True

Returns

Type Description

Dictionary representation of the instance including a 'type' field for type identification during deserialization (unless 'type' is excluded).

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
set[str] | None
exclude_none
Required
kwargs
Required
Any

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 json.dumps(). Common options include indent for pretty-printing and ensure_ascii for Unicode handling.

Returns

Type Description
str

JSON string representation of the instance.

Attributes

enabled

Whether function invocation is enabled. When this is set to False, the client will not attempt to invoke any functions, because the tool mode will be set to None.

max_iterations

Maximum number of function invocation iterations. Each request to this client might end up making multiple requests to the model. Each time the model responds with a function call request, this client might perform that invocation and send the results back to the model in a new request. This property limits the number of times such a roundtrip is performed. The value must be at least one, as it includes the initial request. If you want to fully disable function invocation, use the enabled property. The default is 40.

max_consecutive_errors_per_request

Maximum consecutive errors allowed per request. The maximum number of consecutive function call errors allowed before stopping further function calls for the request. The default is 3.

terminate_on_unknown_calls

Whether to terminate on unknown function calls. When False, call requests to any tools that aren't available to the client will result in a response message automatically being created and returned to the inner client stating that the tool couldn't be found. This behavior can help in cases where a model hallucinates a function, but it's problematic if the model has been made aware of the existence of tools outside of the normal mechanisms, and requests one of those. additional_tools can be used to help with that. But if instead the consumer wants to know about all function call requests that the client can't handle, this can be set to True. Upon receiving a request to call a function that the client doesn't know about, it will terminate the function calling loop and return the response, leaving the handling of the function call requests to the consumer of the client.

additional_tools

Additional tools to include for function execution. These will not impact the requests sent by the client, which will pass through the tools unmodified. However, if the inner client requests the invocation of a tool that was not in ChatOptions.tools, this additional_tools collection will also be consulted to look for a corresponding tool. This is useful when the service might have been pre-configured to be aware of certain tools that aren't also sent on each individual request. These tools are treated the same as declaration_only tools and will be returned to the user.

include_detailed_errors

Whether to include detailed error information in function results. When set to True, detailed error information such as exception type and message will be included in the function result content when a function invocation fails. When False, only a generic error message will be included.

DEFAULT_EXCLUDE

DEFAULT_EXCLUDE: ClassVar[set[str]] = {}

INJECTABLE

INJECTABLE: ClassVar[set[str]] = {}