Building AI agents, atomically
fix: resolve schemas through generic agent subclasses (#328)
Kexin Chenea7c09aae6ce
diff --git a/atomic-agents/atomic_agents/agents/atomic_agent.py b/atomic-agents/atomic_agents/agents/atomic_agent.pyindex 2ac9381..1821aa9 100644--- a/atomic-agents/atomic_agents/agents/atomic_agent.py+++ b/atomic-agents/atomic_agents/agents/atomic_agent.py@@ -169,24 +169,6 @@ 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.@@ -238,49 +220,35 @@ class AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:"""self.history.add_message(self.tool_result_role, content)- @property- def input_schema(self) -> Type[BaseIOSchema]:- """- Returns the input schema for the agent.+ def _resolve_schema_types(self) -> tuple[Type[BaseIOSchema], Type[BaseIOSchema]]:+ """Resolve AtomicAgent's schemas through the instance's specialized bases."""- 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+ def resolve(base: Any, bindings: Dict[Any, Any]) -> Optional[tuple[Any, Any]]:+ origin = get_origin(base) or base+ arguments = tuple(bindings.get(argument, argument) for argument in get_args(base))+ if origin is AtomicAgent:+ return (arguments[0], arguments[1]) if len(arguments) == 2 else None- # Dynamic instantiation: AtomicAgent[Schema1, Schema2]()- if hasattr(self, "__orig_class__"):- TI, _ = get_args(self.__orig_class__)- return TI+ bindings = {**bindings, **dict(zip(getattr(origin, "__parameters__", ()), arguments))}+ # Read only bases declared on this class; inherited __orig_bases__+ # can skip a specialization introduced by an intermediate subclass.+ for parent in origin.__dict__.get("__orig_bases__", origin.__bases__):+ schemas = resolve(parent, bindings)+ if schemas is not None:+ return schemas+ return None- # No type info available- return BasicChatInputSchema+ return resolve(getattr(self, "__orig_class__", type(self)), {}) or (BasicChatInputSchema, BasicChatOutputSchema)@property- def 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__)- return TO+ def input_schema(self) -> Type[BaseIOSchema]:+ """Return the concrete input schema, or the default for an untyped agent."""+ return self._resolve_schema_types()[0]- # No type info available- return BasicChatOutputSchema+ @property+ def output_schema(self) -> Type[BaseIOSchema]:+ """Return the concrete output schema, or the default for an untyped agent."""+ return self._resolve_schema_types()[1]def _build_system_messages(self) -> List[Dict]:"""diff --git a/atomic-agents/tests/agents/test_generic_agent_schemas.py b/atomic-agents/tests/agents/test_generic_agent_schemas.pynew file mode 100644index 0000000..9e2e76e--- /dev/null+++ b/atomic-agents/tests/agents/test_generic_agent_schemas.py@@ -0,0 +1,161 @@+"""Concrete schema bindings survive reusable generic agent subclasses."""++import json++import httpx+import instructor+import openai+import pytest++from atomic_agents import AgentConfig, AtomicAgent, BaseIOSchema, BasicChatInputSchema, BasicChatOutputSchema+++class StageInput(BaseIOSchema):+ """Input to a composed stage."""++ text: str+++class FirstOutput(BaseIOSchema):+ """Output from the first stage."""++ answer: str+++class SecondOutput(BaseIOSchema):+ """Output from the second stage."""++ answer: str+++class ConcreteAgent(AtomicAgent[StageInput, FirstOutput]):+ def __init__(self, config):+ super().__init__(config)+++class ConcreteChild(ConcreteAgent):+ pass+++class OutputTemplate[T: BaseIOSchema](AtomicAgent[StageInput, T]):+ def __init__(self, config):+ super().__init__(config)+++class TwoSchemaTemplate[I: BaseIOSchema, O: BaseIOSchema](AtomicAgent[I, O]):+ pass+++class ReorderedTemplate[O: BaseIOSchema, I: BaseIOSchema](AtomicAgent[I, O]):+ pass+++class ForwardTemplate[T: BaseIOSchema](OutputTemplate[T]):+ pass+++class FinalAgent(ForwardTemplate[FirstOutput]):+ pass+++class UntypedAgent(AtomicAgent):+ pass+++def offline_client():+ requests = []++ def respond(request):+ body = json.loads(request.content)+ function = body["tools"][0]["function"]+ assert function["name"] in {"FirstOutput", "SecondOutput"}+ assert set(function["parameters"]["properties"]) == {"answer"}+ requests.append(body)+ return httpx.Response(+ 200,+ json={+ "id": "schema-binding-test",+ "object": "chat.completion",+ "created": 0,+ "model": "offline-fixture",+ "choices": [+ {+ "index": 0,+ "finish_reason": "tool_calls",+ "message": {+ "role": "assistant",+ "content": None,+ "tool_calls": [+ {+ "id": "call_test",+ "type": "function",+ "function": {+ "name": function["name"],+ "arguments": json.dumps({"answer": "literal fixture result"}),+ },+ }+ ],+ },+ }+ ],+ },+ )++ with openai.OpenAI(+ api_key="test-placeholder",+ base_url="http://localhost/v1",+ max_retries=0,+ http_client=httpx.Client(transport=httpx.MockTransport(respond)),+ ) as provider:+ yield instructor.from_openai(provider), requests+++ "factory, expected_output",+ [+ pytest.param(AtomicAgent[StageInput, FirstOutput], FirstOutput, id="direct"),+ pytest.param(ConcreteAgent, FirstOutput, id="concrete-custom-constructor"),+ pytest.param(ConcreteChild, FirstOutput, id="concrete-descendant"),+ pytest.param(OutputTemplate[FirstOutput], FirstOutput, id="single-output-parameter"),+ pytest.param(OutputTemplate[SecondOutput], SecondOutput, id="other-output-specialization"),+ pytest.param(TwoSchemaTemplate[StageInput, FirstOutput], FirstOutput, id="two-parameters"),+ pytest.param(ReorderedTemplate[FirstOutput, StageInput], FirstOutput, id="reordered-parameters"),+ pytest.param(ForwardTemplate[FirstOutput], FirstOutput, id="forwarded-parameter"),+ pytest.param(FinalAgent, FirstOutput, id="concrete-template-descendant"),+ ],+)+def test_specialized_agents_use_concrete_schemas(offline_client, factory, expected_output):+ client, requests = offline_client+ agent = factory(AgentConfig(client=client, model="offline-fixture"))++ assert agent.input_schema is StageInput+ assert agent.output_schema is expected_output+ result = agent.run(StageInput(text="ordinary stage input"))++ assert isinstance(result, expected_output)+ assert result.answer == "literal fixture result"+ assert len(requests) == 1+ assert agent.history.history[-1].content is result+++def test_specializations_keep_their_own_bindings(offline_client):+ client, _ = offline_client+ config = AgentConfig(client=client)+ first = OutputTemplate[FirstOutput](config)+ second = OutputTemplate[SecondOutput](config)++ assert first.output_schema is FirstOutput+ assert second.output_schema is SecondOutput+ assert first.output_schema is FirstOutput+ assert FinalAgent(config).output_schema is FirstOutput+ assert second.output_schema is SecondOutput++[email protected]("factory", [AtomicAgent, UntypedAgent])+def test_untyped_agents_keep_default_schemas(offline_client, factory):+ client, _ = offline_client+ agent = factory(AgentConfig(client=client))++ assert agent.input_schema is BasicChatInputSchema+ assert agent.output_schema is BasicChatOutputSchema