Building AI agents, atomically
Address PR review: fix copy() footgun for custom memory backends
Eigenwise5bf82b30e172
diff --git a/atomic-agents/atomic_agents/agents/atomic_agent.py b/atomic-agents/atomic_agents/agents/atomic_agent.pyindex 0c151e3..d2ccfe6 100644--- a/atomic-agents/atomic_agents/agents/atomic_agent.py+++ b/atomic-agents/atomic_agents/agents/atomic_agent.py@@ -190,7 +190,7 @@ class AtomicAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:"""self.client = config.clientself.model = config.model- self.history = config.history or ChatHistory()+ self.history = config.history if config.history is not None else ChatHistory()self.system_prompt_generator = config.system_prompt_generator or SystemPromptGenerator()self.system_role = config.system_roleself.assistant_role = config.assistant_rolediff --git a/atomic-agents/atomic_agents/context/base_chat_history.py b/atomic-agents/atomic_agents/context/base_chat_history.pyindex 9754d90..359c5cf 100644--- a/atomic-agents/atomic_agents/context/base_chat_history.py+++ b/atomic-agents/atomic_agents/context/base_chat_history.py@@ -9,7 +9,14 @@ if TYPE_CHECKING:class BaseChatHistory(ABC):"""- Declares the memory/history contract that ``AtomicAgent`` depends on.+ Declares the public contract of a chat history.++ This is the full method surface of the built-in ``ChatHistory``, of which ``AtomicAgent``+ itself uses a subset (``add_message``, ``get_history``, ``initialize_turn``,+ ``delete_turn_id``, ``copy``, plus direct reads of the ``history`` / ``current_turn_id``+ attributes). The remaining methods (``dump`` / ``load`` / ``get_message_count`` /+ ``get_current_turn_id``) round out the standard history surface that tooling and callers+ rely on.This is an interface-only abstract base class: it defines no state and no behavior,only the methods a chat history implementation must provide. ``ChatHistory`` is the@@ -132,6 +139,13 @@ class BaseChatHistory(ABC):"""Creates a copy of the chat history, independent of the original.+ ``AtomicAgent`` calls ``copy()`` to snapshot ``initial_history`` at construction and+ to restore it in ``reset_history()``. The built-in ``ChatHistory.copy()`` returns a+ plain ``ChatHistory``; a subclass that carries extra state (a database handle, a+ ``session_id``, a store reference) MUST override ``copy()`` to return its own type,+ otherwise ``reset_history()`` silently replaces the backend with a plain in-memory+ history and later writes stop reaching the store.+Returns:BaseChatHistory: A copy of the chat history."""diff --git a/atomic-agents/tests/context/test_base_chat_history.py b/atomic-agents/tests/context/test_base_chat_history.pyindex fb1673c..358b8e1 100644--- a/atomic-agents/tests/context/test_base_chat_history.py+++ b/atomic-agents/tests/context/test_base_chat_history.py@@ -11,7 +11,7 @@ from atomic_agents import (BasicChatInputSchema,BasicChatOutputSchema,)-from atomic_agents.context import BaseChatHistory, ChatHistory, SystemPromptGenerator+from atomic_agents.context import BaseChatHistory, ChatHistory, Message, SystemPromptGeneratorclass InputSchema(BaseIOSchema):@@ -103,3 +103,136 @@ def test_custom_chat_history_subclass_used_by_agent(mock_instructor):# One call for the user message, one for the assistant response.assert custom_history.recorded_calls == 2assert custom_history.get_message_count() == 2+++class MinimalHistory(BaseChatHistory):+ """A from-scratch BaseChatHistory implementation that does NOT subclass ChatHistory.++ Exercises the "own everything" path the docs describe, to prove a backend built purely+ against the ABC drives AtomicAgent end to end.+ """++ def __init__(self, max_messages=None):+ self.history = []+ self.current_turn_id = None+ self.max_messages = max_messages++ def initialize_turn(self):+ self.current_turn_id = "turn"++ def add_message(self, role, content):+ if self.current_turn_id is None:+ self.initialize_turn()+ self.history.append(Message(role=role, content=content, turn_id=self.current_turn_id))++ def get_history(self):+ return [{"role": m.role, "content": m.content.model_dump_json()} for m in self.history]++ def get_current_turn_id(self):+ return self.current_turn_id++ def delete_turn_id(self, turn_id):+ self.history = [m for m in self.history if m.turn_id != turn_id]++ def get_message_count(self):+ return len(self.history)++ def dump(self):+ return "{}"++ def load(self, serialized_data):+ pass++ def copy(self):+ new = MinimalHistory(max_messages=self.max_messages)+ new.history = list(self.history)+ new.current_turn_id = self.current_turn_id+ return new+++def test_from_scratch_base_history_drives_agent(mock_instructor):+ history = MinimalHistory()+ config = AgentConfig(+ client=mock_instructor,+ model="gpt-5-mini",+ history=history,+ system_prompt_generator=SystemPromptGenerator(),+ )+ agent = AtomicAgent[BasicChatInputSchema, BasicChatOutputSchema](config)++ assert isinstance(agent.history, MinimalHistory)++ result = agent.run(BasicChatInputSchema(chat_message="Hello"))++ assert result.chat_message == "Test output"+ assert agent.history.get_message_count() == 2+++class StatefulHistory(ChatHistory):+ """A ChatHistory subclass carrying extra state, with copy() overridden to preserve it."""++ def __init__(self, marker, max_messages=None):+ super().__init__(max_messages=max_messages)+ self.marker = marker++ def copy(self):+ new = StatefulHistory(self.marker, max_messages=self.max_messages)+ new.load(self.dump())+ new.current_turn_id = self.current_turn_id+ return new+++def test_reset_history_preserves_backend_when_copy_overridden(mock_instructor):+ history = StatefulHistory(marker="db-handle")+ config = AgentConfig(+ client=mock_instructor,+ model="gpt-5-mini",+ history=history,+ system_prompt_generator=SystemPromptGenerator(),+ )+ agent = AtomicAgent[BasicChatInputSchema, BasicChatOutputSchema](config)++ # The initial_history snapshot keeps the subclass type and its state.+ assert isinstance(agent.initial_history, StatefulHistory)+ assert agent.initial_history.marker == "db-handle"++ agent.run(BasicChatInputSchema(chat_message="Hi"))+ agent.reset_history()++ # After reset, the backend is still the custom type, not a plain ChatHistory.+ assert isinstance(agent.history, StatefulHistory)+ assert agent.history.marker == "db-handle"+++def test_subclass_without_copy_override_downgrades_to_chat_history():+ """Pins the known sharp edge: an un-overridden copy() returns a plain ChatHistory.++ This is exactly why subclasses carrying extra state must override copy(); documented in+ the Memory guide and warned about in BaseChatHistory.copy's docstring.+ """++ class NaiveHistory(ChatHistory):+ pass++ copied = NaiveHistory().copy()+ assert type(copied) is ChatHistory+++def test_falsy_custom_history_is_not_discarded(mock_instructor):+ """AgentConfig must keep a provided history even if it is falsy (e.g. defines __len__)."""++ class FalsyWhenEmpty(ChatHistory):+ def __len__(self):+ return self.get_message_count()++ history = FalsyWhenEmpty()+ assert not history # empty -> falsy via __len__+ config = AgentConfig(+ client=mock_instructor,+ model="gpt-5-mini",+ history=history,+ system_prompt_generator=SystemPromptGenerator(),+ )+ agent = AtomicAgent[BasicChatInputSchema, BasicChatOutputSchema](config)++ assert agent.history is historydiff --git a/atomic-examples/persistent-memory/persistent_memory/main.py b/atomic-examples/persistent-memory/persistent_memory/main.pyindex fec4515..648b57f 100644--- a/atomic-examples/persistent-memory/persistent_memory/main.py+++ b/atomic-examples/persistent-memory/persistent_memory/main.py@@ -11,6 +11,7 @@ override ``add_message`` to persist on every write.Run this script twice: the second run rehydrates the conversation from the first."""+import contextlibimport osimport sqlite3from typing import Optional@@ -38,18 +39,28 @@ if not API_KEY:class SQLiteChatHistory(ChatHistory):- """A ChatHistory that persists to a local SQLite database, keyed by session_id."""+ """A ChatHistory that persists to a local SQLite database, keyed by session_id.++ Follows the recommended pattern from the Memory guide: subclass ChatHistory to inherit+ turn handling and serialization, then override add_message to persist. copy() is also+ overridden so the agent's initial_history snapshot and reset_history() keep this+ persistent backend instead of silently degrading to a plain in-memory ChatHistory.++ A short-lived connection is opened per operation (via contextlib.closing) rather than+ held open for the object's lifetime, so no handle is leaked and the backend is safe to+ use from more than one thread.+ """def __init__(self, session_id: str, db_path: str = "chat_history.db", max_messages: Optional[int] = None):super().__init__(max_messages=max_messages)self.session_id = session_idself.db_path = db_path- self._connection = sqlite3.connect(self.db_path)- self._connection.execute("CREATE TABLE IF NOT EXISTS sessions (session_id TEXT PRIMARY KEY, data TEXT)")- self._connection.commit()+ with contextlib.closing(sqlite3.connect(self.db_path)) as conn:+ conn.execute("CREATE TABLE IF NOT EXISTS sessions (session_id TEXT PRIMARY KEY, data TEXT)")+ conn.commit()+ row = conn.execute("SELECT data FROM sessions WHERE session_id = ?", (self.session_id,)).fetchone()- row = self._connection.execute("SELECT data FROM sessions WHERE session_id = ?", (self.session_id,)).fetchone()if row is not None:self.load(row[0])@@ -58,11 +69,18 @@ class SQLiteChatHistory(ChatHistory):self._save()def _save(self) -> None:- self._connection.execute(- "INSERT OR REPLACE INTO sessions (session_id, data) VALUES (?, ?)",- (self.session_id, self.dump()),- )- self._connection.commit()+ with contextlib.closing(sqlite3.connect(self.db_path)) as conn:+ conn.execute(+ "INSERT OR REPLACE INTO sessions (session_id, data) VALUES (?, ?)",+ (self.session_id, self.dump()),+ )+ conn.commit()++ def copy(self) -> "SQLiteChatHistory":+ new_history = SQLiteChatHistory(self.session_id, db_path=self.db_path, max_messages=self.max_messages)+ new_history.load(self.dump())+ new_history.current_turn_id = self.current_turn_id+ return new_historydef main() -> None:diff --git a/docs/guides/memory.md b/docs/guides/memory.mdindex ca3d8bc..d0bf563 100644--- a/docs/guides/memory.md+++ b/docs/guides/memory.md@@ -444,9 +444,26 @@ class PersistentHistory(ChatHistory):def add_message(self, role, content):super().add_message(role, content)self.store.put(self.session_id, self.dump())++ def copy(self):+ # AtomicAgent calls copy() for its initial_history snapshot and reset_history().+ # Without this override, copy() returns a plain ChatHistory and your backend is+ # silently dropped after reset_history() (later writes stop reaching the store).+ new_history = PersistentHistory(self.session_id, self.store, max_messages=self.max_messages)+ new_history.load(self.dump())+ new_history.current_turn_id = self.current_turn_id+ return new_history+```++The core of the pattern is small: load on init if there's saved state, persist on every `add_message`. `dump()`/`load()` already round-trip the full history, so there's no serialization logic to write yourself.++```{important}+Override `copy()` too. `AtomicAgent` snapshots `initial_history` with `copy()` at construction and restores it in `reset_history()`. The built-in `ChatHistory.copy()` hard-codes a plain `ChatHistory`, so a subclass that carries extra state (a store handle, a `session_id`) that forgets to override `copy()` will be **silently replaced by a non-persistent in-memory history** the first time `reset_history()` runs. Any subclass with its own state must override `copy()` to return its own type.```-That's the whole pattern: load on init if there's saved state, persist on every `add_message`. `dump()`/`load()` already round-trip the full history, so there's no serialization logic to write yourself.+```{note}+This pattern re-serializes and rewrites the **entire** history on every message (`self.dump()`), which is fine for a demo but O(n²) over a long conversation. A production backend against Redis/Postgres/etc. should persist incrementally (append the new message) rather than dumping the whole history each write.+```### From-Scratch Alternative