A programming framework for agentic AI
Add component config support (#4757)
Jack Gerritsdda208f9b45d
diff --git a/python/mypy_plugin.py b/python/mypy_plugin.pynew file mode 100644index 000000000..4e230e732--- /dev/null+++ b/python/mypy_plugin.py@@ -0,0 +1,23 @@+from typing import Callable+from mypy.plugin import Plugin, DynamicClassDefContext, SymbolTableNode+from mypy.nodes import SymbolTableNode++class CustomPlugin(Plugin):+ def get_dynamic_class_hook(+ self, fullname: str+ ) -> Callable[[DynamicClassDefContext], None] | None:++ def hook(ctx: DynamicClassDefContext) -> None:+ if "Component" in fullname:+ # We need to generate mypy.nodes.TypeInfo+ # to make mypy understand the type of the class+ ctx.api.add_symbol_table_node(+ fullname, SymbolTableNode(++ )+ )+ return++def plugin(version: str):+ # ignore version argument if the plugin works with all mypy versions.+ return CustomPlugin\ No newline at end of filediff --git a/python/packages/autogen-core/docs/src/reference/python/autogen_core.rst b/python/packages/autogen-core/docs/src/reference/python/autogen_core.rstindex ee23badec..c3f7bded9 100644--- a/python/packages/autogen-core/docs/src/reference/python/autogen_core.rst+++ b/python/packages/autogen-core/docs/src/reference/python/autogen_core.rst@@ -1,8 +1,11 @@autogen\_core=============-.. automodule:: autogen_core:members::undoc-members::show-inheritance:+ :member-order: bysource++.. For some reason the following isn't picked up by automodule above+.. autoclass:: autogen_core.ComponentType\ No newline at end of filediff --git a/python/packages/autogen-core/docs/src/user-guide/core-user-guide/framework/component-config.ipynb b/python/packages/autogen-core/docs/src/user-guide/core-user-guide/framework/component-config.ipynbnew file mode 100644index 000000000..a3f7efa64--- /dev/null+++ b/python/packages/autogen-core/docs/src/user-guide/core-user-guide/framework/component-config.ipynb@@ -0,0 +1,114 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# Component config\n",+ "\n",+ "AutoGen components are able to be declaratively configured in a generic fashion. This is to support configuration based experiences, such as AutoGen studio, but it is also useful for many other scenarios.\n",+ "\n",+ "The system that provides this is called \"component configuration\". In AutoGen, a component is simply something that can be created from a config object and itself can be dumped to a config object. In this way, you can define a component in code and then get the config object from it.\n",+ "\n",+ "This system is generic and allows for components defined outside of AutoGen itself (such as extensions) to be configured in the same way.\n",+ "\n",+ "## How does this differ from state?\n",+ "\n",+ "This is a very important point to clarify. When we talk about serializing an object, we must include *all* data that makes that object itself. Including things like message history etc. When deserializing from serialized state, you must get back the *exact* same object. This is not the case with component configuration.\n",+ "\n",+ "Component configuration should be thought of as the blueprint for an object, and can be stamped out many times to create many instances of the same configured object.\n",+ "\n",+ "## Usage\n",+ "\n",+ "If you have a component in Python ad want to get the config for it, simply call {py:meth}`~autogen_core.ComponentConfig.dump_component` on it. The resulting object can be passed back into {py:meth}`~autogen_core.ComponentLoader.load_component` to get the component back.\n",+ "\n",+ "## Creating a component\n",+ "\n",+ "To add component functionality to a given class:\n",+ "\n",+ "1. Add a call to {py:meth}`~autogen_core.Component` in the class inheritance list.\n",+ "2. Implment the {py:meth}`~autogen_core.ComponentConfigImpl._to_config` and {py:meth}`~autogen_core.ComponentConfigImpl._from_config` methods\n",+ "\n",+ "For example:"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "from __future__ import annotations\n",+ "\n",+ "from autogen_core import Component\n",+ "from pydantic import BaseModel\n",+ "\n",+ "\n",+ "class Config(BaseModel):\n",+ " value: str\n",+ "\n",+ "\n",+ "class MyComponent(Component[Config]):\n",+ " component_type = \"custom\"\n",+ " config_schema = Config\n",+ "\n",+ " def __init__(self, value: str):\n",+ " self.value = value\n",+ "\n",+ " def _to_config(self) -> Config:\n",+ " return Config(value=self.value)\n",+ "\n",+ " @classmethod\n",+ " def _from_config(cls, config: Config) -> MyComponent:\n",+ " return cls(value=config.value)"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "\n",+ "## Secrets\n",+ "\n",+ "If a field of a config object is a secret value, it should be marked using [`SecretStr`](https://docs.pydantic.dev/latest/api/types/#pydantic.types.SecretStr), this will ensure that the value will not be dumped to the config object.\n",+ "\n",+ "For example:\n"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 1,+ "metadata": {},+ "outputs": [],+ "source": [+ "from pydantic import BaseModel, SecretStr\n",+ "\n",+ "\n",+ "class ClientConfig(BaseModel):\n",+ " endpoint: str\n",+ " api_key: SecretStr"+ ]+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": ".venv",+ "language": "python",+ "name": "python3"+ },+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3",+ "version": "3.12.7"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 2+}diff --git a/python/packages/autogen-core/docs/src/user-guide/core-user-guide/index.md b/python/packages/autogen-core/docs/src/user-guide/core-user-guide/index.mdindex 6a2f31211..207abd10e 100644--- a/python/packages/autogen-core/docs/src/user-guide/core-user-guide/index.md+++ b/python/packages/autogen-core/docs/src/user-guide/core-user-guide/index.md@@ -40,6 +40,7 @@ framework/loggingframework/telemetryframework/command-line-code-executorsframework/distributed-agent-runtime+framework/component-config``````{toctree}diff --git a/python/packages/autogen-core/src/autogen_core/__init__.py b/python/packages/autogen-core/src/autogen_core/__init__.pyindex 0f085d29b..9523476e4 100644--- a/python/packages/autogen-core/src/autogen_core/__init__.py+++ b/python/packages/autogen-core/src/autogen_core/__init__.py@@ -12,6 +12,13 @@ from ._agent_type import AgentTypefrom ._base_agent import BaseAgentfrom ._cancellation_token import CancellationTokenfrom ._closure_agent import ClosureAgent, ClosureContext+from ._component_config import (+ Component,+ ComponentConfigImpl,+ ComponentLoader,+ ComponentModel,+ ComponentType,+)from ._constants import (EVENT_LOGGER_NAME as EVENT_LOGGER_NAME_ALIAS,)@@ -99,4 +106,9 @@ __all__ = ["ROOT_LOGGER_NAME","EVENT_LOGGER_NAME","TRACE_LOGGER_NAME",+ "Component",+ "ComponentLoader",+ "ComponentConfigImpl",+ "ComponentModel",+ "ComponentType",]diff --git a/python/packages/autogen-core/src/autogen_core/_component_config.py b/python/packages/autogen-core/src/autogen_core/_component_config.pynew file mode 100644index 000000000..6652ea6cd--- /dev/null+++ b/python/packages/autogen-core/src/autogen_core/_component_config.py@@ -0,0 +1,231 @@+from __future__ import annotations++import importlib+import warnings+from typing import Any, ClassVar, Dict, Generic, Literal, Protocol, Type, cast, overload, runtime_checkable++from pydantic import BaseModel+from typing_extensions import Self, TypeVar++ComponentType = Literal["model", "agent", "tool", "termination", "token_provider"] | str+ConfigT = TypeVar("ConfigT", bound=BaseModel)++T = TypeVar("T", bound=BaseModel, covariant=True)+++class ComponentModel(BaseModel):+ """Model class for a component. Contains all information required to instantiate a component."""++ provider: str+ """Describes how the component can be instantiated."""+ component_type: ComponentType+ """Logical type of the component."""+ version: int+ """Version of the component specification."""+ description: str | None+ """Description of the component."""++ config: dict[str, Any]+ """The schema validated config field is passed to a given class's implmentation of :py:meth:`autogen_core.ComponentConfigImpl._from_config` to create a new instance of the component class."""+++def _type_to_provider_str(t: type) -> str:+ return f"{t.__module__}.{t.__qualname__}"+++@runtime_checkable+class ComponentConfigImpl(Protocol[ConfigT]):+ # Ideally would be ClassVar[Type[ConfigT]], but this is disallowed https://github.com/python/typing/discussions/1424 (despite being valid in this context)+ config_schema: Type[ConfigT]+ component_type: ClassVar[ComponentType]++ """The two methods a class must implement to be a component.++ Args:+ Protocol (ConfigT): Type which derives from :py:class:`pydantic.BaseModel`.+ """++ def _to_config(self) -> ConfigT:+ """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.++ :meta public:+ """+ ...++ @classmethod+ def _from_config(cls, config: ConfigT) -> Self:+ """Create a new instance of the component from a configuration object.++ Args:+ config (T): The configuration object.++ Returns:+ Self: The new instance of the component.++ :meta public:+ """+ ...+++ExpectedType = TypeVar("ExpectedType")+++class ComponentLoader:+ @overload+ @classmethod+ def load_component(cls, model: ComponentModel | Dict[str, Any], expected: None = None) -> Self: ...++ @overload+ @classmethod+ def load_component(cls, model: ComponentModel | Dict[str, Any], expected: Type[ExpectedType]) -> ExpectedType: ...++ @classmethod+ def load_component(+ cls, model: ComponentModel | Dict[str, Any], expected: Type[ExpectedType] | None = None+ ) -> Self | ExpectedType:+ """Load a component from a model. Intended to be used with the return type of :py:meth:`autogen_core.ComponentConfig.dump_component`.++ Example:++ .. code-block:: python++ from autogen_core import ComponentModel+ from autogen_core.models import ChatCompletionClient++ component: ComponentModel = ... # type: ignore++ model_client = ChatCompletionClient.load_component(component)++ Args:+ model (ComponentModel): The model to load the component from.++ Returns:+ Self: The loaded component.++ Args:+ model (ComponentModel): _description_+ expected (Type[ExpectedType] | None, optional): Explicit type only if used directly on ComponentLoader. Defaults to None.++ Raises:+ ValueError: If the provider string is invalid.+ TypeError: Provider is not a subclass of ComponentConfigImpl, or the expected type does not match.++ Returns:+ Self | ExpectedType: The loaded component.+ """++ # Use global and add further type checks++ if isinstance(model, dict):+ loaded_model = ComponentModel(**model)+ else:+ loaded_model = model++ output = loaded_model.provider.rsplit(".", maxsplit=1)+ if len(output) != 2:+ raise ValueError("Invalid")++ module_path, class_name = output+ module = importlib.import_module(module_path)+ component_class = cast(ComponentConfigImpl[BaseModel], module.__getattribute__(class_name))++ if not isinstance(component_class, ComponentConfigImpl):+ raise TypeError("Invalid component class")++ # We need to check the schema is valid+ if not hasattr(component_class, "config_schema"):+ raise AttributeError("config_schema not defined")++ if not hasattr(component_class, "component_type"):+ raise AttributeError("component_type not defined")++ schema = component_class.config_schema+ validated_config = schema.model_validate(loaded_model.config)++ # We're allowed to use the private method here+ instance = component_class._from_config(validated_config) # type: ignore++ if expected is None and not isinstance(instance, cls):+ raise TypeError("Expected type does not match")+ elif expected is None:+ return cast(Self, instance)+ elif not isinstance(instance, expected):+ raise TypeError("Expected type does not match")+ else:+ return cast(ExpectedType, instance)+++class Component(ComponentConfigImpl[ConfigT], ComponentLoader, Generic[ConfigT]):+ """To create a component class, inherit from this class. Then implement two class variables:++ - :py:attr:`config_schema` - A Pydantic model class which represents the configuration of the component. This is also the type parameter of Component.+ - :py:attr:`component_type` - What is the logical type of the component.++ Example:++ .. code-block:: python++ from __future__ import annotations++ from pydantic import BaseModel+ from autogen_core import Component+++ class Config(BaseModel):+ value: str+++ class MyComponent(Component[Config]):+ component_type = "custom"+ 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)+ """++ required_class_vars = ["config_schema", "component_type"]++ def __init_subclass__(cls, **kwargs: Any):+ super().__init_subclass__(**kwargs)++ for var in cls.required_class_vars:+ if not hasattr(cls, var):+ warnings.warn(+ f"Class variable '{var}' must be defined in {cls.__name__} to be a valid component", stacklevel=2+ )++ def dump_component(self) -> ComponentModel:+ """Dump the component to a model that can be loaded back in.++ Raises:+ TypeError: If the component is a local class.++ Returns:+ ComponentModel: The model representing the component.+ """+ provider = _type_to_provider_str(self.__class__)++ if "<locals>" in provider:+ raise TypeError("Cannot dump component with local class")++ if not hasattr(self, "component_type"):+ raise AttributeError("component_type not defined")++ obj_config = self._to_config().model_dump()+ return ComponentModel(+ provider=provider,+ component_type=self.component_type,+ version=1,+ description=None,+ config=obj_config,+ )diff --git a/python/packages/autogen-core/src/autogen_core/models/_model_client.py b/python/packages/autogen-core/src/autogen_core/models/_model_client.pyindex c141c480d..0cba5b079 100644--- a/python/packages/autogen-core/src/autogen_core/models/_model_client.py+++ b/python/packages/autogen-core/src/autogen_core/models/_model_client.py@@ -1,17 +1,18 @@from __future__ import annotations-from typing import Mapping, Optional, Sequence, runtime_checkable+from abc import ABC, abstractmethod+from typing import Mapping, Optional, Sequencefrom typing_extensions import (Any,AsyncGenerator,- Protocol,Required,TypedDict,Union,)from .. import CancellationToken+from .._component_config import ComponentLoaderfrom ..tools import Tool, ToolSchemafrom ._types import CreateResult, LLMMessage, RequestUsage@@ -22,9 +23,9 @@ class ModelCapabilities(TypedDict, total=False):json_output: Required[bool]-@runtime_checkable-class ChatCompletionClient(Protocol):+class ChatCompletionClient(ABC, ComponentLoader):# Caching has to be handled internally as they can depend on the create args that were stored in the constructor+ @abstractmethodasync def create(self,messages: Sequence[LLMMessage],@@ -36,6 +37,7 @@ class ChatCompletionClient(Protocol):cancellation_token: Optional[CancellationToken] = None,) -> CreateResult: ...+ @abstractmethoddef create_stream(self,messages: Sequence[LLMMessage],@@ -47,13 +49,18 @@ class ChatCompletionClient(Protocol):cancellation_token: Optional[CancellationToken] = None,) -> AsyncGenerator[Union[str, CreateResult], None]: ...+ @abstractmethoddef actual_usage(self) -> RequestUsage: ...+ @abstractmethoddef total_usage(self) -> RequestUsage: ...+ @abstractmethoddef count_tokens(self, messages: Sequence[LLMMessage], tools: Sequence[Tool | ToolSchema] = []) -> int: ...+ @abstractmethoddef remaining_tokens(self, messages: Sequence[LLMMessage], tools: Sequence[Tool | ToolSchema] = []) -> int: ...@property+ @abstractmethoddef capabilities(self) -> ModelCapabilities: ...diff --git a/python/packages/autogen-core/tests/test_component_config.py b/python/packages/autogen-core/tests/test_component_config.pynew file mode 100644index 000000000..6c0df593f--- /dev/null+++ b/python/packages/autogen-core/tests/test_component_config.py@@ -0,0 +1,176 @@+from __future__ import annotations++import json++import pytest+from autogen_core import Component, ComponentLoader, ComponentModel+from autogen_core._component_config import _type_to_provider_str # type: ignore+from autogen_core.models import ChatCompletionClient+from autogen_test_utils import MyInnerComponent, MyOuterComponent+from pydantic import BaseModel, ValidationError+from typing_extensions import Self+++class MyConfig(BaseModel):+ info: str+++class MyComponent(Component[MyConfig]):+ config_schema = MyConfig+ component_type = "custom"++ def __init__(self, info: str) -> None:+ self.info = info++ def _to_config(self) -> MyConfig:+ return MyConfig(info=self.info)++ @classmethod+ def _from_config(cls, config: MyConfig) -> MyComponent:+ return cls(info=config.info)+++def test_custom_component() -> None:+ comp = MyComponent("test")+ comp2 = MyComponent.load_component(comp.dump_component())+ assert comp.info == comp2.info+ assert comp.__class__ == comp2.__class__+++def test_custom_component_generic_loader() -> None:+ comp = MyComponent("test")+ comp2 = ComponentLoader.load_component(comp.dump_component(), MyComponent)+ assert comp.info == comp2.info+ assert comp.__class__ == comp2.__class__+++def test_custom_component_json() -> None:+ comp = MyComponent("test")+ json_str = comp.dump_component().model_dump_json()+ comp2 = MyComponent.load_component(json.loads(json_str))+ assert comp.info == comp2.info+ assert comp.__class__ == comp2.__class__+++def test_custom_component_generic_loader_json() -> None:+ comp = MyComponent("test")+ json_str = comp.dump_component().model_dump_json()+ comp2 = ComponentLoader.load_component(json.loads(json_str), MyComponent)+ assert comp.info == comp2.info+ assert comp.__class__ == comp2.__class__+++def test_custom_component_incorrect_class() -> None:+ comp = MyComponent("test")++ with pytest.raises(TypeError):+ _ = ComponentLoader.load_component(comp.dump_component(), str)+++def test_nested_component_diff_module() -> None:+ inner_class = MyInnerComponent("inner")+ comp = MyOuterComponent("test", inner_class)+ dumped = comp.dump_component()+ comp2 = MyOuterComponent.load_component(dumped)+ assert comp.__class__ == comp2.__class__+ assert comp.outer_message == comp2.outer_message+ assert comp.inner_class.inner_message == comp2.inner_class.inner_message+ assert comp.inner_class.__class__ == comp2.inner_class.__class__+++def test_nested_component_diff_module_json() -> None:+ inner_class = MyInnerComponent("inner")+ comp = MyOuterComponent("test", inner_class)+ dumped = comp.dump_component()+ json_str = dumped.model_dump_json()+ comp2 = MyOuterComponent.load_component(json.loads(json_str))+ assert comp.__class__ == comp2.__class__+ assert comp.outer_message == comp2.outer_message+ assert comp.inner_class.inner_message == comp2.inner_class.inner_message+ assert comp.inner_class.__class__ == comp2.inner_class.__class__+++def test_cannot_import_locals() -> None:+ class InvalidModelClientConfig(BaseModel):+ info: str++ class MyInvalidModelClient(Component[InvalidModelClientConfig]):+ config_schema = InvalidModelClientConfig+ component_type = "model"++ def __init__(self, info: str):+ self.info = info++ def _to_config(self) -> InvalidModelClientConfig:+ return InvalidModelClientConfig(info=self.info)++ @classmethod+ def _from_config(cls, config: InvalidModelClientConfig) -> Self:+ return cls(info=config.info)++ comp = MyInvalidModelClient("test")+ with pytest.raises(TypeError):+ # Fails due to the class not being importable+ ChatCompletionClient.load_component(comp.dump_component())+++class InvalidModelClientConfig(BaseModel):+ info: str+++class MyInvalidModelClient(Component[InvalidModelClientConfig]):+ config_schema = InvalidModelClientConfig+ component_type = "model"++ def __init__(self, info: str) -> None:+ self.info = info++ def _to_config(self) -> InvalidModelClientConfig:+ return InvalidModelClientConfig(info=self.info)++ @classmethod+ def _from_config(cls, config: InvalidModelClientConfig) -> Self:+ return cls(info=config.info)+++def test_type_error_on_creation() -> None:+ comp = MyInvalidModelClient("test")+ # Fails due to MyInvalidModelClient not being a model client+ with pytest.raises(TypeError):+ ChatCompletionClient.load_component(comp.dump_component())+++with pytest.warns(UserWarning):++ class MyInvalidMissingAttrs(Component[InvalidModelClientConfig]):+ def __init__(self, info: str):+ self.info = info++ def _to_config(self) -> InvalidModelClientConfig:+ return InvalidModelClientConfig(info=self.info)++ @classmethod+ def _from_config(cls, config: InvalidModelClientConfig) -> Self:+ return cls(info=config.info)+++def test_fails_to_save_on_missing_attributes() -> None:+ comp = MyInvalidMissingAttrs("test") # type: ignore+ with pytest.raises(AttributeError):+ comp.dump_component()+++def test_schema_validation_fails_on_bad_config() -> None:+ class OtherConfig(BaseModel):+ other: str++ config = OtherConfig(other="test").model_dump()+ model = ComponentModel(+ provider=_type_to_provider_str(MyComponent),+ component_type=MyComponent.component_type,+ version=1,+ description=None,+ config=config,+ )+ with pytest.raises(ValidationError):+ _ = MyComponent.load_component(model)diff --git a/python/packages/autogen-ext/src/autogen_ext/models/openai/_azure_token_provider.py b/python/packages/autogen-ext/src/autogen_ext/models/openai/_azure_token_provider.pynew file mode 100644index 000000000..a3960fbef--- /dev/null+++ b/python/packages/autogen-ext/src/autogen_ext/models/openai/_azure_token_provider.py@@ -0,0 +1,54 @@+from typing import List++from autogen_core import Component+from azure.core.credentials import TokenProvider+from azure.identity import DefaultAzureCredential, get_bearer_token_provider+from pydantic import BaseModel+from typing_extensions import Self+++class TokenProviderConfig(BaseModel):+ provider_kind: str+ scopes: List[str]+++class AzureTokenProvider(Component[TokenProviderConfig]):+ component_type = "token_provider"+ config_schema = TokenProviderConfig++ def __init__(self, credential: TokenProvider, *scopes: str):+ self.credential = credential+ self.scopes = list(scopes)+ self.provider = get_bearer_token_provider(self.credential, *self.scopes)++ def __call__(self) -> str:+ return self.provider()++ def _to_config(self) -> TokenProviderConfig:+ """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.+ """++ if isinstance(self.credential, DefaultAzureCredential):+ # NOTE: we are not currently inspecting the chained credentials, so this could result in a loss of information+ return TokenProviderConfig(provider_kind="DefaultAzureCredential", scopes=self.scopes)+ else:+ raise ValueError("Only DefaultAzureCredential is supported")++ @classmethod+ def _from_config(cls, config: TokenProviderConfig) -> Self:+ """Create a new instance of the component from a configuration object.++ Args:+ config (T): The configuration object.++ Returns:+ Self: The new instance of the component.+ """++ if config.provider_kind == "DefaultAzureCredential":+ return cls(DefaultAzureCredential(), *config.scopes)+ else:+ raise ValueError("Only DefaultAzureCredential is supported")diff --git a/python/packages/autogen-ext/src/autogen_ext/models/openai/_openai_client.py b/python/packages/autogen-ext/src/autogen_ext/models/openai/_openai_client.pyindex baf57628d..1f6115618 100644--- a/python/packages/autogen-ext/src/autogen_ext/models/openai/_openai_client.py+++ b/python/packages/autogen-ext/src/autogen_ext/models/openai/_openai_client.py@@ -25,6 +25,7 @@ from autogen_core import (EVENT_LOGGER_NAME,TRACE_LOGGER_NAME,CancellationToken,+ Component,FunctionCall,Image,)@@ -64,7 +65,9 @@ from openai.types.chat.chat_completion import Choicefrom openai.types.chat.chat_completion_chunk import Choice as ChunkChoicefrom openai.types.shared_params import FunctionDefinition, FunctionParametersfrom pydantic import BaseModel-from typing_extensions import Unpack+from typing_extensions import Self, Unpack++from autogen_ext.models.openai._azure_token_provider import AzureTokenProviderfrom . import _model_infofrom .config import AzureOpenAIClientConfiguration, OpenAIClientConfiguration@@ -971,7 +974,11 @@ class OpenAIChatCompletionClient(BaseOpenAIChatCompletionClient):self._client = _openai_client_from_config(state["_raw_config"])-class AzureOpenAIChatCompletionClient(BaseOpenAIChatCompletionClient):+class ConfigHolder(BaseModel):+ values: Dict[str, Any]+++class AzureOpenAIChatCompletionClient(BaseOpenAIChatCompletionClient, Component[ConfigHolder]):"""Chat completion client for Azure OpenAI hosted models.Args:@@ -1019,6 +1026,9 @@ class AzureOpenAIChatCompletionClient(BaseOpenAIChatCompletionClient):"""+ component_type = "model"+ config_schema = ConfigHolder+def __init__(self, **kwargs: Unpack[AzureOpenAIClientConfiguration]):model_capabilities: Optional[ModelCapabilities] = Nonecopied_args = dict(kwargs).copy()@@ -1039,3 +1049,26 @@ class AzureOpenAIChatCompletionClient(BaseOpenAIChatCompletionClient):def __setstate__(self, state: Dict[str, Any]) -> None:self.__dict__.update(state)self._client = _azure_openai_client_from_config(state["_raw_config"])++ def _to_config(self) -> ConfigHolder:+ copied_config = self._raw_config.copy()++ if "azure_ad_token_provider" in copied_config:+ if not isinstance(copied_config["azure_ad_token_provider"], AzureTokenProvider):+ raise ValueError("azure_ad_token_provider must be a AzureTokenProvider to be component serialized")++ copied_config["azure_ad_token_provider"] = (+ copied_config["azure_ad_token_provider"].dump_component().model_dump()+ )++ return ConfigHolder(values=copied_config)++ @classmethod+ def _from_config(cls, config: ConfigHolder) -> Self:+ copied_config = config.values.copy()+ if "azure_ad_token_provider" in copied_config:+ copied_config["azure_ad_token_provider"] = AzureTokenProvider.load_component(+ copied_config["azure_ad_token_provider"]+ )++ return cls(**copied_config)diff --git a/python/packages/autogen-ext/src/autogen_ext/models/openai/config/__init__.py b/python/packages/autogen-ext/src/autogen_ext/models/openai/config/__init__.pyindex 70671347a..04a366cfe 100644--- a/python/packages/autogen-ext/src/autogen_ext/models/openai/config/__init__.py+++ b/python/packages/autogen-ext/src/autogen_ext/models/openai/config/__init__.py@@ -3,6 +3,8 @@ from typing import Awaitable, Callable, Dict, List, Literal, Optional, Unionfrom autogen_core.models import ModelCapabilitiesfrom typing_extensions import Required, TypedDict+from autogen_ext.models.openai._azure_token_provider import AzureTokenProvider+class ResponseFormat(TypedDict):type: Literal["text", "json_object"]@@ -46,7 +48,7 @@ class AzureOpenAIClientConfiguration(BaseOpenAIClientConfiguration, total=False)azure_deployment: strapi_version: Required[str]azure_ad_token: str- azure_ad_token_provider: AsyncAzureADTokenProvider+ azure_ad_token_provider: AsyncAzureADTokenProvider | AzureTokenProvider__all__ = ["AzureOpenAIClientConfiguration", "OpenAIClientConfiguration"]diff --git a/python/packages/autogen-ext/src/autogen_ext/models/replay/_replay_chat_completion_client.py b/python/packages/autogen-ext/src/autogen_ext/models/replay/_replay_chat_completion_client.pyindex d0cd159a3..5b7ac7095 100644--- a/python/packages/autogen-ext/src/autogen_ext/models/replay/_replay_chat_completion_client.py+++ b/python/packages/autogen-ext/src/autogen_ext/models/replay/_replay_chat_completion_client.py@@ -16,7 +16,7 @@ from autogen_core.tools import Tool, ToolSchemalogger = logging.getLogger(EVENT_LOGGER_NAME)-class ReplayChatCompletionClient:+class ReplayChatCompletionClient(ChatCompletionClient):"""A mock chat completion client that replays predefined responses using an index-based approach.diff --git a/python/packages/autogen-test-utils/src/autogen_test_utils/__init__.py b/python/packages/autogen-test-utils/src/autogen_test_utils/__init__.pyindex f1aeed229..b4f9332b6 100644--- a/python/packages/autogen-test-utils/src/autogen_test_utils/__init__.py+++ b/python/packages/autogen-test-utils/src/autogen_test_utils/__init__.py@@ -1,7 +1,19 @@+from __future__ import annotations+from dataclasses import dataclassfrom typing import Any-from autogen_core import BaseAgent, DefaultTopicId, MessageContext, RoutedAgent, default_subscription, message_handler+from autogen_core import (+ BaseAgent,+ Component,+ DefaultTopicId,+ MessageContext,+ RoutedAgent,+ default_subscription,+ message_handler,+)+from autogen_core._component_config import ComponentModel+from pydantic import BaseModel@dataclass@@ -58,3 +70,45 @@ class NoopAgent(BaseAgent):async def on_message_impl(self, message: Any, ctx: MessageContext) -> Any:raise NotImplementedError+++class MyInnerConfig(BaseModel):+ inner_message: str+++class MyInnerComponent(Component[MyInnerConfig]):+ config_schema = MyInnerConfig+ component_type = "custom"++ def __init__(self, inner_message: str):+ self.inner_message = inner_message++ def _to_config(self) -> MyInnerConfig:+ return MyInnerConfig(inner_message=self.inner_message)++ @classmethod+ def _from_config(cls, config: MyInnerConfig) -> MyInnerComponent:+ return cls(inner_message=config.inner_message)+++class MyOuterConfig(BaseModel):+ outer_message: str+ inner_class: ComponentModel+++class MyOuterComponent(Component[MyOuterConfig]):+ config_schema = MyOuterConfig+ component_type = "custom"++ def __init__(self, outer_message: str, inner_class: MyInnerComponent):+ self.outer_message = outer_message+ self.inner_class = inner_class++ def _to_config(self) -> MyOuterConfig:+ inner_component_config = self.inner_class.dump_component()+ return MyOuterConfig(outer_message=self.outer_message, inner_class=inner_component_config)++ @classmethod+ def _from_config(cls, config: MyOuterConfig) -> MyOuterComponent:+ inner = MyInnerComponent.load_component(config.inner_class)+ return cls(outer_message=config.outer_message, inner_class=inner)