组件配置#

AutoGen 组件能够以通用方式进行声明式配置。 这是为了支持基于配置的体验(例如 AutoGen Studio),但它对许多其他场景也很有用。

提供此功能的系统称为“组件配置”。 在 AutoGen 中,组件可以简单地理解为可以从配置对象创建,并且本身可以转储到配置对象的东西。 这样,您可以在代码中定义一个组件,然后从中获取配置对象。

该系统是通用的,允许在 AutoGen 外部定义的组件(例如扩展)以相同的方式进行配置。

这与状态有何不同?#

这是需要澄清的非常重要的一点。 当我们谈论序列化对象时,我们必须包含使该对象本身成为其本身的所有数据。 包括消息历史记录等。 当从序列化状态反序列化时,您必须获得完全相同的对象。 组件配置并非如此。

组件配置应被视为对象的蓝图,可以多次盖章以创建同一配置对象的多个实例。

用法#

如果您在 Python 中有一个组件,并且想要获取它的配置,只需调用 dump_component()。 生成的对象可以传递回 load_component() 以获取返回的组件。

从配置加载组件#

要从配置对象加载组件,可以使用 load_component() 方法。 此方法将采用配置对象并返回组件对象。 最好在你想要的接口上调用这个方法。 例如,加载模型客户端

from autogen_core.models import ChatCompletionClient

config = {
    "provider": "openai_chat_completion_client",
    "config": {"model": "gpt-4o"},
}

client = ChatCompletionClient.load_component(config)

创建组件类#

要将组件功能添加到给定类

  1. 在类继承列表中添加对 Component() 的调用。

  2. 实现 _to_config()_from_config() 方法

例如

from autogen_core import Component, ComponentBase
from pydantic import BaseModel


class Config(BaseModel):
    value: str


class MyComponent(ComponentBase[Config], Component[Config]):
    component_type = "custom"
    component_config_schema = Config

    def __init__(self, value: str):
        self.value = value

    def _to_config(self) -> Config:
        return Config(value=self.value)

    @classmethod
    def _from_config(cls, config: Config) -> "MyComponent":
        return cls(value=config.value)

密钥#

如果配置对象的字段是密钥值,则应使用 SecretStr 进行标记,这将确保该值不会被转储到配置对象。

例如

from pydantic import BaseModel, SecretStr


class ClientConfig(BaseModel):
    endpoint: str
    api_key: SecretStr