组件配置#

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