Building AI agents, atomically
Patterns & Conventions
Last Updated: 2026-10-24
Atomicity
Build with small, single-purpose, composable parts ("LEGO blocks"): each agent, tool, and context
provider does one thing and is reusable. Compose pipelines by feeding one agent's output schema into
the next's input. See atomic-examples/deep-research and orchestration-agent.
Schema-driven I/O
- Every input and output is a
BaseIOSchema(Pydantic) subclass with a required docstring (used as the LLM-facing description). Naming:<Thing>InputSchema/<Thing>OutputSchema. - Agents are parameterized by schemas via PEP 695 generics:
AtomicAgent[InputSchema, OutputSchema]. - Fully specialized generic agent subclasses resolve their concrete schemas through intermediate bases per instance. Different specializations keep independent input/output bindings; untyped agents retain the basic chat defaults.
- Structured output is enforced by Instructor through
response_model=OutputSchema. - Streaming completion accepts field names when reconstructing output schemas with aliases.
- Tool messages use Pydantic JSON-mode serialization, including JSON-only field serializers.
- MCP dictionary schemas preserve mapping values and validate typed
additionalProperties, including mappings reached through$defsordefinitionsreferences.
Dynamic system prompts (context providers)
SystemPromptGenerator(background=[...], steps=[...], output_instructions=[...], context_providers={...}).- A
BaseDynamicContextProviderinjects live data (retrieved docs, current date, search results) into the system prompt at call time. Register viaagent.register_context_provider(name, provider).
Tools
- A tool is a
BaseTool[InputSchema, OutputSchema]with arun(params) -> OutputSchemamethod and an optionalBaseToolConfig(overridetitle/descriptionto disambiguate similar tools). - Forge tool layout (
atomic-forge/guides/tool_structure.md): imports → input schema → output schema(s) → config → tool class + logic → example usage.
Memory
BaseChatHistory(context/base_chat_history.py) is an interface-only ABC declaring the memory contractAtomicAgentrelies on (add_message,get_history, turn handling,dump()/load(),copy(), plus thehistory/current_turn_idattributes). It is the documented, dependency-free seam for plugging in custom/persistent backends;AgentConfig.historyis typed to it.ChatHistoryis the built-in implementation: stores typedMessages grouped into turns (a user+assistant pair shares aturn_id), is multimodal-aware (Image/Audio/PDF plusVideoURL), and supportsdump()/load().VideoURLis converted to an OpenAI-compatiblevideo_urlcontent part for provider messages.AtomicAgenttrims the oldest whole turns to honormax_context_tokens, using a text placeholder when LiteLLM cannot count video parts.- Invalid serialized history is validated before replacing existing state. Context trimming includes the incoming message in the token budget.
- Custom backend pattern: subclass
ChatHistoryand overrideadd_message/loadto persist (see thepersistent-memoryexample and the "Writing a Custom Memory Backend" guide section).
Error handling & retries
- Lean on Instructor's validation/retry of structured outputs, plus hook events (
parse:error, …) for observability. Seedocs/guides/error-handling.mdanddocs/guides/hooks.md.
Testing
pytest(+pytest-asynciofor async,pytest-covfor coverage), withunittest.mockfor LLM clients. Core tests inatomic-agents/tests/mirror the package layout (agents/,base/,context/,connectors/mcp/,utils/), includingtests/base/test_multimodal.pyforVideoURL. Discovery (pytest.ini): filestest_*.py, classesTest*, functionstest_*.- Instructor transport regressions use real clients with
httpx.MockTransport, including sync/async streaming and explicit strict validation. - MCP tests use real SDK result models with mocked transport/session boundaries. Synthetic execution against production filenames is not used to increase coverage.
Configuration
- Use explicit
Field(default=...)for public config defaults so static type checkers infer optional constructor arguments. The AgentConfig constructor regression covers direct calls and typed settings unpacking. - Omitted
BaseTool,BaseResource, andBasePromptconfigurations are created per instance. Explicitly supplied configuration objects retain their identity. - Runtime config is explicit via
AgentConfig(client, model, history, roles, mode,model_api_parameters,max_context_tokens) — no global state. Secrets (API keys) come from the environment /.env.