autogen_core.tools#

class BaseTool(args_type: Type[ArgsT], return_type: Type[ReturnT], name: str, description: str, strict: bool = False)[源代码]#

基类: ABC, Tool, Generic[ArgsT, ReturnT], ComponentBase[BaseModel]

args_type() Type[BaseModel][源代码]#
component_type: ClassVar[ComponentType] = 'tool'#

组件的逻辑类型。

property description: str#
async load_state_json(state: Mapping[str, Any]) None[源代码]#
property name: str#
return_type() Type[Any][源代码]#
return_value_as_string(value: Any) str[源代码]#
abstract async run(args: ArgsT, cancellation_token: CancellationToken) ReturnT[源代码]#
async run_json(args: Mapping[str, Any], cancellation_token: CancellationToken) Any[源代码]#
async save_state_json() Mapping[str, Any][source]#
property schema: ToolSchema#
state_type() Type[BaseModel] | None[source]#
class BaseToolWithState(args_type: Type[ArgsT], return_type: Type[ReturnT], state_type: Type[StateT], name: str, description: str)[source]#

继承自:BaseTool[ArgsT, ReturnT], ABC, Generic[ArgsT, ReturnT, StateT], ComponentBase[BaseModel]

component_type: ClassVar[ComponentType] = 'tool'#

组件的逻辑类型。

abstract load_state(state: StateT) None[source]#
async load_state_json(state: Mapping[str, Any]) None[source]#
abstract save_state() StateT[source]#
async save_state_json() Mapping[str, Any][source]#
class FunctionTool(func: Callable[[...], Any], description: str, name: str | None = None, global_imports: Sequence[str | ImportFromModule | Alias] = [], strict: bool = False)[source]#

继承自:BaseTool[BaseModel, BaseModel], Component[FunctionToolConfig]

通过封装标准 Python 函数来创建自定义工具。

FunctionTool 提供了一个用于异步或同步执行 Python 函数的接口。每个函数都必须包含所有参数及其返回类型的类型注释。这些注释使 FunctionTool 能够生成输入验证、序列化以及通知 LLM 关于预期参数所需的模式。当 LLM 准备一个函数调用时,它会利用这个模式来生成与函数规范对齐的参数。

注意

用户有责任验证工具的输出类型是否与预期类型匹配。

参数:
  • func (Callable[..., ReturnT | Awaitable[ReturnT]]) – 要包装并作为工具公开的函数。

  • description (str) – 用于告知模型函数用途的描述,指定其功能以及应在何种情况下调用它。

  • name (str, optional) – 工具的可选自定义名称。如果未提供,则默认为函数的原始名称。

  • strict (bool, optional) – 如果设置为 True,则工具模式将仅包含在函数签名中显式定义的参数,并且不允许使用默认值。默认为 False。与结构化输出模式中的模型一起使用时,必须将其设置为 True。

示例

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]#

从配置对象创建一个组件的新实例。

参数:

config (T) – 配置对象。

返回值:

Self – 组件的新实例。

_to_config() FunctionToolConfig[source]#

转储创建与此实例配置匹配的组件新实例所需的配置。

返回值:

T – 组件的配置。

component_config_schema#

别名为 FunctionToolConfig

component_provider_override: ClassVar[str | None] = 'autogen_core.tools.FunctionTool'#

覆盖组件的提供程序字符串。这应用于防止内部模块名称成为模块名称的一部分。

async run(args: BaseModel, cancellation_token: CancellationToken) Any[source]#
pydantic 模型 ImageResultContent[source]#

基类: BaseModel

工具执行的图像结果内容。

显示 JSON 模式
{
   "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"
   ]
}

字段:
  • content (autogen_core._image.Image)

  • type (Literal['ImageResultContent'])

field content: Image [Required]#

结果的图像内容。

field type: Literal['ImageResultContent'] = 'ImageResultContent'#
class ParametersSchema[source]#

基类: TypedDict

additionalProperties: NotRequired[bool]#
properties: Dict[str, Any]#
required: NotRequired[Sequence[str]]#
type: str#
class StaticWorkbench(tools: List[BaseTool[Any, Any]])[source]#

基类: Workbench, Component[StaticWorkbenchConfig]

一个工作台,提供一组静态工具,这些工具在每次工具执行后都不会改变。

参数:

tools (List[BaseTool[Any, Any]]) – 要包含在工作台中的工具列表。这些工具应该是 BaseTool 的子类。

classmethod _from_config(config: StaticWorkbenchConfig) Self[source]#

从配置对象创建一个组件的新实例。

参数:

config (T) – 配置对象。

返回值:

Self – 组件的新实例。

_to_config() StaticWorkbenchConfig[source]#

转储创建与此实例配置匹配的组件新实例所需的配置。

返回值:

T – 组件的配置。

async call_tool(name: str, arguments: Mapping[str, Any] | None = None, cancellation_token: CancellationToken | None = None) ToolResult[source]#

调用工作台中的工具。

参数:
  • name (str) – 要调用的工具的名称。

  • arguments (Mapping[str, Any] | None) – 传递给工具的参数。如果为 None,则调用工具时不带任何参数。

  • cancellation_token (CancellationToken | None) – 用于取消工具执行的可选取消令牌。

