Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Microsoft Autogen FunctionTool Init

From Leeroopedia
Knowledge Sources
Domains Tool Use, Function Calling, LLM Agents, Schema Generation
Last Updated 2026-02-11 00:00 GMT

Overview

Concrete tool for wrapping Python functions as LLM-callable tools with auto-generated JSON schemas, provided by Microsoft AutoGen.

Description

FunctionTool takes a Python function (sync or async) and wraps it as a tool that an LLM agent can invoke via structured tool calling. During initialization, it inspects the function's type annotations and signature to automatically generate a Pydantic model for the arguments, which in turn produces the JSON Schema presented to the LLM. The function's docstring or an explicit description is attached for the LLM to understand the tool's purpose. At execution time, the tool deserializes JSON arguments into the Pydantic model, validates them, and calls the original function with the validated keyword arguments.

FunctionTool supports both synchronous and asynchronous functions. Synchronous functions are executed in a thread pool executor to avoid blocking the event loop. If the function signature includes a cancellation_token parameter, the tool automatically passes the framework's cancellation token, enabling cooperative cancellation of long-running operations.

Usage

Import and instantiate FunctionTool when you have a Python function that you want to make available to an LLM agent. Pass the resulting FunctionTool instance to an agent's tools parameter or add it to a StaticWorkbench. Use this when you need explicit control over the tool name or description; for simpler cases, you can pass plain callables directly to the agent and they will be auto-wrapped.

Code Reference

Source Location

  • Repository: Microsoft AutoGen
  • File: python/packages/autogen-core/src/autogen_core/tools/_function_tool.py (lines 88-103)

Signature

class FunctionTool:
    def __init__(
        self,
        func: Callable[..., Any],
        description: str,
        name: str | None = None,
        global_imports: Sequence[Import] = [],
        strict: bool = False,
    ) -> None:
        ...

Import

from autogen_core.tools import FunctionTool

I/O Contract

Inputs

Name Type Required Description
func Callable[..., Any] Yes The Python function (sync or async) to wrap as a tool. Type annotations on parameters are used to generate the JSON Schema. If the function accepts a cancellation_token parameter, the framework will pass its cancellation token automatically.
description str Yes A natural-language description of what the tool does. This is presented to the LLM to help it decide when to use the tool.
name str or None No An explicit name for the tool. If not provided, the function's __name__ is used. For functools.partial objects, the wrapped function's name is used.
global_imports Sequence[Import] No A list of import specifications needed when the function is serialized or executed in a different context. Defaults to an empty list.
strict bool No Whether to enforce strict JSON Schema mode. When True, all properties are marked as required and additionalProperties is set to False. Defaults to False.

Outputs

Name Type Description
instance FunctionTool A tool object that implements BaseTool. It exposes a schema property (returning a ToolSchema with the generated JSON Schema) and a run(args, cancellation_token) method for execution.

Usage Examples

Basic Example

from autogen_core.tools import FunctionTool


async def get_weather(city: str, units: str = "celsius") -> str:
    """Get the current weather for a city."""
    return f"The weather in {city} is 72 degrees {units}."


weather_tool = FunctionTool(
    func=get_weather,
    description="Get the current weather for a specified city.",
)

# Inspect the generated schema
print(weather_tool.schema)

Custom Name and Strict Mode

from autogen_core.tools import FunctionTool


def calculate_compound_interest(
    principal: float, rate: float, years: int
) -> float:
    """Calculate compound interest."""
    return principal * (1 + rate) ** years


tool = FunctionTool(
    func=calculate_compound_interest,
    description="Calculate compound interest given principal, rate, and years.",
    name="compound_interest",
    strict=True,
)

Using with an Agent

from autogen_core.tools import FunctionTool
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_agentchat.agents import AssistantAgent


async def search_web(query: str) -> str:
    """Search the web for information."""
    return f"Results for: {query}"


search_tool = FunctionTool(
    func=search_web,
    description="Search the web for information on a topic.",
)

model_client = OpenAIChatCompletionClient(model="gpt-4o")

agent = AssistantAgent(
    name="research_assistant",
    model_client=model_client,
    tools=[search_tool],
)

Related Pages

Implements Principle

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment