autogen_core.tools#
- class BaseTool(args_type: Type[ArgsT], return_type: Type[ReturnT], name: str, description: str, strict: bool = False)[source]#
Bases:
ABC
,Tool
,Generic
[ArgsT
,ReturnT
],ComponentBase
[BaseModel
]- component_type: ClassVar[ComponentType] = 'tool'#
The logical type of the component.
- abstract async run(args: ArgsT, cancellation_token: CancellationToken) ReturnT [source]#
- property schema: ToolSchema#
- class BaseToolWithState(args_type: Type[ArgsT], return_type: Type[ReturnT], state_type: Type[StateT], name: str, description: str)[source]#
Bases:
BaseTool
[ArgsT
,ReturnT
],ABC
,Generic
[ArgsT
,ReturnT
,StateT
],ComponentBase
[BaseModel
]- component_type: ClassVar[ComponentType] = 'tool'#
The logical type of the component.
- class FunctionTool(func: Callable[[...], Any], description: str, name: str | None = None, global_imports: Sequence[str | ImportFromModule | Alias] = [], strict: bool = False)[source]#
Bases:
BaseTool
[BaseModel
,BaseModel
],Component
[FunctionToolConfig
]Create custom tools by wrapping standard Python functions.
FunctionTool offers an interface for executing Python functions either asynchronously or synchronously. Each function must include type annotations for all parameters and its return type. These annotations enable FunctionTool to generate a schema necessary for input validation, serialization, and for informing the LLM about expected parameters. When the LLM prepares a function call, it leverages this schema to generate arguments that align with the function’s specifications.
Note
It is the user’s responsibility to verify that the tool’s output type matches the expected type.
- Parameters:
func (Callable[..., ReturnT | Awaitable[ReturnT]]) – The function to wrap and expose as a tool.
description (str) – A description to inform the model of the function’s purpose, specifying what it does and the context in which it should be called.
name (str, optional) – An optional custom name for the tool. Defaults to the function’s original name if not provided.
strict (bool, optional) – If set to True, the tool schema will only contain arguments that are explicitly defined in the function signature, and no default values will be allowed. Defaults to False. This is required to be set to True when used with models in structured output mode.
Example
import random from autogen_core import CancellationToken from autogen_core.tools import FunctionTool from typing_extensions import Annotated import asyncio async def get_stock_price(ticker: str, date: Annotated[str, "Date in YYYY/MM/DD"]) -> float: # Simulates a stock price retrieval by returning a random float within a specified range. return random.uniform(10, 200) async def example(): # Initialize a FunctionTool instance for retrieving stock prices. stock_price_tool = FunctionTool(get_stock_price, description="Fetch the stock price for a given ticker.") # Execute the tool with cancellation support. cancellation_token = CancellationToken() result = await stock_price_tool.run_json({"ticker": "AAPL", "date": "2021/01/01"}, cancellation_token) # Output the result as a formatted string. print(stock_price_tool.return_value_as_string(result)) asyncio.run(example())
- classmethod _from_config(config: FunctionToolConfig) Self [source]#
Create a new instance of the component from a configuration object.
- Parameters:
config (T) – The configuration object.
- Returns:
Self – The new instance of the component.
- _to_config() FunctionToolConfig [source]#
Dump the configuration that would be requite to create a new instance of a component matching the configuration of this instance.
- Returns:
T – The configuration of the component.
- component_config_schema#
alias of
FunctionToolConfig
- component_provider_override: ClassVar[str | None] = 'autogen_core.tools.FunctionTool'#
Override the provider string for the component. This should be used to prevent internal module names being a part of the module name.
- async run(args: BaseModel, cancellation_token: CancellationToken) Any [source]#
- pydantic model ImageResultContent[source]#
Bases:
BaseModel
Image result content of a tool execution.
Show JSON schema
{ "title": "ImageResultContent", "description": "Image result content of a tool execution.", "type": "object", "properties": { "type": { "const": "ImageResultContent", "default": "ImageResultContent", "title": "Type", "type": "string" }, "content": { "title": "Content" } }, "required": [ "content" ] }
- Fields:
content (autogen_core._image.Image)
type (Literal['ImageResultContent'])
- class ParametersSchema[source]#
Bases:
TypedDict
- additionalProperties: NotRequired[bool]#
- required: NotRequired[Sequence[str]]#
- class StaticWorkbench(tools: List[BaseTool[Any, Any]])[source]#
Bases:
Workbench
,Component
[StaticWorkbenchConfig
]A workbench that provides a static set of tools that do not change after each tool execution.
- Parameters:
tools (List[BaseTool[Any, Any]]) – A list of tools to be included in the workbench. The tools should be subclasses of
BaseTool
.
- classmethod _from_config(config: StaticWorkbenchConfig) Self [source]#
Create a new instance of the component from a configuration object.
- Parameters:
config (T) – The configuration object.
- Returns:
Self – The new instance of the component.
- _to_config() StaticWorkbenchConfig [source]#
Dump the configuration that would be requite to create a new instance of a component matching the configuration of this instance.
- Returns:
T – The configuration of the component.
- async call_tool(name: str, arguments: Mapping[str, Any] | None = None, cancellation_token: CancellationToken | None = None) ToolResult [source]#
Call a tool in the workbench.
- Parameters:
name (str) – The name of the tool to call.
arguments (Mapping[str, Any] | None) – The arguments to pass to the tool. If None, the tool will be called with no arguments.
cancellation_token (CancellationToken | None) – An optional cancellation token to cancel the tool execution.
- Returns:
ToolResult – The result of the tool execution.
- component_config_schema#
alias of
StaticWorkbenchConfig
- component_provider_override: ClassVar[str | None] = 'autogen_core.tools.StaticWorkbench'#
Override the provider string for the component. This should be used to prevent internal module names being a part of the module name.
- async list_tools() List[ToolSchema] [source]#
List the currently available tools in the workbench as
ToolSchema
objects.The list of tools may be dynamic, and their content may change after tool execution.
- async load_state(state: Mapping[str, Any]) None [source]#
Load the state of the workbench.
- Parameters:
state (Mapping[str, Any]) – The state to load into the workbench.
- async save_state() Mapping[str, Any] [source]#
Save the state of the workbench.
This method should be called to persist the state of the workbench.
- pydantic model TextResultContent[source]#
Bases:
BaseModel
Text result content of a tool execution.
Show JSON schema
{ "title": "TextResultContent", "description": "Text result content of a tool execution.", "type": "object", "properties": { "type": { "const": "TextResultContent", "default": "TextResultContent", "title": "Type", "type": "string" }, "content": { "title": "Content", "type": "string" } }, "required": [ "content" ] }
- Fields:
content (str)
type (Literal['TextResultContent'])
- class Tool(*args, **kwargs)[source]#
Bases:
Protocol
- property schema: ToolSchema#
- pydantic model ToolResult[source]#
Bases:
BaseModel
A result of a tool execution by a workbench.
Show JSON schema
{ "title": "ToolResult", "description": "A result of a tool execution by a workbench.", "type": "object", "properties": { "type": { "const": "ToolResult", "default": "ToolResult", "title": "Type", "type": "string" }, "name": { "title": "Name", "type": "string" }, "result": { "items": { "discriminator": { "mapping": { "ImageResultContent": "#/$defs/ImageResultContent", "TextResultContent": "#/$defs/TextResultContent" }, "propertyName": "type" }, "oneOf": [ { "$ref": "#/$defs/TextResultContent" }, { "$ref": "#/$defs/ImageResultContent" } ] }, "title": "Result", "type": "array" }, "is_error": { "default": false, "title": "Is Error", "type": "boolean" } }, "$defs": { "ImageResultContent": { "description": "Image result content of a tool execution.", "properties": { "type": { "const": "ImageResultContent", "default": "ImageResultContent", "title": "Type", "type": "string" }, "content": { "title": "Content" } }, "required": [ "content" ], "title": "ImageResultContent", "type": "object" }, "TextResultContent": { "description": "Text result content of a tool execution.", "properties": { "type": { "const": "TextResultContent", "default": "TextResultContent", "title": "Type", "type": "string" }, "content": { "title": "Content", "type": "string" } }, "required": [ "content" ], "title": "TextResultContent", "type": "object" } }, "required": [ "name", "result" ] }
- Fields:
is_error (bool)
name (str)
result (List[autogen_core.tools._workbench.TextResultContent | autogen_core.tools._workbench.ImageResultContent])
type (Literal['ToolResult'])
- field result: List[Annotated[TextResultContent | ImageResultContent, FieldInfo(annotation=NoneType, required=True, discriminator='type')]] [Required]#
The result of the tool execution.
- to_text(replace_image: str | None = None) str [source]#
Convert the result to a text string.
- Parameters:
replace_image (str | None) – The string to replace the image content with. If None, the image content will be included in the text as base64 string.
- Returns:
str – The text representation of the result.
- class ToolSchema[source]#
Bases:
TypedDict
- description: NotRequired[str]#
- parameters: NotRequired[ParametersSchema]#
- strict: NotRequired[bool]#
- class Workbench[source]#
Bases:
ABC
,ComponentBase
[BaseModel
]A workbench is a component that provides a set of tools that may share resources and state.
A workbench is responsible for managing the lifecycle of the tools and providing a single interface to call them. The tools provided by the workbench may be dynamic and their availabilities may change after each tool execution.
A workbench can be started by calling the
start()
method and stopped by calling thestop()
method. It can also be used as an asynchronous context manager, which will automatically start and stop the workbench when entering and exiting the context.- abstract async call_tool(name: str, arguments: Mapping[str, Any] | None = None, cancellation_token: CancellationToken | None = None) ToolResult [source]#
Call a tool in the workbench.
- Parameters:
name (str) – The name of the tool to call.
arguments (Mapping[str, Any] | None) – The arguments to pass to the tool. If None, the tool will be called with no arguments.
cancellation_token (CancellationToken | None) – An optional cancellation token to cancel the tool execution.
- Returns:
ToolResult – The result of the tool execution.
- component_type: ClassVar[ComponentType] = 'workbench'#
The logical type of the component.
- abstract async list_tools() List[ToolSchema] [source]#
List the currently available tools in the workbench as
ToolSchema
objects.The list of tools may be dynamic, and their content may change after tool execution.
- abstract async load_state(state: Mapping[str, Any]) None [source]#
Load the state of the workbench.
- Parameters:
state (Mapping[str, Any]) – The state to load into the workbench.
- abstract async save_state() Mapping[str, Any] [source]#
Save the state of the workbench.
This method should be called to persist the state of the workbench.