返回值:

ToolResult – 工具执行的结果。

component_config_schema#

alias of StaticWorkbenchConfig

component_provider_override: ClassVar[str | None] = 'autogen_core.tools.StaticWorkbench'#

覆盖组件的提供程序字符串。这应用于防止内部模块名称成为模块名称的一部分。

async list_tools() List[ToolSchema][source]#

将工作台中当前可用的工具列为 ToolSchema 对象。

工具列表可能是动态的,并且它们的内容可能在工具执行后发生更改。

async load_state(state: Mapping[str, Any]) None[source]#

加载工作台的状态。

参数:

state (Mapping[str, Any]) – 要加载到工作台中的状态。

async reset() None[source]#

将工作台重置为其初始化、启动状态。

async save_state() Mapping[str, Any][source]#

保存工作台的状态。

应调用此方法以持久化工作台的状态。

async start() None[source]#

启动工作台并初始化任何资源。

应在使用工作台之前调用此方法。

async stop() None[source]#

停止工作台并释放任何资源。

当不再需要工作台时,应调用此方法。

pydantic model TextResultContent[source]#

基类: BaseModel

工具执行的文本结果内容。

显示 JSON 模式
{
   "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"
   ]
}

字段:
  • content (str)

  • type (Literal['TextResultContent'])

field content: str [Required]#

结果的文本内容。

field type: Literal['TextResultContent'] = 'TextResultContent'#
class Tool(*args, **kwargs)[source]#

基类:Protocol

args_type() Type[BaseModel][source]#
property description: str#
async load_state_json(state: Mapping[str, Any]) None[source]#
property name: str#
return_type() Type[Any][source]#
return_value_as_string(value: Any) str[source]#
async run_json(args: Mapping[str, Any], cancellation_token: CancellationToken) Any[source]#
async save_state_json() Mapping[str, Any][source]#
property schema: ToolSchema#
state_type() Type[BaseModel] | None[source]#
pydantic model ToolResult[source]#

基类: BaseModel

工作台执行工具的结果。

显示 JSON 模式
{
   "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"
   ]
}

字段:
  • is_error (bool)

  • name (str)

  • result (List[autogen_core.tools._workbench.TextResultContent | autogen_core.tools._workbench.ImageResultContent])

  • type (Literal['ToolResult'])

field is_error: bool = False#

工具执行是否出错。

field name: str [Required]#

执行的工具的名称。

field result: List[Annotated[TextResultContent | ImageResultContent, FieldInfo(annotation=NoneType, required=True, discriminator='type')]] [Required]#

工具执行的结果。

field type: Literal['ToolResult'] = 'ToolResult'#
to_text(replace_image: str | None = None) str[source]#

将结果转换为文本字符串。

参数:

replace_image (str | None) – 用于替换图像内容的字符串。如果为 None,图像内容将作为 base64 字符串包含在文本中。

返回值:

str – 结果的文本表示形式。

class ToolSchema[source]#

基类: TypedDict

description: NotRequired[str]#
name: str#
parameters: NotRequired[ParametersSchema]#
strict: NotRequired[bool]#
class Workbench[source]#

基类: ABC, ComponentBase[BaseModel]

工作台是一个组件,它提供一组可能共享资源和状态的工具。

工作台负责管理工具的生命周期,并提供一个单一的接口来调用它们。工作台提供的工具可能是动态的,并且它们的可用性可能会在每次工具执行后发生变化。

可以通过调用 start() 方法来启动工作台,并通过调用 stop() 方法来停止工作台。它也可以用作异步上下文管理器,它将在进入和退出上下文时自动启动和停止工作台。

abstract async call_tool(name: str, arguments: Mapping[str, Any] | None = None, cancellation_token: CancellationToken | None = None) ToolResult[source]#

调用工作台中的工具。

参数:
  • name (str) – 要调用的工具的名称。

  • arguments (Mapping[str, Any] | None) – 传递给工具的参数。如果为 None,则调用工具时不带任何参数。

  • cancellation_token (CancellationToken | None) – 用于取消工具执行的可选取消令牌。

返回值:

ToolResult – 工具执行的结果。

component_type: ClassVar[ComponentType] = 'workbench'#

组件的逻辑类型。

abstract async list_tools() List[ToolSchema][source]#

将工作台中当前可用的工具列为 ToolSchema 对象。

工具列表可能是动态的,并且它们的内容可能在工具执行后发生更改。

abstract async load_state(state: Mapping[str, Any]) None[source]#

加载工作台的状态。

参数:

state (Mapping[str, Any]) – 要加载到工作台中的状态。

abstract async reset() None[source]#

将工作台重置为其初始化、启动状态。

abstract async save_state() Mapping[str, Any][source]#

保存工作台的状态。

应调用此方法以持久化工作台的状态。

abstract async start() None[source]#

启动工作台并初始化任何资源。

应在使用工作台之前调用此方法。

abstract async stop() None[source]#

停止工作台并释放任何资源。

当不再需要工作台时,应调用此方法。