Skip to content

Building AI agents, atomically

refactor: instances of vars, attributes and comments renamed from memory to history, #115

jon fox36bd7d5b7a01
diff --git a/README.md b/README.md
index 05e5670..45e6680 100644
--- a/README.md
+++ b/README.md
@@ -86,7 +86,7 @@ In Atomic Agents, an agent is composed of several key components:
- **System Prompt:** Defines the agent's behavior and purpose.
- **Input Schema:** Specifies the structure and validation rules for the agent's input.
- **Output Schema:** Specifies the structure and validation rules for the agent's output.
-- **Memory:** Stores conversation history or other relevant data.
+- **History:** Stores conversation history or other relevant data.
- **Context Providers:** Inject dynamic context into the agent's system prompt at runtime.
Here's a high-level architecture diagram:
@@ -140,7 +140,7 @@ import instructor
from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseAgentInputSchema
from atomic_agents.lib.base.base_io_schema import BaseIOSchema
from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator
-from atomic_agents.lib.components.agent_memory import AgentHistory
+from atomic_agents.lib.components.agent_history import AgentHistory
# Define a custom output schema
class CustomOutputSchema(BaseIOSchema):
@@ -173,7 +173,7 @@ agent = BaseAgent[BaseAgentInputSchema, CustomOutputSchema](
client=client,
model="gpt-4o-mini",
system_prompt_generator=system_prompt_generator,
- memory=AgentHistory(),
+ history=AgentHistory(),
)
)
diff --git a/atomic-agents/atomic_agents/agents/base_agent.py b/atomic-agents/atomic_agents/agents/base_agent.py
index f02fc1e..18d211e 100644
--- a/atomic-agents/atomic_agents/agents/base_agent.py
+++ b/atomic-agents/atomic_agents/agents/base_agent.py
@@ -60,7 +60,7 @@ class BaseAgentOutputSchema(BaseIOSchema):
class BaseAgentConfig(BaseModel):
client: instructor.client.Instructor = Field(..., description="Client for interacting with the language model.")
model: str = Field(default="gpt-4o-mini", description="The model to use for generating responses.")
- memory: Optional[AgentHistory] = Field(default=None, description="Memory component for storing chat history.")
+ history: Optional[AgentHistory] = Field(default=None, description="history component for storing chat history.")
system_prompt_generator: Optional[SystemPromptGenerator] = Field(
default=None, description="Component for generating system prompts."
)
@@ -75,7 +75,7 @@ class BaseAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
"""
Base class for chat agents.
- This class provides the core functionality for handling chat interactions, including managing memory,
+ This class provides the core functionality for handling chat interactions, including managing history,
generating system prompts, and obtaining responses from a language model.
Type Parameters:
@@ -85,10 +85,10 @@ class BaseAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
Attributes:
client: Client for interacting with the language model.
model (str): The model to use for generating responses.
- memory (AgentHistory): Memory component for storing chat history.
+ history (AgentHistory): History component for storing chat history.
system_prompt_generator (SystemPromptGenerator): Component for generating system prompts.
system_role (Optional[str]): The role of the system in the conversation. None means no system prompt.
- initial_memory (AgentHistory): Initial state of the memory.
+ initial_history (AgentHistory): Initial state of the history.
current_user_input (Optional[InputSchema]): The current user input being processed.
model_api_parameters (dict): Additional parameters passed to the API provider.
- Use this for parameters like 'temperature', 'max_tokens', etc.
@@ -103,18 +103,18 @@ class BaseAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
"""
self.client = config.client
self.model = config.model
- self.memory = config.memory or AgentHistory()
+ self.history = config.history or AgentHistory()
self.system_prompt_generator = config.system_prompt_generator or SystemPromptGenerator()
self.system_role = config.system_role
- self.initial_memory = self.memory.copy()
+ self.initial_history = self.history.copy()
self.current_user_input = None
self.model_api_parameters = config.model_api_parameters or {}
- def reset_memory(self):
+ def reset_history(self):
"""
- Resets the memory to its initial state.
+ Resets the history to its initial state.
"""
- self.memory = self.initial_memory.copy()
+ self.history = self.initial_history.copy()
@property
def input_schema(self) -> Type[BaseIOSchema]:
@@ -145,14 +145,14 @@ class BaseAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
}
]
- self.messages += self.memory.get_history()
+ self.messages += self.history.get_history()
def run(self, user_input: Optional[InputSchema] = None) -> OutputSchema:
"""
Runs the chat agent with the given user input synchronously.
Args:
- user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to memory.
+ user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.
Returns:
OutputSchema: The response from the chat agent.
@@ -161,9 +161,9 @@ class BaseAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
self.client, instructor.client.AsyncInstructor
), "The run method is not supported for async clients. Use run_async instead."
if user_input:
- self.memory.initialize_turn()
+ self.history.initialize_turn()
self.current_user_input = user_input
- self.memory.add_message("user", user_input)
+ self.history.add_message("user", user_input)
self._prepare_messages()
response = self.client.chat.completions.create(
@@ -172,7 +172,7 @@ class BaseAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
response_model=self.output_schema,
**self.model_api_parameters,
)
- self.memory.add_message("assistant", response)
+ self.history.add_message("assistant", response)
return response
@@ -181,7 +181,7 @@ class BaseAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
Runs the chat agent with the given user input, supporting streaming output.
Args:
- user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to memory.
+ user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.
Yields:
OutputSchema: Partial responses from the chat agent.
@@ -193,9 +193,9 @@ class BaseAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
self.client, instructor.client.AsyncInstructor
), "The run_stream method is not supported for async clients. Use run_async instead."
if user_input:
- self.memory.initialize_turn()
+ self.history.initialize_turn()
self.current_user_input = user_input
- self.memory.add_message("user", user_input)
+ self.history.add_message("user", user_input)
self._prepare_messages()
@@ -211,7 +211,7 @@ class BaseAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
yield partial_response
full_response_content = self.output_schema(**partial_response.model_dump())
- self.memory.add_message("assistant", full_response_content)
+ self.history.add_message("assistant", full_response_content)
return full_response_content
@@ -220,7 +220,7 @@ class BaseAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
Runs the chat agent asynchronously with the given user input.
Args:
- user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to memory.
+ user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.
Returns:
OutputSchema: The response from the chat agent.
@@ -231,9 +231,9 @@ class BaseAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
"""
assert isinstance(self.client, instructor.client.AsyncInstructor), "The run_async method is for async clients."
if user_input:
- self.memory.initialize_turn()
+ self.history.initialize_turn()
self.current_user_input = user_input
- self.memory.add_message("user", user_input)
+ self.history.add_message("user", user_input)
self._prepare_messages()
@@ -241,7 +241,7 @@ class BaseAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
model=self.model, messages=self.messages, response_model=self.output_schema, **self.model_api_parameters
)
- self.memory.add_message("assistant", response)
+ self.history.add_message("assistant", response)
return response
async def run_async_stream(self, user_input: Optional[InputSchema] = None) -> AsyncGenerator[OutputSchema, None]:
@@ -249,16 +249,16 @@ class BaseAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
Runs the chat agent asynchronously with the given user input, supporting streaming output.
Args:
- user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to memory.
+ user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.
Yields:
OutputSchema: Partial responses from the chat agent.
"""
assert isinstance(self.client, instructor.client.AsyncInstructor), "The run_async method is for async clients."
if user_input:
- self.memory.initialize_turn()
+ self.history.initialize_turn()
self.current_user_input = user_input
- self.memory.add_message("user", user_input)
+ self.history.add_message("user", user_input)
self._prepare_messages()
@@ -277,7 +277,7 @@ class BaseAgent[InputSchema: BaseIOSchema, OutputSchema: BaseIOSchema]:
if last_response:
full_response_content = self.output_schema(**last_response.model_dump())
- self.memory.add_message("assistant", full_response_content)
+ self.history.add_message("assistant", full_response_content)
def get_context_provider(self, provider_name: str) -> Type[SystemPromptContextProviderBase]:
"""
@@ -365,7 +365,7 @@ if __name__ == "__main__":
info_table.add_column("Value", style="yellow")
info_table.add_row("Model", agent.model)
- info_table.add_row("Memory", str(type(agent.memory).__name__))
+ info_table.add_row("History", str(type(agent.history).__name__))
info_table.add_row("System Prompt Generator", str(type(agent.system_prompt_generator).__name__))
return info_table
diff --git a/atomic-agents/atomic_agents/lib/components/agent_history.py b/atomic-agents/atomic_agents/lib/components/agent_history.py
index b9f6fd4..f494613 100644
--- a/atomic-agents/atomic_agents/lib/components/agent_history.py
+++ b/atomic-agents/atomic_agents/lib/components/agent_history.py
@@ -126,15 +126,15 @@ class AgentHistory:
def copy(self) -> "AgentHistory":
"""
- Creates a copy of the chat memory.
+ Creates a copy of the chat history.
Returns:
- AgentHistory: A copy of the chat memory.
+ AgentHistory: A copy of the chat history.
"""
- new_memory = AgentHistory(max_messages=self.max_messages)
- new_memory.load(self.dump())
- new_memory.current_turn_id = self.current_turn_id
- return new_memory
+ new_history = AgentHistory(max_messages=self.max_messages)
+ new_history.load(self.dump())
+ new_history.current_turn_id = self.current_turn_id
+ return new_history
def get_current_turn_id(self) -> Optional[str]:
"""
@@ -147,7 +147,7 @@ class AgentHistory:
def delete_turn_id(self, turn_id: int):
"""
- Delete messages from the memory by its turn ID.
+ Delete messages from the history by its turn ID.
Args:
turn_id (int): The turn ID of the message to delete.
@@ -156,13 +156,13 @@ class AgentHistory:
str: A success message with the deleted turn ID.
Raises:
- ValueError: If the specified turn ID is not found in the memory.
+ ValueError: If the specified turn ID is not found in the history.
"""
initial_length = len(self.history)
self.history = [msg for msg in self.history if msg.turn_id != turn_id]
if len(self.history) == initial_length:
- raise ValueError(f"Turn ID {turn_id} not found in memory.")
+ raise ValueError(f"Turn ID {turn_id} not found in history.")
# Update current_turn_id if necessary
if not len(self.history):
@@ -200,12 +200,12 @@ class AgentHistory:
}
serialized_history.append(serialized_message)
- memory_data = {
+ history_data = {
"history": serialized_history,
"max_messages": self.max_messages,
"current_turn_id": self.current_turn_id,
}
- return json.dumps(memory_data)
+ return json.dumps(history_data)
def load(self, serialized_data: str) -> None:
"""
@@ -218,12 +218,12 @@ class AgentHistory:
ValueError: If the serialized data is invalid or cannot be deserialized.
"""
try:
- memory_data = json.loads(serialized_data)
+ history_data = json.loads(serialized_data)
self.history = []
- self.max_messages = memory_data["max_messages"]
- self.current_turn_id = memory_data["current_turn_id"]
+ self.max_messages = history_data["max_messages"]
+ self.current_turn_id = history_data["current_turn_id"]
- for message_data in memory_data["history"]:
+ for message_data in history_data["history"]:
content_info = message_data["content"]
content_class = self._get_class_from_string(content_info["class_name"])
content_instance = content_class(**content_info["data"])
@@ -286,11 +286,11 @@ if __name__ == "__main__":
instruction_text: str = Field(..., description="The instruction text")
images: List[instructor.Image] = Field(..., description="The images to analyze")
- # Create and populate the original memory with complex data
- original_memory = AgentHistory(max_messages=10)
+ # Create and populate the original history with complex data
+ original_history = AgentHistory(max_messages=10)
# Add a complex input message
- original_memory.add_message(
+ original_history.add_message(
"user",
ComplexInputSchema(
text_field="Hello, this is a complex input",
@@ -301,7 +301,7 @@ if __name__ == "__main__":
)
# Add a complex output message
- original_memory.add_message(
+ original_history.add_message(
"assistant",
ComplexOutputSchema(
response_text="This is a complex response",
@@ -317,7 +317,7 @@ if __name__ == "__main__":
test_image_path = os.path.join("test_images", "test.jpg")
if os.path.exists(test_image_path):
# Add a multimodal message
- original_memory.add_message(
+ original_history.add_message(
"user",
MultimodalSchema(
instruction_text="Please analyze this image", images=[instructor.Image.from_path(test_image_path)]
@@ -325,17 +325,17 @@ if __name__ == "__main__":
)
# Continue with existing tests...
- dumped_data = original_memory.dump()
+ dumped_data = original_history.dump()
print("Dumped data:")
print(dumped_data)
- # Create a new memory and load the dumped data
- loaded_memory = AgentHistory()
- loaded_memory.load(dumped_data)
+ # Create a new history and load the dumped data
+ loaded_history = AgentHistory()
+ loaded_history.load(dumped_data)
- # Print detailed information about the loaded memory
- print("\nLoaded memory details:")
- for i, message in enumerate(loaded_memory.history):
+ # Print detailed information about the loaded history
+ print("\nLoaded history details:")
+ for i, message in enumerate(loaded_history.history):
print(f"\nMessage {i + 1}:")
print(f"Role: {message.role}")
print(f"Turn ID: {message.turn_id}")
@@ -346,8 +346,8 @@ if __name__ == "__main__":
# Final verification
print("\nFinal verification:")
- print(f"Max messages: {loaded_memory.max_messages}")
- print(f"Current turn ID: {loaded_memory.get_current_turn_id()}")
+ print(f"Max messages: {loaded_history.max_messages}")
+ print(f"Current turn ID: {loaded_history.get_current_turn_id()}")
print("Last message content:")
- last_message = loaded_memory.history[-1]
+ last_message = loaded_history.history[-1]
print(last_message.content.model_dump())
diff --git a/atomic-agents/tests/agents/test_base_agent.py b/atomic-agents/tests/agents/test_base_agent.py
index ad126df..0d30fa6 100644
--- a/atomic-agents/tests/agents/test_base_agent.py
+++ b/atomic-agents/tests/agents/test_base_agent.py
@@ -57,7 +57,7 @@ def mock_instructor_async():
@pytest.fixture
-def mock_memory():
+def mock_history():
mock = Mock(spec=AgentHistory)
mock.get_history.return_value = []
mock.add_message = Mock()
@@ -75,11 +75,11 @@ def mock_system_prompt_generator():
@pytest.fixture
-def agent_config(mock_instructor, mock_memory, mock_system_prompt_generator):
+def agent_config(mock_instructor, mock_history, mock_system_prompt_generator):
return BaseAgentConfig(
client=mock_instructor,
model="gpt-4o-mini",
- memory=mock_memory,
+ history=mock_history,
system_prompt_generator=mock_system_prompt_generator,
)
@@ -90,11 +90,11 @@ def agent(agent_config):
@pytest.fixture
-def agent_config_async(mock_instructor_async, mock_memory, mock_system_prompt_generator):
+def agent_config_async(mock_instructor_async, mock_history, mock_system_prompt_generator):
return BaseAgentConfig(
client=mock_instructor_async,
model="gpt-4o-mini",
- memory=mock_memory,
+ history=mock_history,
system_prompt_generator=mock_system_prompt_generator,
)
@@ -104,20 +104,20 @@ def agent_async(agent_config_async):
return BaseAgent[BaseAgentInputSchema, BaseAgentOutputSchema](agent_config_async)
-def test_initialization(agent, mock_instructor, mock_memory, mock_system_prompt_generator):
+def test_initialization(agent, mock_instructor, mock_history, mock_system_prompt_generator):
assert agent.client == mock_instructor
assert agent.model == "gpt-4o-mini"
- assert agent.memory == mock_memory
+ assert agent.history == mock_history
assert agent.system_prompt_generator == mock_system_prompt_generator
assert "max_tokens" not in agent.model_api_parameters
# model_api_parameters should have priority over other settings
-def test_initialization_temperature_priority(mock_instructor, mock_memory, mock_system_prompt_generator):
+def test_initialization_temperature_priority(mock_instructor, mock_history, mock_system_prompt_generator):
config = BaseAgentConfig(
client=mock_instructor,
model="gpt-4o-mini",
- memory=mock_memory,
+ history=mock_history,
system_prompt_generator=mock_system_prompt_generator,
model_api_parameters={"temperature": 1.0},
)
@@ -125,11 +125,11 @@ def test_initialization_temperature_priority(mock_instructor, mock_memory, mock_
assert agent.model_api_parameters["temperature"] == 1.0
-def test_initialization_without_temperature(mock_instructor, mock_memory, mock_system_prompt_generator):
+def test_initialization_without_temperature(mock_instructor, mock_history, mock_system_prompt_generator):
config = BaseAgentConfig(
client=mock_instructor,
model="gpt-4o-mini",
- memory=mock_memory,
+ history=mock_history,
system_prompt_generator=mock_system_prompt_generator,
model_api_parameters={"temperature": 0.5},
)
@@ -137,11 +137,11 @@ def test_initialization_without_temperature(mock_instructor, mock_memory, mock_s
assert agent.model_api_parameters["temperature"] == 0.5
-def test_initialization_without_max_tokens(mock_instructor, mock_memory, mock_system_prompt_generator):
+def test_initialization_without_max_tokens(mock_instructor, mock_history, mock_system_prompt_generator):
config = BaseAgentConfig(
client=mock_instructor,
model="gpt-4o-mini",
- memory=mock_memory,
+ history=mock_history,
system_prompt_generator=mock_system_prompt_generator,
model_api_parameters={"max_tokens": 1024},
)
@@ -149,11 +149,11 @@ def test_initialization_without_max_tokens(mock_instructor, mock_memory, mock_sy
assert agent.model_api_parameters["max_tokens"] == 1024
-def test_initialization_system_role_equals_developer(mock_instructor, mock_memory, mock_system_prompt_generator):
+def test_initialization_system_role_equals_developer(mock_instructor, mock_history, mock_system_prompt_generator):
config = BaseAgentConfig(
client=mock_instructor,
model="gpt-4o-mini",
- memory=mock_memory,
+ history=mock_history,
system_prompt_generator=mock_system_prompt_generator,
system_role="developer",
model_api_parameters={}, # No temperature specified
@@ -163,11 +163,11 @@ def test_initialization_system_role_equals_developer(mock_instructor, mock_memor
assert isinstance(agent.messages, list) and agent.messages[0]["role"] == "developer"
-def test_initialization_system_role_equals_None(mock_instructor, mock_memory, mock_system_prompt_generator):
+def test_initialization_system_role_equals_None(mock_instructor, mock_history, mock_system_prompt_generator):
config = BaseAgentConfig(
client=mock_instructor,
model="gpt-4o-mini",
- memory=mock_memory,
+ history=mock_history,
system_prompt_generator=mock_system_prompt_generator,
system_role=None,
model_api_parameters={}, # No temperature specified
@@ -177,11 +177,11 @@ def test_initialization_system_role_equals_None(mock_instructor, mock_memory, mo
assert isinstance(agent.messages, list) and len(agent.messages) == 0
-def test_reset_memory(agent, mock_memory):
- initial_memory = agent.initial_memory
- agent.reset_memory()
- assert agent.memory != initial_memory
- mock_memory.copy.assert_called_once()
+def test_reset_history(agent, mock_history):
+ initial_history = agent.initial_history
+ agent.reset_history()
+ assert agent.history != initial_history
+ mock_history.copy.assert_called_once()
def test_get_context_provider(agent, mock_system_prompt_generator):
@@ -278,7 +278,7 @@ def test_base_io_schema_model_json_schema_no_description():
assert schema["description"] == "Test schema docstring."
-def test_run(agent, mock_memory):
+def test_run(agent, mock_history):
# Use the agent fixture that's already configured correctly
mock_input = BaseAgentInputSchema(chat_message="Test input")
@@ -288,15 +288,15 @@ def test_run(agent, mock_memory):
assert result.chat_message == "Test output"
assert agent.current_user_input == mock_input
- mock_memory.add_message.assert_has_calls([call("user", mock_input), call("assistant", result)])
+ mock_history.add_message.assert_has_calls([call("user", mock_input), call("assistant", result)])
-def test_run_stream(mock_instructor, mock_memory):
+def test_run_stream(mock_instructor, mock_history):
# Create a BaseAgentConfig with system_role set to None
config = BaseAgentConfig(
client=mock_instructor,
model="gpt-4o-mini",
- memory=mock_memory,
+ history=mock_history,
system_prompt_generator=None, # No system prompt generator
)
agent = BaseAgent[BaseAgentInputSchema, BaseAgentOutputSchema](config)
@@ -310,11 +310,11 @@ def test_run_stream(mock_instructor, mock_memory):
assert result == mock_output
assert agent.current_user_input == mock_input
- mock_memory.add_message.assert_has_calls([call("user", mock_input), call("assistant", mock_output)])
+ mock_history.add_message.assert_has_calls([call("user", mock_input), call("assistant", mock_output)])
@pytest.mark.asyncio
-async def test_run_async(agent_async, mock_memory):
+async def test_run_async(agent_async, mock_history):
# Create a mock input
mock_input = BaseAgentInputSchema(chat_message="Test input")
mock_output = BaseAgentOutputSchema(chat_message="Test output")
@@ -325,11 +325,11 @@ async def test_run_async(agent_async, mock_memory):
# Assertions
assert response == mock_output
assert agent_async.current_user_input == mock_input
- mock_memory.add_message.assert_has_calls([call("user", mock_input), call("assistant", mock_output)])
+ mock_history.add_message.assert_has_calls([call("user", mock_input), call("assistant", mock_output)])
@pytest.mark.asyncio
-async def test_run_async_stream(agent_async, mock_memory):
+async def test_run_async_stream(agent_async, mock_history):
# Create a mock input
mock_input = BaseAgentInputSchema(chat_message="Test input")
mock_output = BaseAgentOutputSchema(chat_message="Test output")
@@ -344,12 +344,12 @@ async def test_run_async_stream(agent_async, mock_memory):
assert responses[0] == mock_output
assert agent_async.current_user_input == mock_input
- # Verify that both user input and assistant response were added to memory
- mock_memory.add_message.assert_any_call("user", mock_input)
+ # Verify that both user input and assistant response were added to history
+ mock_history.add_message.assert_any_call("user", mock_input)
# Create the expected full response content to check
full_response_content = agent_async.output_schema(**responses[0].model_dump())
- mock_memory.add_message.assert_any_call("assistant", full_response_content)
+ mock_history.add_message.assert_any_call("assistant", full_response_content)
def test_model_from_chunks_patched():
diff --git a/atomic-agents/tests/lib/components/test_agent_history.py b/atomic-agents/tests/lib/components/test_agent_history.py
index 253165a..2a6acb3 100644
--- a/atomic-agents/tests/lib/components/test_agent_history.py
+++ b/atomic-agents/tests/lib/components/test_agent_history.py
@@ -51,69 +51,69 @@ class MockMultimodalSchema(BaseIOSchema):
@pytest.fixture
-def memory():
+def history():
return AgentHistory(max_messages=5)
-def test_initialization(memory):
- assert memory.history == []
- assert memory.max_messages == 5
- assert memory.current_turn_id is None
+def test_initialization(history):
+ assert history.history == []
+ assert history.max_messages == 5
+ assert history.current_turn_id is None
-def test_initialize_turn(memory):
- memory.initialize_turn()
- assert memory.current_turn_id is not None
+def test_initialize_turn(history):
+ history.initialize_turn()
+ assert history.current_turn_id is not None
-def test_add_message(memory):
- memory.add_message("user", InputSchema(test_field="Hello"))
- assert len(memory.history) == 1
- assert memory.history[0].role == "user"
- assert isinstance(memory.history[0].content, InputSchema)
- assert memory.history[0].turn_id is not None
+def test_add_message(history):
+ history.add_message("user", InputSchema(test_field="Hello"))
+ assert len(history.history) == 1
+ assert history.history[0].role == "user"
+ assert isinstance(history.history[0].content, InputSchema)
+ assert history.history[0].turn_id is not None
-def test_manage_overflow(memory):
+def test_manage_overflow(history):
for i in range(7):
- memory.add_message("user", InputSchema(test_field=f"Message {i}"))
- assert len(memory.history) == 5
- assert memory.history[0].content.test_field == "Message 2"
+ history.add_message("user", InputSchema(test_field=f"Message {i}"))
+ assert len(history.history) == 5
+ assert history.history[0].content.test_field == "Message 2"
-def test_get_history(memory):
- memory.add_message("user", InputSchema(test_field="Hello"))
- memory.add_message("assistant", MockOutputSchema(test_field="Hi there"))
- history = memory.get_history()
+def test_get_history(history):
+ history.add_message("user", InputSchema(test_field="Hello"))
+ history.add_message("assistant", MockOutputSchema(test_field="Hi there"))
+ history = history.get_history()
assert len(history) == 2
assert history[0]["role"] == "user"
assert json.loads(history[0]["content"]) == {"test_field": "Hello"}
-def test_copy(memory):
- memory.add_message("user", InputSchema(test_field="Hello"))
- copied_memory = memory.copy()
- assert copied_memory.max_messages == memory.max_messages
- assert copied_memory.current_turn_id == memory.current_turn_id
- assert len(copied_memory.history) == len(memory.history)
- assert copied_memory.history[0].role == memory.history[0].role
- assert copied_memory.history[0].content.test_field == memory.history[0].content.test_field
+def test_copy(history):
+ history.add_message("user", InputSchema(test_field="Hello"))
+ copied_history = history.copy()
+ assert copied_history.max_messages == history.max_messages
+ assert copied_history.current_turn_id == history.current_turn_id
+ assert len(copied_history.history) == len(history.history)
+ assert copied_history.history[0].role == history.history[0].role
+ assert copied_history.history[0].content.test_field == history.history[0].content.test_field
-def test_get_current_turn_id(memory):
- assert memory.get_current_turn_id() is None
- memory.initialize_turn()
- assert memory.get_current_turn_id() is not None
+def test_get_current_turn_id(history):
+ assert history.get_current_turn_id() is None
+ history.initialize_turn()
+ assert history.get_current_turn_id() is not None
-def test_get_message_count(memory):
- assert memory.get_message_count() == 0
- memory.add_message("user", InputSchema(test_field="Hello"))
- assert memory.get_message_count() == 1
+def test_get_message_count(history):
+ assert history.get_message_count() == 0
+ history.add_message("user", InputSchema(test_field="Hello"))
+ assert history.get_message_count() == 1
-def test_dump_and_load(memory):
- memory.add_message(
+def test_dump_and_load(history):
+ history.add_message(
"user",
MockComplexInputSchema(
text_field="Hello",
@@ -122,7 +122,7 @@ def test_dump_and_load(memory):
nested_field=MockNestedSchema(nested_field="Nested", nested_int=42),
),
)
- memory.add_message(
+ history.add_message(
"assistant",
MockComplexOutputSchema(
response_text="Hi there",
@@ -131,29 +131,29 @@ def test_dump_and_load(memory):
),
)
- dumped_data = memory.dump()
- new_memory = AgentHistory()
- new_memory.load(dumped_data)
+ dumped_data = history.dump()
+ new_history = AgentHistory()
+ new_history.load(dumped_data)
- assert new_memory.max_messages == memory.max_messages
- assert new_memory.current_turn_id == memory.current_turn_id
- assert len(new_memory.history) == len(memory.history)
- assert isinstance(new_memory.history[0].content, MockComplexInputSchema)
- assert isinstance(new_memory.history[1].content, MockComplexOutputSchema)
- assert new_memory.history[0].content.text_field == "Hello"
- assert new_memory.history[1].content.response_text == "Hi there"
+ assert new_history.max_messages == history.max_messages
+ assert new_history.current_turn_id == history.current_turn_id
+ assert len(new_history.history) == len(history.history)
+ assert isinstance(new_history.history[0].content, MockComplexInputSchema)
+ assert isinstance(new_history.history[1].content, MockComplexOutputSchema)
+ assert new_history.history[0].content.text_field == "Hello"
+ assert new_history.history[1].content.response_text == "Hi there"
-def test_load_invalid_data(memory):
+def test_load_invalid_data(history):
with pytest.raises(ValueError):
- memory.load("invalid json")
+ history.load("invalid json")
def test_get_class_from_string():
- class_string = "tests.lib.components.test_agent_memory.InputSchema"
+ class_string = "tests.lib.components.test_agent_history.InputSchema"
cls = AgentHistory._get_class_from_string(class_string)
assert cls.__name__ == InputSchema.__name__
- assert cls.__module__.endswith("test_agent_memory")
+ assert cls.__module__.endswith("test_agent_history")
assert issubclass(cls, BaseIOSchema)
@@ -169,9 +169,9 @@ def test_message_model():
assert message.turn_id == "123"
-def test_complex_scenario(memory):
+def test_complex_scenario(history):
# Add complex input
- memory.add_message(
+ history.add_message(
"user",
MockComplexInputSchema(
text_field="Complex input",
@@ -182,7 +182,7 @@ def test_complex_scenario(memory):
)
# Add complex output
- memory.add_message(
+ history.add_message(
"assistant",
MockComplexOutputSchema(
response_text="Complex output",
@@ -195,105 +195,105 @@ def test_complex_scenario(memory):
)
# Dump and load
- dumped_data = memory.dump()
- new_memory = AgentHistory()
- new_memory.load(dumped_data)
+ dumped_data = history.dump()
+ new_history = AgentHistory()
+ new_history.load(dumped_data)
# Verify loaded data
- assert len(new_memory.history) == 2
- assert isinstance(new_memory.history[0].content, MockComplexInputSchema)
- assert isinstance(new_memory.history[1].content, MockComplexOutputSchema)
- assert new_memory.history[0].content.text_field == "Complex input"
- assert new_memory.history[0].content.nested_field.nested_int == 99
- assert new_memory.history[1].content.response_text == "Complex output"
- assert new_memory.history[1].content.data_dict["key1"].nested_field == "Nested output 1"
-
- # Add a new message to the loaded memory
- new_memory.add_message("user", InputSchema(test_field="New message"))
- assert len(new_memory.history) == 3
- assert new_memory.history[2].content.test_field == "New message"
-
-
-def test_memory_with_no_max_messages():
- unlimited_memory = AgentHistory()
+ assert len(new_history.history) == 2
+ assert isinstance(new_history.history[0].content, MockComplexInputSchema)
+ assert isinstance(new_history.history[1].content, MockComplexOutputSchema)
+ assert new_history.history[0].content.text_field == "Complex input"
+ assert new_history.history[0].content.nested_field.nested_int == 99
+ assert new_history.history[1].content.response_text == "Complex output"
+ assert new_history.history[1].content.data_dict["key1"].nested_field == "Nested output 1"
+
+ # Add a new message to the loaded history
+ new_history.add_message("user", InputSchema(test_field="New message"))
+ assert len(new_history.history) == 3
+ assert new_history.history[2].content.test_field == "New message"
+
+
+def test_history_with_no_max_messages():
+ unlimited_history = AgentHistory()
for i in range(100):
- unlimited_memory.add_message("user", InputSchema(test_field=f"Message {i}"))
- assert len(unlimited_memory.history) == 100
+ unlimited_history.add_message("user", InputSchema(test_field=f"Message {i}"))
+ assert len(unlimited_history.history) == 100
-def test_memory_with_zero_max_messages():
- zero_max_memory = AgentHistory(max_messages=0)
+def test_history_with_zero_max_messages():
+ zero_max_history = AgentHistory(max_messages=0)
for i in range(10):
- zero_max_memory.add_message("user", InputSchema(test_field=f"Message {i}"))
- assert len(zero_max_memory.history) == 0
+ zero_max_history.add_message("user", InputSchema(test_field=f"Message {i}"))
+ assert len(zero_max_history.history) == 0
-def test_memory_turn_consistency():
- memory = AgentHistory()
- memory.initialize_turn()
- turn_id = memory.get_current_turn_id()
- memory.add_message("user", InputSchema(test_field="Hello"))
- memory.add_message("assistant", MockOutputSchema(test_field="Hi"))
- assert memory.history[0].turn_id == turn_id
- assert memory.history[1].turn_id == turn_id
+def test_history_turn_consistency():
+ history = AgentHistory()
+ history.initialize_turn()
+ turn_id = history.get_current_turn_id()
+ history.add_message("user", InputSchema(test_field="Hello"))
+ history.add_message("assistant", MockOutputSchema(test_field="Hi"))
+ assert history.history[0].turn_id == turn_id
+ assert history.history[1].turn_id == turn_id
- memory.initialize_turn()
- new_turn_id = memory.get_current_turn_id()
+ history.initialize_turn()
+ new_turn_id = history.get_current_turn_id()
assert new_turn_id != turn_id
- memory.add_message("user", InputSchema(test_field="Next turn"))
- assert memory.history[2].turn_id == new_turn_id
+ history.add_message("user", InputSchema(test_field="Next turn"))
+ assert history.history[2].turn_id == new_turn_id
-def test_agent_memory_delete_turn_id(memory):
+def test_agent_history_delete_turn_id(history):
mock_input = InputSchema(test_field="Test input")
mock_output = InputSchema(test_field="Test output")
- memory = AgentHistory()
+ history = AgentHistory()
initial_turn_id = "123-456"
- memory.current_turn_id = initial_turn_id
+ history.current_turn_id = initial_turn_id
# Add a message with a specific turn ID
- memory.add_message(
+ history.add_message(
"user",
mock_input,
)
- memory.history[-1].turn_id = initial_turn_id
+ history.history[-1].turn_id = initial_turn_id
# Add another message with a different turn ID
other_turn_id = "789-012"
- memory.add_message(
+ history.add_message(
"assistant",
mock_output,
)
- memory.history[-1].turn_id = other_turn_id
+ history.history[-1].turn_id = other_turn_id
# Act & Assert: Delete the message with initial_turn_id and verify
- memory.delete_turn_id(initial_turn_id)
+ history.delete_turn_id(initial_turn_id)
- # The remaining message in memory should have the other_turn_id
- assert len(memory.history) == 1
- assert memory.history[0].turn_id == other_turn_id
+ # The remaining message in history should have the other_turn_id
+ assert len(history.history) == 1
+ assert history.history[0].turn_id == other_turn_id
# If we delete the last message, current_turn_id should become None
- memory.delete_turn_id(other_turn_id)
- assert memory.current_turn_id is None
- assert len(memory.history) == 0
+ history.delete_turn_id(other_turn_id)
+ assert history.current_turn_id is None
+ assert len(history.history) == 0
# Assert: Trying to delete a non-existing turn ID should raise a ValueError
- with pytest.raises(ValueError, match="Turn ID non-existent-id not found in memory."):
- memory.delete_turn_id("non-existent-id")
+ with pytest.raises(ValueError, match="Turn ID non-existent-id not found in history."):
+ history.delete_turn_id("non-existent-id")
-def test_get_history_with_multimodal_content(memory):
+def test_get_history_with_multimodal_content(history):
"""Test that get_history correctly handles multimodal content"""
# Create a mock image
mock_image = instructor.Image(source="test_url", media_type="image/jpeg", detail="low")
# Add a multimodal message
- memory.add_message("user", MockMultimodalSchema(instruction_text="Analyze this image", images=[mock_image]))
+ history.add_message("user", MockMultimodalSchema(instruction_text="Analyze this image", images=[mock_image]))
# Get history and verify format
- history = memory.get_history()
+ history = history.get_history()
assert len(history) == 1
assert history[0]["role"] == "user"
assert isinstance(history[0]["content"], list)
@@ -301,7 +301,7 @@ def test_get_history_with_multimodal_content(memory):
assert history[0]["content"][1] == mock_image
-def test_get_history_with_multiple_images_multimodal_content(memory):
+def test_get_history_with_multiple_images_multimodal_content(history):
"""Test that get_history correctly handles multimodal content"""
class MockMultimodalSchemaArbitraryKeys(BaseIOSchema):
@@ -317,7 +317,7 @@ def test_get_history_with_multiple_images_multimodal_content(memory):
mock_image_3 = instructor.Image(source="test_url_3", media_type="image/jpeg", detail="low")
# Add a multimodal message
- memory.add_message(
+ history.add_message(
"user",
MockMultimodalSchemaArbitraryKeys(
instruction_text="Analyze this image",
@@ -327,7 +327,7 @@ def test_get_history_with_multiple_images_multimodal_content(memory):
)
# Get history and verify format
- history = memory.get_history()
+ history = history.get_history()
assert len(history) == 1
assert history[0]["role"] == "user"
assert isinstance(history[0]["content"], list)
diff --git a/atomic-examples/deep-research/deep_research/main.py b/atomic-examples/deep-research/deep_research/main.py
index 8e8198d..4010118 100644
--- a/atomic-examples/deep-research/deep_research/main.py
+++ b/atomic-examples/deep-research/deep_research/main.py
@@ -81,7 +81,7 @@ def initialize_conversation() -> None:
answer=WELCOME_MESSAGE,
follow_up_questions=STARTER_QUESTIONS,
)
- question_answering_agent.memory.add_message("assistant", initial_answer)
+ question_answering_agent.history.add_message("assistant", initial_answer)
def display_welcome() -> None:
@@ -164,7 +164,7 @@ def chat_loop() -> None:
question_answering_agent.register_context_provider("scraped_content", scraped_content_context_provider)
query_agent.register_context_provider("scraped_content", scraped_content_context_provider)
- console.print("[dim]• Initializing conversation memory...[/dim]")
+ console.print("[dim]• Initializing conversation history...[/dim]")
initialize_conversation()
console.print("[bold green]✨ System initialized successfully![/bold green]\n")
diff --git a/atomic-examples/mcp-agent/example-client/example_client/main_sse.py b/atomic-examples/mcp-agent/example-client/example_client/main_sse.py
index 0ef191b..ec8cddb 100644
--- a/atomic-examples/mcp-agent/example-client/example_client/main_sse.py
+++ b/atomic-examples/mcp-agent/example-client/example_client/main_sse.py
@@ -140,12 +140,12 @@ def main():
console.print(table)
# Create and initialize orchestrator agent
console.print("[dim]• Creating orchestrator agent...[/dim]")
- memory = AgentHistory()
+ history = AgentHistory()
orchestrator_agent = BaseAgent[MCPOrchestratorInputSchema, OrchestratorOutputSchema](
BaseAgentConfig(
client=client,
model=config.openai_model,
- memory=memory,
+ history=history,
system_prompt_generator=SystemPromptGenerator(
background=[
"You are an MCP Orchestrator Agent, designed to chat with users and",
@@ -378,11 +378,11 @@ def main():
tool_output = tool_instance.run(action_instance)
console.print(f"[bold green]Result:[/bold green] {tool_output.result}")
- # Add tool result to agent memory
+ # Add tool result to agent history
result_message = MCPOrchestratorInputSchema(
query=f"Tool {tool_name} executed with result: {tool_output.result}"
)
- orchestrator_agent.memory.add_message("system", result_message)
+ orchestrator_agent.history.add_message("system", result_message)
# Run the agent again without parameters to continue the flow
orchestrator_output = orchestrator_agent.run()
diff --git a/atomic-examples/mcp-agent/example-client/example_client/main_stdio.py b/atomic-examples/mcp-agent/example-client/example_client/main_stdio.py
index ea1f654..66e2f88 100644
--- a/atomic-examples/mcp-agent/example-client/example_client/main_stdio.py
+++ b/atomic-examples/mcp-agent/example-client/example_client/main_stdio.py
@@ -133,12 +133,12 @@ def main():
console.print(table)
# Create and initialize orchestrator agent
console.print("[dim]• Creating orchestrator agent...[/dim]")
- memory = AgentHistory()
+ history = AgentHistory()
orchestrator_agent = BaseAgent[MCPOrchestratorInputSchema, OrchestratorOutputSchema](
BaseAgentConfig(
client=client,
model=config.openai_model,
- memory=memory,
+ history=history,
system_prompt_generator=SystemPromptGenerator(
background=[
"You are an MCP Orchestrator Agent, designed to chat with users and",
@@ -195,11 +195,11 @@ def main():
tool_output = tool_instance.run(action_instance)
console.print(f"[bold green]Result:[/bold green] {tool_output.result}")
- # Add tool result to agent memory
+ # Add tool result to agent history
result_message = MCPOrchestratorInputSchema(
query=(f"Tool {tool_name} executed with result: " f"{tool_output.result}")
)
- orchestrator_agent.memory.add_message("system", result_message)
+ orchestrator_agent.history.add_message("system", result_message)
# Run the agent again without parameters to continue the flow
orchestrator_output = orchestrator_agent.run()
diff --git a/atomic-examples/orchestration-agent/orchestration_agent/orchestrator.py b/atomic-examples/orchestration-agent/orchestration_agent/orchestrator.py
index 0512406..0441917 100644
--- a/atomic-examples/orchestration-agent/orchestration_agent/orchestrator.py
+++ b/atomic-examples/orchestration-agent/orchestration_agent/orchestrator.py
@@ -172,10 +172,10 @@ if __name__ == "__main__":
console.print("\n" + "-" * 80 + "\n")
# Switch agent
- memory = orchestrator_agent.memory
+ history = orchestrator_agent.history
orchestrator_agent = orchestrator_agent_final
- orchestrator_agent.memory = memory
- orchestrator_agent.memory.add_message("system", response)
+ orchestrator_agent.history = history
+ orchestrator_agent.history.add_message("system", response)
final_answer = orchestrator_agent.run(input_schema)
console.print(f"\n[bold blue]Final Answer:[/bold blue] {final_answer.final_answer}")
# Reset the agent to the original
diff --git a/atomic-examples/quickstart/quickstart/1_0_basic_chatbot.py b/atomic-examples/quickstart/quickstart/1_0_basic_chatbot.py
index 0c1fc69..27ebddd 100644
--- a/atomic-examples/quickstart/quickstart/1_0_basic_chatbot.py
+++ b/atomic-examples/quickstart/quickstart/1_0_basic_chatbot.py
@@ -20,12 +20,12 @@ if not API_KEY:
# Initialize a Rich Console for pretty console outputs
console = Console()
-# Memory setup
-memory = AgentHistory()
+# History setup
+history = AgentHistory()
-# Initialize memory with an initial message from the assistant
+# Initialize history with an initial message from the assistant
initial_message = BaseAgentOutputSchema(chat_message="Hello! How can I assist you today?")
-memory.add_message("assistant", initial_message)
+history.add_message("assistant", initial_message)
# OpenAI client setup using the Instructor library
client = instructor.from_openai(openai.OpenAI(api_key=API_KEY))
@@ -35,7 +35,7 @@ agent = BaseAgent[BaseAgentInputSchema, BaseAgentOutputSchema](
config=BaseAgentConfig(
client=client,
model="gpt-4o-mini",
- memory=memory,
+ history=history,
)
)
diff --git a/atomic-examples/quickstart/quickstart/1_1_basic_chatbot_streaming.py b/atomic-examples/quickstart/quickstart/1_1_basic_chatbot_streaming.py
index 46ca6d3..8caf281 100644
--- a/atomic-examples/quickstart/quickstart/1_1_basic_chatbot_streaming.py
+++ b/atomic-examples/quickstart/quickstart/1_1_basic_chatbot_streaming.py
@@ -20,12 +20,12 @@ if not API_KEY:
# Initialize a Rich Console for pretty console outputs
console = Console()
-# Memory setup
-memory = AgentHistory()
+# History setup
+history = AgentHistory()
-# Initialize memory with an initial message from the assistant
+# Initialize history with an initial message from the assistant
initial_message = BaseAgentOutputSchema(chat_message="Hello! How can I assist you today?")
-memory.add_message("assistant", initial_message)
+history.add_message("assistant", initial_message)
# OpenAI client setup using the Instructor library for synchronous operations
client = instructor.from_openai(openai.OpenAI(api_key=API_KEY))
@@ -35,7 +35,7 @@ agent = BaseAgent[BaseAgentInputSchema, BaseAgentOutputSchema](
config=BaseAgentConfig(
client=client,
model="gpt-4o-mini",
- memory=memory,
+ history=history,
)
)
diff --git a/atomic-examples/quickstart/quickstart/1_2_basic_chatbot_async_streaming.py b/atomic-examples/quickstart/quickstart/1_2_basic_chatbot_async_streaming.py
index baa9421..00572ca 100644
--- a/atomic-examples/quickstart/quickstart/1_2_basic_chatbot_async_streaming.py
+++ b/atomic-examples/quickstart/quickstart/1_2_basic_chatbot_async_streaming.py
@@ -21,12 +21,12 @@ if not API_KEY:
# Initialize a Rich Console for pretty console outputs
console = Console()
-# Memory setup
-memory = AgentHistory()
+# History setup
+history = AgentHistory()
-# Initialize memory with an initial message from the assistant
+# Initialize history with an initial message from the assistant
initial_message = BaseAgentOutputSchema(chat_message="Hello! How can I assist you today?")
-memory.add_message("assistant", initial_message)
+history.add_message("assistant", initial_message)
# OpenAI client setup using the Instructor library for async operations
client = instructor.from_openai(openai.AsyncOpenAI(api_key=API_KEY))
@@ -36,7 +36,7 @@ agent = BaseAgent[BaseAgentInputSchema, BaseAgentOutputSchema](
config=BaseAgentConfig(
client=client,
model="gpt-4o-mini",
- memory=memory,
+ history=history,
)
)
diff --git a/atomic-examples/quickstart/quickstart/2_basic_custom_chatbot.py b/atomic-examples/quickstart/quickstart/2_basic_custom_chatbot.py
index a75c3bf..5f939d7 100644
--- a/atomic-examples/quickstart/quickstart/2_basic_custom_chatbot.py
+++ b/atomic-examples/quickstart/quickstart/2_basic_custom_chatbot.py
@@ -21,14 +21,14 @@ if not API_KEY:
# Initialize a Rich Console for pretty console outputs
console = Console()
-# Memory setup
-memory = AgentHistory()
+# History setup
+history = AgentHistory()
-# Initialize memory with an initial message from the assistant
+# Initialize history with an initial message from the assistant
initial_message = BaseAgentOutputSchema(
chat_message="How do you do? What can I do for you? Tell me, pray, what is your need today?"
)
-memory.add_message("assistant", initial_message)
+history.add_message("assistant", initial_message)
# OpenAI client setup using the Instructor library
# Note, you can also set up a client using any other LLM provider, such as Anthropic, Cohere, etc.
@@ -55,7 +55,7 @@ agent = BaseAgent[BaseAgentInputSchema, BaseAgentOutputSchema](
client=client,
model="gpt-4o-mini",
system_prompt_generator=system_prompt_generator,
- memory=memory,
+ history=history,
)
)
diff --git a/atomic-examples/quickstart/quickstart/3_0_basic_custom_chatbot_with_custom_schema.py b/atomic-examples/quickstart/quickstart/3_0_basic_custom_chatbot_with_custom_schema.py
index 90f4d0a..fcde61d 100644
--- a/atomic-examples/quickstart/quickstart/3_0_basic_custom_chatbot_with_custom_schema.py
+++ b/atomic-examples/quickstart/quickstart/3_0_basic_custom_chatbot_with_custom_schema.py
@@ -24,8 +24,8 @@ if not API_KEY:
# Initialize a Rich Console for pretty console outputs
console = Console()
-# Memory setup
-memory = AgentHistory()
+# History setup
+history = AgentHistory()
# Custom output schema
@@ -42,12 +42,12 @@ class CustomOutputSchema(BaseIOSchema):
)
-# Initialize memory with an initial message from the assistant
+# Initialize history with an initial message from the assistant
initial_message = CustomOutputSchema(
chat_message="Hello! How can I assist you today?",
suggested_user_questions=["What can you do?", "Tell me a joke", "Tell me about how you were made"],
)
-memory.add_message("assistant", initial_message)
+history.add_message("assistant", initial_message)
# OpenAI client setup using the Instructor library
client = instructor.from_openai(openai.OpenAI(api_key=API_KEY))
@@ -79,7 +79,7 @@ agent = BaseAgent[BaseAgentInputSchema, CustomOutputSchema](
client=client,
model="gpt-4o-mini",
system_prompt_generator=system_prompt_generator,
- memory=memory,
+ history=history,
)
)
diff --git a/atomic-examples/quickstart/quickstart/3_1_basic_custom_chatbot_with_custom_schema_streaming.py b/atomic-examples/quickstart/quickstart/3_1_basic_custom_chatbot_with_custom_schema_streaming.py
index 09fed7b..5eec19b 100644
--- a/atomic-examples/quickstart/quickstart/3_1_basic_custom_chatbot_with_custom_schema_streaming.py
+++ b/atomic-examples/quickstart/quickstart/3_1_basic_custom_chatbot_with_custom_schema_streaming.py
@@ -25,8 +25,8 @@ if not API_KEY:
# Initialize a Rich Console for pretty console outputs
console = Console()
-# Memory setup
-memory = AgentHistory()
+# History setup
+history = AgentHistory()
# Custom output schema
@@ -43,12 +43,12 @@ class CustomOutputSchema(BaseIOSchema):
)
-# Initialize memory with an initial message from the assistant
+# Initialize history with an initial message from the assistant
initial_message = CustomOutputSchema(
chat_message="Hello! How can I assist you today?",
suggested_user_questions=["What can you do?", "Tell me a joke", "Tell me about how you were made"],
)
-memory.add_message("assistant", initial_message)
+history.add_message("assistant", initial_message)
# OpenAI client setup using the Instructor library for async operations
client = instructor.from_openai(openai.AsyncOpenAI(api_key=API_KEY))
@@ -81,7 +81,7 @@ agent = BaseAgent[BaseAgentInputSchema, CustomOutputSchema](
client=client,
model="gpt-4o-mini",
system_prompt_generator=system_prompt_generator,
- memory=memory,
+ history=history,
)
)
diff --git a/atomic-examples/quickstart/quickstart/4_basic_chatbot_different_providers.py b/atomic-examples/quickstart/quickstart/4_basic_chatbot_different_providers.py
index 12013a3..9043da2 100644
--- a/atomic-examples/quickstart/quickstart/4_basic_chatbot_different_providers.py
+++ b/atomic-examples/quickstart/quickstart/4_basic_chatbot_different_providers.py
@@ -12,12 +12,12 @@ load_dotenv()
# Initialize a Rich Console for pretty console outputs
console = Console()
-# Memory setup
-memory = AgentHistory()
+# History setup
+history = AgentHistory()
-# Initialize memory with an initial message from the assistant
+# Initialize history with an initial message from the assistant
initial_message = BaseAgentOutputSchema(chat_message="Hello! How can I assist you today?")
-memory.add_message("assistant", initial_message)
+history.add_message("assistant", initial_message)
# Function to set up the client based on the chosen provider
@@ -86,7 +86,7 @@ client, model = setup_client(provider)
# Agent setup with specified configuration
agent = BaseAgent[BaseAgentInputSchema, BaseAgentOutputSchema](
- config=BaseAgentConfig(client=client, model=model, memory=memory, model_api_parameters={"max_tokens": 2048})
+ config=BaseAgentConfig(client=client, model=model, history=history, model_api_parameters={"max_tokens": 2048})
)
# Generate the default system prompt for the agent
diff --git a/atomic-examples/quickstart/quickstart/6_0_asynchronous_processing.py b/atomic-examples/quickstart/quickstart/6_0_asynchronous_processing.py
index 217df00..09f2ffc 100644
--- a/atomic-examples/quickstart/quickstart/6_0_asynchronous_processing.py
+++ b/atomic-examples/quickstart/quickstart/6_0_asynchronous_processing.py
@@ -60,7 +60,7 @@ agent = BaseAgent[BaseAgentInputSchema, PersonSchema](
async def exec_agent(message: str):
"""Execute the agent with the provided message."""
user_input = BaseAgentInputSchema(chat_message=message)
- agent.reset_memory()
+ agent.reset_history()
response = await agent.run_async(user_input)
return response
diff --git a/atomic-examples/quickstart/quickstart/6_1_asynchronous_processing_streaming.py b/atomic-examples/quickstart/quickstart/6_1_asynchronous_processing_streaming.py
index ea9e0b3..c8b71f5 100644
--- a/atomic-examples/quickstart/quickstart/6_1_asynchronous_processing_streaming.py
+++ b/atomic-examples/quickstart/quickstart/6_1_asynchronous_processing_streaming.py
@@ -67,7 +67,7 @@ async def exec_agent(message: str, idx: int, progress_dict: dict):
# Acquire the semaphore to limit concurrent executions
async with sem:
user_input = BaseAgentInputSchema(chat_message=message)
- agent.reset_memory()
+ agent.reset_history()
# Track streaming progress
partial_data = {}
diff --git a/atomic-examples/rag-chatbot/rag_chatbot/config.py b/atomic-examples/rag-chatbot/rag_chatbot/config.py
index 4a4d507..17d6e2e 100644
--- a/atomic-examples/rag-chatbot/rag_chatbot/config.py
+++ b/atomic-examples/rag-chatbot/rag_chatbot/config.py
@@ -35,6 +35,6 @@ SIMILARITY_METRIC = "cosine"
# ChromaDB Configuration
CHROMA_PERSIST_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "chroma_db")
-# Memory Configuration
-MEMORY_SIZE = 10 # Number of messages to keep in conversation memory
+# History Configuration
+HISTORY_SIZE = 10 # Number of messages to keep in conversation history
MAX_CONTEXT_LENGTH = 4000 # Maximum length of combined context to send to the model
diff --git a/atomic-examples/web-search-agent/web_search_agent/main.py b/atomic-examples/web-search-agent/web_search_agent/main.py
index 3234c71..7ad36a0 100644
--- a/atomic-examples/web-search-agent/web_search_agent/main.py
+++ b/atomic-examples/web-search-agent/web_search_agent/main.py
@@ -24,8 +24,8 @@ load_dotenv()
# Initialize a Rich Console for pretty console outputs
console = Console()
-# Memory setup
-memory = AgentHistory()
+# History setup
+history = AgentHistory()
# Initialize the SearXNGSearchTool
search_tool = SearXNGSearchTool(config=SearXNGSearchToolConfig(base_url=os.getenv("SEARXNG_BASE_URL"), max_results=5))
diff --git a/docs/api/agents.md b/docs/api/agents.md
index 427f86b..5d0386a 100644
--- a/docs/api/agents.md
+++ b/docs/api/agents.md
@@ -99,11 +99,11 @@ class CustomOutputSchema(BaseIOSchema):
## Base Agent
-The `BaseAgent` class is the foundation for building AI agents in the Atomic Agents framework. It handles chat interactions, memory management, system prompts, and responses from language models.
+The `BaseAgent` class is the foundation for building AI agents in the Atomic Agents framework. It handles chat interactions, history management, system prompts, and responses from language models.
```python
from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig
-from atomic_agents.lib.components.agent_memory import AgentHistory
+from atomic_agents.lib.components.agent_history import AgentHistory
from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator
# Create agent with basic configuration
@@ -111,7 +111,7 @@ agent = BaseAgent[BaseAgentInputSchema, BaseAgentOutputSchema](
config=BaseAgentConfig(
client=instructor.from_openai(OpenAI()),
model="gpt-4-turbo-preview",
- memory=AgentHistory(),
+ history=AgentHistory(),
system_prompt_generator=SystemPromptGenerator()
)
)
@@ -132,7 +132,7 @@ The `BaseAgentConfig` class provides configuration options:
class BaseAgentConfig:
client: instructor.Instructor # Client for interacting with the language model
model: str = "gpt-4-turbo-preview" # Model to use
- memory: Optional[AgentHistory] = None # Memory component
+ history: Optional[AgentHistory] = None # History component
system_prompt_generator: Optional[SystemPromptGenerator] = None # Prompt generator
input_schema: Optional[Type[BaseModel]] = None # Custom input schema
output_schema: Optional[Type[BaseModel]] = None # Custom output schema
@@ -164,7 +164,7 @@ class BaseAgentOutputSchema(BaseIOSchema):
- `run(user_input: Optional[BaseIOSchema] = None) -> BaseIOSchema`: Process user input and get response
- `run_async(user_input: Optional[BaseIOSchema] = None)`: Stream responses asynchronously
- `get_response(response_model=None) -> Type[BaseModel]`: Get direct model response
-- `reset_memory()`: Reset memory to initial state
+- `reset_history()`: Reset history to initial state
- `get_context_provider(provider_name: str)`: Get a registered context provider
- `register_context_provider(provider_name: str, provider: SystemPromptContextProviderBase)`: Register a new context provider
- `unregister_context_provider(provider_name: str)`: Remove a context provider
@@ -205,20 +205,20 @@ async def chat():
print(partial_response.chat_message)
```
-### Memory Management
+### History Management
The agent automatically manages conversation history through the `AgentHistory` component:
```python
-# Access memory
-history = agent.memory.get_history()
+# Access history
+history = agent.history.get_history()
# Reset to initial state
-agent.reset_memory()
+agent.reset_history()
-# Save/load memory state
-serialized = agent.memory.dump()
-agent.memory.load(serialized)
+# Save/load history state
+serialized = agent.history.dump()
+agent.history.load(serialized)
```
### Custom Schemas
diff --git a/docs/api/components.md b/docs/api/components.md
index 7d68180..be5a175 100644
--- a/docs/api/components.md
+++ b/docs/api/components.md
@@ -1,39 +1,39 @@
# Components
-## Agent Memory
+## Agent History
The `AgentHistory` class manages conversation history and state for AI agents:
```python
-from atomic_agents.lib.components.agent_memory import AgentHistory
+from atomic_agents.lib.components.agent_history import AgentHistory
from atomic_agents.lib.base.base_io_schema import BaseIOSchema
-# Initialize memory with optional max messages
-memory = AgentHistory(max_messages=10)
+# Initialize history with optional max messages
+history = AgentHistory(max_messages=10)
# Add messages
-memory.add_message(
+history.add_message(
role="user",
content=BaseIOSchema(...)
)
# Initialize a new turn
-memory.initialize_turn()
-turn_id = memory.get_current_turn_id()
+history.initialize_turn()
+turn_id = history.get_current_turn_id()
# Access history
-history = memory.get_history()
+history = history.get_history()
-# Manage memory
-memory.get_message_count() # Get number of messages
-memory.delete_turn_id(turn_id) # Delete messages by turn
+# Manage history
+history.get_message_count() # Get number of messages
+history.delete_turn_id(turn_id) # Delete messages by turn
# Persistence
-serialized = memory.dump() # Save to string
-memory.load(serialized) # Load from string
+serialized = history.dump() # Save to string
+history.load(serialized) # Load from string
# Create copy
-new_memory = memory.copy()
+new_history = history.copy()
```
Key features:
@@ -41,12 +41,12 @@ Key features:
- Turn-based conversation tracking
- Support for multimodal content (images, etc.)
- Serialization and persistence
-- Memory size management
+- History size management
- Deep copy functionality
### Message Structure
-Messages in memory are structured as:
+Messages in history are structured as:
```python
class Message(BaseModel):
@@ -57,11 +57,11 @@ class Message(BaseModel):
### Multimodal Support
-The memory system automatically handles multimodal content:
+The history system automatically handles multimodal content:
```python
# For content with images
-history = memory.get_history()
+history = history.get_history()
for message in history:
if isinstance(message.content, list):
text_content = message.content[0] # JSON string
@@ -203,7 +203,7 @@ Key features:
For full API details:
```{eval-rst}
-.. automodule:: atomic_agents.lib.components.agent_memory
+.. automodule:: atomic_agents.lib.components.agent_history
:members:
:undoc-members:
:show-inheritance:
diff --git a/docs/api/index.md b/docs/api/index.md
index 0fa7572..a55e663 100644
--- a/docs/api/index.md
+++ b/docs/api/index.md
@@ -35,7 +35,7 @@ The components module contains essential building blocks:
- Turn-based conversation tracking
- Multimodal content
- Serialization and persistence
- - Memory size management
+ - History size management
- `SystemPromptGenerator`: Creates structured system prompts with:
- Background information
diff --git a/docs/examples/index.md b/docs/examples/index.md
index a2770d1..ca44bc7 100644
--- a/docs/examples/index.md
+++ b/docs/examples/index.md
@@ -6,7 +6,7 @@ This section contains detailed examples of using Atomic Agents in various scenar
Simple examples to get started with the framework:
-- Basic chatbot with memory
+- Basic chatbot with history
- Custom chatbot with personality
- Streaming responses
- Custom input/output schemas
diff --git a/docs/guides/index.md b/docs/guides/index.md
index a4cb55c..1ec59e0 100644
--- a/docs/guides/index.md
+++ b/docs/guides/index.md
@@ -22,7 +22,7 @@ The framework supports various implementation patterns and use cases:
- Streaming responses
- Custom response schemas
- Suggested follow-up questions
-- Memory management and context retention
+- History management and context retention
- Multi-turn conversations
### RAG Systems
diff --git a/docs/guides/quickstart.md b/docs/guides/quickstart.md
index d6cc8db..f202d39 100644
--- a/docs/guides/quickstart.md
+++ b/docs/guides/quickstart.md
@@ -24,18 +24,18 @@ import os
import instructor
import openai
from rich.console import Console
-from atomic_agents.lib.components.agent_memory import AgentHistory
+from atomic_agents.lib.components.agent_history import AgentHistory
from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseAgentInputSchema, BaseAgentOutputSchema
# Initialize console for pretty outputs
console = Console()
-# Memory setup
-memory = AgentHistory()
+# History setup
+history = AgentHistory()
-# Initialize memory with an initial message from the assistant
+# Initialize history with an initial message from the assistant
initial_message = BaseAgentOutputSchema(chat_message="Hello! How can I assist you today?")
-memory.add_message("assistant", initial_message)
+history.add_message("assistant", initial_message)
# OpenAI client setup using the Instructor library
client = instructor.from_openai(openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY")))
@@ -45,7 +45,7 @@ agent = BaseAgent[BaseAgentInputSchema, BaseAgentOutputSchema](
config=BaseAgentConfig(
client=client,
model="gpt-4o-mini", # Using the latest model
- memory=memory,
+ history=history,
model_api_parameters={"max_tokens": 2048}
)
)
@@ -80,18 +80,18 @@ from rich.console import Console
from rich.panel import Panel
from rich.text import Text
from rich.live import Live
-from atomic_agents.lib.components.agent_memory import AgentHistory
+from atomic_agents.lib.components.agent_history import AgentHistory
from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseAgentInputSchema, BaseAgentOutputSchema
# Initialize console for pretty outputs
console = Console()
-# Memory setup
-memory = AgentHistory()
+# History setup
+history = AgentHistory()
-# Initialize memory with an initial message from the assistant
+# Initialize history with an initial message from the assistant
initial_message = BaseAgentOutputSchema(chat_message="Hello! How can I assist you today?")
-memory.add_message("assistant", initial_message)
+history.add_message("assistant", initial_message)
# OpenAI client setup using the Instructor library for async operations
client = instructor.from_openai(openai.AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY")))
@@ -101,7 +101,7 @@ agent = BaseAgent(
config=BaseAgentConfig(
client=client,
model="gpt-4o-mini",
- memory=memory,
+ history=history,
)
)
@@ -152,15 +152,15 @@ from rich.console import Console
from typing import List
from pydantic import Field
from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator
-from atomic_agents.lib.components.agent_memory import AgentHistory
+from atomic_agents.lib.components.agent_history import AgentHistory
from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseAgentInputSchema
from atomic_agents.lib.base.base_io_schema import BaseIOSchema
# Initialize console for pretty outputs
console = Console()
-# Memory setup
-memory = AgentHistory()
+# history setup
+history = AgentHistory()
# Custom output schema
class CustomOutputSchema(BaseIOSchema):
@@ -175,12 +175,12 @@ class CustomOutputSchema(BaseIOSchema):
description="A list of suggested follow-up questions the user could ask the agent.",
)
-# Initialize memory with an initial message from the assistant
+# Initialize history with an initial message from the assistant
initial_message = CustomOutputSchema(
chat_message="Hello! How can I assist you today?",
suggested_user_questions=["What can you do?", "Tell me a joke", "Tell me about how you were made"],
)
-memory.add_message("assistant", initial_message)
+history.add_message("assistant", initial_message)
# OpenAI client setup using the Instructor library
client = instructor.from_openai(openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY")))
@@ -209,7 +209,7 @@ agent = BaseAgent[BaseAgentInputSchema, BaseAgentOutputSchema](
client=client,
model="gpt-4o-mini",
system_prompt_generator=system_prompt_generator,
- memory=memory,
+ history=history,
output_schema=CustomOutputSchema,
)
)
@@ -258,7 +258,7 @@ import os
import instructor
from rich.console import Console
from rich.text import Text
-from atomic_agents.lib.components.agent_memory import AgentHistory
+from atomic_agents.lib.components.agent_history import AgentHistory
from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseAgentInputSchema, BaseAgentOutputSchema
from dotenv import load_dotenv
@@ -267,12 +267,12 @@ load_dotenv()
# Initialize console for pretty outputs
console = Console()
-# Memory setup
-memory = AgentHistory()
+# history setup
+history = AgentHistory()
-# Initialize memory with an initial message from the assistant
+# Initialize history with an initial message from the assistant
initial_message = BaseAgentOutputSchema(chat_message="Hello! How can I assist you today?")
-memory.add_message("assistant", initial_message)
+history.add_message("assistant", initial_message)
# Function to set up the client based on the chosen provider
def setup_client(provider):
@@ -347,7 +347,7 @@ agent = BaseAgent[BaseAgentInputSchema, BaseAgentOutputSchema](
config=BaseAgentConfig(
client=client,
model=model,
- memory=memory,
+ history=history,
model_api_parameters={"max_tokens": 2048}
)
)
@@ -406,4 +406,4 @@ After trying these examples, you can:
## Explore More Examples
-For more advanced usage and examples, please check out the [Atomic Agents examples on GitHub](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples). These examples demonstrate various capabilities of the framework including custom schemas, advanced memory usage, tool integration, and more.
+For more advanced usage and examples, please check out the [Atomic Agents examples on GitHub](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples). These examples demonstrate various capabilities of the framework including custom schemas, advanced history usage, tool integration, and more.
diff --git a/docs/index.md b/docs/index.md
index a5fae3a..b726f4d 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -61,7 +61,7 @@ Here's a glimpse of how easy it is to create an agent:
```python
import instructor
import openai
-from atomic_agents.lib.components.agent_memory import AgentHistory
+from atomic_agents.lib.components.agent_history import AgentHistory
from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseAgentInputSchema, BaseAgentOutputSchema
@@ -69,8 +69,8 @@ from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseAgen
# os.environ["OPENAI_API_KEY"] = "your-api-key"
# or pass it to the client: openai.OpenAI(api_key="your-api-key")
-# Initialize agent with memory
-memory = AgentHistory()
+# Initialize agent with history
+history = AgentHistory()
# Set up client with your preferred provider
client = instructor.from_openai(openai.OpenAI()) # Pass your API key here if not in environment
@@ -80,7 +80,7 @@ agent = BaseAgent[BaseAgentInputSchema, BaseAgentOutputSchema](
config=BaseAgentConfig(
client=client,
model="gpt-4o-mini", # Use your provider's model
- memory=memory
+ history=history
)
)