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][源代码]#
property schema: ToolSchema#
state_type() Type[BaseModel] | None[源代码]#
class BaseToolWithState(args_type: Type[ArgsT], return_type: Type[ReturnT], state_type: Type[StateT], name: str, description: str)[源代码]#

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

component_type: ClassVar[ComponentType] = 'tool'#

组件的逻辑类型。

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

基类: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:
    # 通过返回指定范围内的随机浮点数模拟股票价格检索。
    return random.uniform(10, 200)


async def example():
    # 初始化用于检索股票价格的 FunctionTool 实例。
    stock_price_tool = FunctionTool(get_stock_price, description="获取给定股票代码的价格。")

    # 执行支持取消的工具。
    cancellation_token = CancellationToken()
    result = await stock_price_tool.run_json({"ticker": "AAPL", "date": "2021/01/01"}, cancellation_token)

    # 将结果格式化为字符串输出。
    print(stock_price_tool.return_value_as_string(result))


asyncio.run(example())
classmethod _from_config(config: FunctionToolConfig) Self[源代码]#

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

参数:

config (T) -- 配置对象。

Returns:

Self -- 组件的新实例。

_to_config() FunctionToolConfig[源代码]#

导出当前组件实例的配置,该配置可用于创建具有相同配置的新组件实例。

Returns:

T -- 组件的配置。

component_config_schema#

FunctionToolConfig 的别名

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

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

async run(args: BaseModel, cancellation_token: CancellationToken) Any[源代码]#
pydantic model ImageResultContent[源代码]#

基类:BaseModel

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

Show JSON schema
{
   "title": "ImageResultContent",
   "description": "\u5de5\u5177\u6267\u884c\u7ed3\u679c\u7684\u56fe\u50cf\u5185\u5bb9\u3002",
   "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'])

field content: Image [Required]#

结果的图像内容。

field type: Literal['ImageResultContent'] = 'ImageResultContent'#
class ParametersSchema[源代码]#

基类:TypedDict

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

基类:Workbench, Component[StaticWorkbenchConfig]

一个提供静态工具集的工作台,每次工具执行后不会改变。

参数:

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

classmethod _from_config(config: StaticWorkbenchConfig) Self[源代码]#

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

参数:

config (T) -- 配置对象。

Returns:

Self -- 组件的新实例。

_to_config() StaticWorkbenchConfig[源代码]#

导出当前组件实例的配置,该配置可用于创建具有相同配置的新组件实例。

Returns:

T -- 组件的配置。

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

调用工作台中的工具。

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

  • arguments (Mapping[str, Any] | None) -- 传递给工具的参数。 如果为None,工具将在无参数情况下被调用。

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

Returns:

ToolResult -- 工具执行的结果。

component_config_schema#

StaticWorkbenchConfig 的别名

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

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

async list_tools() List[ToolSchema][源代码]#

ToolSchema 对象形式列出工作台中当前可用的工具。

工具列表可能是动态的,其内容可能在工具执行后发生变化。

async load_state(state: Mapping[str, Any]) None[源代码]#

加载工作台的状态。

参数:

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

async reset() None[源代码]#

将工作台重置为初始化后的启动状态。

async save_state() Mapping[str, Any][源代码]#

保存工作台的状态。

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

async start() None[源代码]#

启动工作台并初始化所有资源。

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

async stop() None[源代码]#

停止工作台并释放所有资源。

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

pydantic model TextResultContent[源代码]#

基类:BaseModel

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

Show JSON schema
{
   "title": "TextResultContent",
   "description": "\u5de5\u5177\u6267\u884c\u7ed3\u679c\u7684\u6587\u672c\u5185\u5bb9\u3002",
   "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'])

field content: str [Required]#

结果的文本内容。

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

基类:Protocol

args_type() Type[BaseModel][源代码]#
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[源代码]#
async run_json(args: Mapping[str, Any], cancellation_token: CancellationToken) Any[源代码]#
async save_state_json() Mapping[str, Any][源代码]#
property schema: ToolSchema#
state_type() Type[BaseModel] | None[源代码]#
pydantic model ToolResult[源代码]#

基类:BaseModel

工作台中工具执行的结果。

Show JSON schema
{
   "title": "ToolResult",
   "description": "\u5de5\u4f5c\u53f0\u4e2d\u5de5\u5177\u6267\u884c\u7684\u7ed3\u679c\u3002",
   "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": "\u5de5\u5177\u6267\u884c\u7ed3\u679c\u7684\u56fe\u50cf\u5185\u5bb9\u3002",
         "properties": {
            "type": {
               "const": "ImageResultContent",
               "default": "ImageResultContent",
               "title": "Type",
               "type": "string"
            },
            "content": {
               "title": "Content"
            }
         },
         "required": [
            "content"
         ],
         "title": "ImageResultContent",
         "type": "object"
      },
      "TextResultContent": {
         "description": "\u5de5\u5177\u6267\u884c\u7ed3\u679c\u7684\u6587\u672c\u5185\u5bb9\u3002",
         "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 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[源代码]#

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

参数:

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

Returns:

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

class ToolSchema[源代码]#

基类:TypedDict

description: NotRequired[str]#
name: str#
parameters: NotRequired[ParametersSchema]#
strict: NotRequired[bool]#
class Workbench[源代码]#

基类:ABC, ComponentBase[BaseModel]

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

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

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

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

调用工作台中的工具。

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

  • arguments (Mapping[str, Any] | None) -- 传递给工具的参数。 如果为None,工具将在无参数情况下被调用。

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

Returns:

ToolResult -- 工具执行的结果。

component_type: ClassVar[ComponentType] = 'workbench'#

组件的逻辑类型。

abstract async list_tools() List[ToolSchema][源代码]#

ToolSchema 对象形式列出工作台中当前可用的工具。

工具列表可能是动态的,其内容可能在工具执行后发生变化。

abstract async load_state(state: Mapping[str, Any]) None[源代码]#

加载工作台的状态。

参数:

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

abstract async reset() None[源代码]#

将工作台重置为初始化后的启动状态。

abstract async save_state() Mapping[str, Any][源代码]#

保存工作台的状态。

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

abstract async start() None[源代码]#

启动工作台并初始化所有资源。

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

abstract async stop() None[源代码]#

停止工作台并释放所有资源。

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