Building AI agents, atomically
Fix generic type parameters lost during subclassing
KennyVaneetvelde51020c80e1fe
diff --git a/atomic-agents/atomic_agents/agents/atomic_agent.py b/atomic-agents/atomic_agents/agents/atomic_agent.pyindex 74e0dd7..a8782da 100644--- a/atomic-agents/atomic_agents/agents/atomic_agent.py+++ b/atomic-agents/atomic_agents/agents/atomic_agent.py@@ -1,6 +1,6 @@import instructorfrom pydantic import BaseModel, Field-from typing import Optional, Type, Generator, AsyncGenerator, get_args, Dict, List, Callable+from typing import Optional, Type, Generator, AsyncGenerator, get_args, get_origin, Dict, List, Callableimport loggingfrom atomic_agents.context.chat_history import ChatHistoryfrom atomic_agents.context.system_prompt_generator import (@@ -129,6 +129,24 @@ class AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:```"""+ @classmethod+ def __init_subclass__(cls, **kwargs):+ """+ Hook called when a class is subclassed.++ Captures generic type parameters during class creation and stores them as class attributes+ to work around the unreliable __orig_class__ attribute in modern Python generic syntax.+ """+ super().__init_subclass__(**kwargs)+ if hasattr(cls, "__orig_bases__"):+ for base in cls.__orig_bases__:+ if get_origin(base) is AtomicAgent:+ args = get_args(base)+ if len(args) == 2:+ cls._input_schema_cls = args[0]+ cls._output_schema_cls = args[1]+ break+def __init__(self, config: AgentConfig):"""Initializes the AtomicAgent.@@ -157,21 +175,47 @@ class AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:@propertydef input_schema(self) -> Type[BaseIOSchema]:+ """+ Returns the input schema for the agent.++ Uses a three-level fallback mechanism:+ 1. Class attributes from __init_subclass__ (handles subclassing)+ 2. Instance __orig_class__ (handles direct instantiation)+ 3. Default schema (handles untyped usage)+ """+ # Inheritance pattern: MyAgent(AtomicAgent[Schema1, Schema2])+ if hasattr(self.__class__, "_input_schema_cls"):+ return self.__class__._input_schema_cls++ # Dynamic instantiation: AtomicAgent[Schema1, Schema2]()if hasattr(self, "__orig_class__"):TI, _ = get_args(self.__orig_class__)- else:- TI = BasicChatInputSchema+ return TI- return TI+ # No type info available+ return BasicChatInputSchema@propertydef output_schema(self) -> Type[BaseIOSchema]:+ """+ Returns the output schema for the agent.++ Uses a three-level fallback mechanism:+ 1. Class attributes from __init_subclass__ (handles subclassing)+ 2. Instance __orig_class__ (handles direct instantiation)+ 3. Default schema (handles untyped usage)+ """+ # Inheritance pattern: MyAgent(AtomicAgent[Schema1, Schema2])+ if hasattr(self.__class__, "_output_schema_cls"):+ return self.__class__._output_schema_cls++ # Dynamic instantiation: AtomicAgent[Schema1, Schema2]()if hasattr(self, "__orig_class__"):_, TO = get_args(self.__orig_class__)- else:- TO = BasicChatOutputSchema+ return TO- return TO+ # No type info available+ return BasicChatOutputSchemadef _prepare_messages(self):if self.system_role is None:diff --git a/atomic-agents/tests/agents/test_atomic_agent.py b/atomic-agents/tests/agents/test_atomic_agent.pyindex 69f9e1f..c526d47 100644--- a/atomic-agents/tests/agents/test_atomic_agent.py+++ b/atomic-agents/tests/agents/test_atomic_agent.py@@ -242,6 +242,32 @@ def test_custom_input_output_schemas(mock_instructor):assert custom_agent.output_schema == CustomOutputSchema+def test_subclass_with_custom_constructor(mock_instructor):+ """Test that generic types are preserved in subclasses with custom constructors."""++ class CustomInputSchema(BaseModel):+ custom_field: str++ class CustomOutputSchema(BaseModel):+ result: str++ class MyAgent(AtomicAgent[CustomInputSchema, CustomOutputSchema]):+ def __init__(self, extra_param: str):+ self.extra_param = extra_param+ config = AgentConfig(+ client=mock_instructor,+ model="gpt-4o-mini",+ )+ super().__init__(config)++ agent = MyAgent("test_value")++ # These would fail without the __init_subclass__ fix+ assert agent.input_schema == CustomInputSchema+ assert agent.output_schema == CustomOutputSchema+ assert agent.extra_param == "test_value"++def test_base_agent_io_str_and_rich():class TestIO(BaseIOSchema):"""TestIO docstring"""