Skip to content

Building AI agents, atomically

- Deleted `ToolInterfaceAgent` class and its associated tests. - Refactored `AgentMemory` class: - Removed unnecessary fields related to tool calls. - Simplified message handling and serialization methods. - Enhanced `dump` and `load` methods to support new content types. - Added capability to manage complex schemas in memory operations. - Updated tests for `AgentMemory` to cover new serialization functionality and ensure correct behavior with complex schemas. - Updated test assertions to match recent changes in the memory structure and message handling. - Improved example code and renamed several demo scripts for clarity.

KennyVaneetvelde0645c36a7afd
diff --git a/atomic-agents/.coveragerc b/atomic-agents/.coveragerc
new file mode 100644
index 0000000..6fa6eb9
--- /dev/null
+++ b/atomic-agents/.coveragerc
@@ -0,0 +1,12 @@
+[report]
+show_missing=true
+exclude_lines =
+ @abstractmethod
+ @abc.abstractmethod
+exclude_also =
+ if __name__ == .__main__.:
+
+[run]
+omit =
+ */__init__.py
+ */tests/*
diff --git a/atomic-agents/atomic_agents/agents/tool_interface_agent.py b/atomic-agents/atomic_agents/agents/tool_interface_agent.py
deleted file mode 100644
index a6b36c6..0000000
--- a/atomic-agents/atomic_agents/agents/tool_interface_agent.py
+++ /dev/null
@@ -1,101 +0,0 @@
-import json
-
-from pydantic import Field, create_model
-
-from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig
-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator
-from atomic_agents.lib.base.base_tool import BaseTool
-from atomic_agents.lib.utils.format_tool_message import format_tool_message
-
-
-class ToolInterfaceAgentConfig(BaseAgentConfig):
- tool_instance: BaseTool
-
-
-class ToolInterfaceAgent(BaseAgent):
- """
- A specialized chat agent designed to interact with a specific tool.
-
- This agent extends the BaseAgent to include functionality for interacting with a tool instance.
- It generates system prompts, handles tool input and output, and processes the tool output.
-
- Attributes:
- tool_instance: The instance of the tool this agent will interact with.
- """
-
- def __init__(self, config: ToolInterfaceAgentConfig):
- """
- Initializes the ToolInterfaceAgent.
-
- Args:
- config (ToolInterfaceAgentConfig): Configuration for the tool interface agent.
- """
- super().__init__(config=config)
-
- self.tool_instance = config.tool_instance
-
- # Create a new model with the updated schema
- self.input_schema = create_model(
- self.tool_instance.__class__.__name__,
- tool_input=(
- str,
- Field(
- ...,
- description=(
- f"{self.tool_instance.__class__.__name__} tool input. " "Presented as a single question or instruction"
- ),
- alias=f"tool_input_{self.tool_instance.__class__.__name__}",
- ),
- ),
- __base__=BaseIOSchema,
- __doc__=self.tool_instance.tool_description,
- )
-
- # Set the __name__ attribute of the new model
- self.input_schema.__name__ = self.tool_instance.__class__.__name__
-
- output_instructions = [
- "Make sure the tool call will maximize the utility of the tool in the context of the user input.",
- "Process the output of the tool into a human readable format and use it to respond to the user input.",
- ]
-
- self.system_prompt_generator = SystemPromptGenerator(
- background=[
- f"This AI agent is designed to interact with the {self.tool_instance.tool_name} tool.",
- f"Tool description: {self.tool_instance.tool_description}",
- ],
- steps=[
- "Get the user input.",
- "Convert the input to the proper parameters to call the tool.",
- "Call the tool with the parameters.",
- "Process the tool output and respond to the user",
- ],
- output_instructions=output_instructions,
- )
-
- def get_response(self, response_model=None):
- """
- Handles obtaining and processing the response from the tool.
-
- This method gets the response from the tool, formats the tool input, adds it to memory,
- runs the tool, processes the tool output, and returns the processed response.
-
- Args:
- response_model: Ignored in this implementation, but included for compatibility with BaseAgent.
-
- Returns:
- BaseModel: The processed response.
- """
- tool_input = super().get_response(response_model=self.tool_instance.input_schema)
- formatted_tool_input = format_tool_message(tool_input)
-
- self.memory.add_message("assistant", "TOOL CALL: " + json.dumps(formatted_tool_input))
- tool_output = self.tool_instance.run(tool_input)
- self.memory.add_message("assistant", "TOOL RESPONSE: " + tool_output.model_dump_json())
-
- self.memory.add_message(
- "assistant",
- "I will now formulate a response for the user based on the tool output.",
- )
- response = super().get_response(response_model=response_model or self.output_schema)
- return response
diff --git a/atomic-agents/atomic_agents/lib/components/agent_memory.py b/atomic-agents/atomic_agents/lib/components/agent_memory.py
index a26c21d..3d5cabb 100644
--- a/atomic-agents/atomic_agents/lib/components/agent_memory.py
+++ b/atomic-agents/atomic_agents/lib/components/agent_memory.py
@@ -1,7 +1,7 @@
import uuid
import json
-from typing import Dict, List, Optional, Union
-from pydantic import BaseModel, ValidationError
+from typing import Dict, List, Optional, Type
+from pydantic import BaseModel, Field
from atomic_agents.lib.base.base_io_schema import BaseIOSchema
@@ -12,16 +12,12 @@ class Message(BaseModel):
Attributes:
role (str): The role of the message sender (e.g., 'user', 'system', 'tool').
- content (Union[str, BaseIOSchema]): The content of the message.
- tool_calls (Optional[List[Dict]]): Optional list of tool call messages.
- tool_call_id (Optional[str]): Optional unique identifier for the tool call.
+ content (BaseIOSchema): The content of the message.
turn_id (Optional[str]): Unique identifier for the turn this message belongs to.
"""
role: str
- content: Union[str, BaseIOSchema]
- tool_calls: Optional[List[Dict]] = None
- tool_call_id: Optional[str] = None
+ content: BaseIOSchema
turn_id: Optional[str] = None
@@ -55,29 +51,19 @@ class AgentMemory:
def add_message(
self,
role: str,
- content: Union[str, BaseIOSchema],
- tool_message: Optional[Dict] = None,
- tool_id: Optional[str] = None,
+ content: BaseIOSchema,
) -> None:
"""
Adds a message to the chat history and manages overflow.
Args:
role (str): The role of the message sender.
- content (Union[str, BaseIOSchema]): The content of the message.
- tool_message (Optional[Dict]): Optional tool message to be included.
- tool_id (Optional[str]): Optional unique identifier for the tool call.
+ content (BaseIOSchema): The content of the message.
"""
if self.current_turn_id is None:
self.initialize_turn()
message = Message(role=role, content=content, turn_id=self.current_turn_id)
- if tool_message:
- message.tool_calls = [tool_message]
- message.tool_call_id = tool_id or tool_message.get("id")
- elif role == "tool":
- message.tool_call_id = tool_id
-
self.history.append(message)
self._manage_overflow()
@@ -89,20 +75,6 @@ class AgentMemory:
while len(self.history) > self.max_messages:
self.history.pop(0)
- def _serialize_content(self, content: Union[str, BaseIOSchema]) -> str:
- """
- Serializes the content of a message to a JSON string if it's a BaseIOSchema instance.
-
- Args:
- content (Union[str, BaseIOSchema]): The content to serialize.
-
- Returns:
- str: The serialized content.
- """
- if isinstance(content, BaseIOSchema):
- return json.dumps(content.model_dump())
- return content
-
def get_history(self) -> List[Dict]:
"""
Retrieves the chat history, filtering out unnecessary fields and serializing content.
@@ -113,53 +85,11 @@ class AgentMemory:
return [
{
"role": message.role,
- "content": self._serialize_content(message.content),
- **({"tool_calls": message.tool_calls} if message.tool_calls else {}),
- **({"tool_call_id": message.tool_call_id} if message.tool_call_id else {}),
- }
- for message in self.history
- ]
-
- def dump(self) -> List[Dict]:
- """
- Converts the chat history to a list of dictionaries, including turn_id and serializing content.
-
- Returns:
- List[Dict]: The list of messages as dictionaries, including turn_id.
- """
- return [
- {
- **message.model_dump(exclude_none=True),
- "content": self._serialize_content(message.content),
+ "content": json.dumps(message.content.model_dump()),
}
for message in self.history
]
- def load(self, dict_list: List[Dict]) -> None:
- """
- Loads the chat history from a list of dictionaries using Pydantic's parsing.
-
- Args:
- dict_list (List[Dict]): The list of messages as dictionaries.
- """
- self.history = []
- for message_dict in dict_list:
- try:
- content = message_dict["content"]
- if isinstance(content, dict):
- # Assume it's a BaseIOSchema subclass, but we don't know which one
- # For now, we'll keep it as a dict, but in practice, you might want to
- # implement a way to determine the correct BaseIOSchema subclass
- message_dict["content"] = content
- message = Message.model_validate(message_dict)
- self.history.append(message)
- except ValidationError as e:
- print(f"Error parsing message: {e}")
- continue
- # Set the current_turn_id to the last message's turn_id if available
- if self.history:
- self.current_turn_id = self.history[-1].turn_id
-
def copy(self) -> "AgentMemory":
"""
Creates a copy of the chat memory.
@@ -189,3 +119,182 @@ class AgentMemory:
int: The number of messages.
"""
return len(self.history)
+
+ def dump(self) -> str:
+ """
+ Serializes the entire AgentMemory instance to a JSON string.
+
+ Returns:
+ str: A JSON string representation of the AgentMemory.
+ """
+ serialized_history = []
+ for message in self.history:
+ content_class = message.content.__class__
+ serialized_message = {
+ "role": message.role,
+ "content": {
+ "class_name": f"{content_class.__module__}.{content_class.__name__}",
+ "data": message.content.model_dump(),
+ },
+ "turn_id": message.turn_id,
+ }
+ serialized_history.append(serialized_message)
+
+ memory_data = {
+ "history": serialized_history,
+ "max_messages": self.max_messages,
+ "current_turn_id": self.current_turn_id,
+ }
+ return json.dumps(memory_data)
+
+ def load(self, serialized_data: str) -> None:
+ """
+ Deserializes a JSON string and loads it into the AgentMemory instance.
+
+ Args:
+ serialized_data (str): A JSON string representation of the AgentMemory.
+
+ Raises:
+ ValueError: If the serialized data is invalid or cannot be deserialized.
+ """
+ try:
+ memory_data = json.loads(serialized_data)
+ self.history = []
+ self.max_messages = memory_data["max_messages"]
+ self.current_turn_id = memory_data["current_turn_id"]
+
+ for message_data in memory_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"])
+
+ message = Message(role=message_data["role"], content=content_instance, turn_id=message_data["turn_id"])
+ self.history.append(message)
+ except (json.JSONDecodeError, KeyError, AttributeError, TypeError) as e:
+ raise ValueError(f"Invalid serialized data: {e}")
+
+ @staticmethod
+ def _get_class_from_string(class_string: str) -> Type[BaseIOSchema]:
+ """
+ Retrieves a class object from its string representation.
+
+ Args:
+ class_string (str): The fully qualified class name.
+
+ Returns:
+ Type[BaseIOSchema]: The class object.
+
+ Raises:
+ AttributeError: If the class cannot be found.
+ """
+ module_name, class_name = class_string.rsplit(".", 1)
+ module = __import__(module_name, fromlist=[class_name])
+ return getattr(module, class_name)
+
+
+if __name__ == "__main__":
+ from typing import List as TypeList, Dict as TypeDict
+
+ # Define complex test schemas
+ class NestedSchema(BaseIOSchema):
+ """A nested schema for testing"""
+
+ nested_field: str = Field(..., description="A nested field")
+ nested_int: int = Field(..., description="A nested integer")
+
+ class ComplexInputSchema(BaseIOSchema):
+ """Complex Input Schema"""
+
+ text_field: str = Field(..., description="A text field")
+ number_field: float = Field(..., description="A number field")
+ list_field: TypeList[str] = Field(..., description="A list of strings")
+ nested_field: NestedSchema = Field(..., description="A nested schema")
+
+ class ComplexOutputSchema(BaseIOSchema):
+ """Complex Output Schema"""
+
+ response_text: str = Field(..., description="A response text")
+ calculated_value: int = Field(..., description="A calculated value")
+ data_dict: TypeDict[str, NestedSchema] = Field(..., description="A dictionary of nested schemas")
+
+ # Create and populate the original memory with complex data
+ original_memory = AgentMemory(max_messages=10)
+
+ # Add a complex input message
+ original_memory.add_message(
+ "user",
+ ComplexInputSchema(
+ text_field="Hello, this is a complex input",
+ number_field=3.14159,
+ list_field=["item1", "item2", "item3"],
+ nested_field=NestedSchema(nested_field="Nested input", nested_int=42),
+ ),
+ )
+
+ # Add a complex output message
+ original_memory.add_message(
+ "assistant",
+ ComplexOutputSchema(
+ response_text="This is a complex response",
+ calculated_value=100,
+ data_dict={
+ "key1": NestedSchema(nested_field="Nested output 1", nested_int=10),
+ "key2": NestedSchema(nested_field="Nested output 2", nested_int=20),
+ },
+ ),
+ )
+
+ # Add another input message
+ original_memory.add_message(
+ "user",
+ ComplexInputSchema(
+ text_field="Another complex input",
+ number_field=2.71828,
+ list_field=["apple", "banana", "cherry"],
+ nested_field=NestedSchema(nested_field="More nested input", nested_int=99),
+ ),
+ )
+
+ # Dump the memory
+ dumped_data = original_memory.dump()
+ print("Dumped data:")
+ print(dumped_data)
+
+ # Create a new memory and load the dumped data
+ loaded_memory = AgentMemory()
+ loaded_memory.load(dumped_data)
+
+ # Verify that the loaded memory matches the original
+ print("\nOriginal memory dump == Loaded memory dump:", original_memory.dump() == loaded_memory.dump())
+
+ # Print detailed information about the loaded memory
+ print("\nLoaded memory details:")
+ for i, message in enumerate(loaded_memory.history):
+ print(f"\nMessage {i + 1}:")
+ print(f"Role: {message.role}")
+ print(f"Turn ID: {message.turn_id}")
+ print(f"Content type: {type(message.content).__name__}")
+ print("Content:")
+ for field, value in message.content.model_dump().items():
+ print(f" {field}: {value}")
+
+ # Verify that the loaded memory can be used to add new messages
+ loaded_memory.add_message(
+ "assistant",
+ ComplexOutputSchema(
+ response_text="This is a new message added to the loaded memory",
+ calculated_value=200,
+ data_dict={"key3": NestedSchema(nested_field="New nested output", nested_int=30)},
+ ),
+ )
+
+ print("\nAdded a new message to the loaded memory.")
+ print(f"Total messages in loaded memory: {loaded_memory.get_message_count()}")
+
+ # 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("Last message content:")
+ last_message = loaded_memory.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 c16a37b..ad95edf 100644
--- a/atomic-agents/tests/agents/test_base_agent.py
+++ b/atomic-agents/tests/agents/test_base_agent.py
@@ -85,22 +85,18 @@ def test_get_response(agent, mock_instructor, mock_memory, mock_system_prompt_ge
)
-def test_run(agent):
+def test_run(agent, mock_memory):
mock_input = BaseAgentInputSchema(chat_message="Test input")
mock_output = BaseAgentOutputSchema(chat_message="Test output")
- agent._init_run = Mock()
- agent._pre_run = Mock()
- agent._post_run = Mock()
agent.get_response = Mock(return_value=mock_output)
result = agent.run(mock_input)
assert result == mock_output
- agent._init_run.assert_called_once_with(mock_input)
- agent._pre_run.assert_called_once()
- agent.get_response.assert_called_once()
- agent._post_run.assert_called_once_with(mock_output)
+ assert agent.current_user_input == mock_input
+
+ mock_memory.add_message.assert_has_calls([call("user", mock_input), call("assistant", mock_output)])
def test_get_context_provider(agent, mock_system_prompt_generator):
@@ -173,7 +169,7 @@ def test_run(agent, mock_memory):
assert result == mock_output
assert agent.current_user_input == mock_input
- mock_memory.add_message.assert_has_calls([call("user", str(mock_input)), call("assistant", str(mock_output))])
+ mock_memory.add_message.assert_has_calls([call("user", mock_input), call("assistant", mock_output)])
def test_base_io_schema_empty_docstring():
diff --git a/atomic-agents/tests/agents/test_tool_interface_agent.py b/atomic-agents/tests/agents/test_tool_interface_agent.py
deleted file mode 100644
index 9ba6641..0000000
--- a/atomic-agents/tests/agents/test_tool_interface_agent.py
+++ /dev/null
@@ -1,110 +0,0 @@
-import pytest
-from unittest.mock import Mock, patch
-from pydantic import Field
-import instructor
-
-from atomic_agents.agents.tool_interface_agent import ToolInterfaceAgent, ToolInterfaceAgentConfig
-from atomic_agents.lib.base.base_tool import BaseTool
-from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgentOutputSchema
-
-
-class MockTool(BaseTool):
- class InputSchema(BaseIOSchema):
- """Mock input schema"""
-
- query: str = Field(..., description="The query to process")
-
- class OutputSchema(BaseIOSchema):
- """Mock output schema"""
-
- result: str = Field(..., description="The result of the tool operation")
-
- input_schema = InputSchema
- output_schema = OutputSchema
-
- def run(self, params: InputSchema) -> OutputSchema:
- return self.OutputSchema(result=f"Processed: {params.query}")
-
-
-def mock_tool():
- return MockTool()
-
-
-def mock_instructor():
- mock = Mock(spec=instructor.Instructor)
- mock.chat.completions.create = Mock()
- return mock
-
-
-def tool_interface_agent(mock_tool, mock_instructor):
- config = ToolInterfaceAgentConfig(client=mock_instructor, model="gpt-4o-mini", tool_instance=mock_tool)
- return ToolInterfaceAgent(config)
-
-
-def test_tool_interface_agent_initialization(tool_interface_agent, mock_tool):
- assert tool_interface_agent.tool_instance == mock_tool
- assert tool_interface_agent.input_schema.__name__ == "MockTool"
- assert issubclass(tool_interface_agent.input_schema, BaseIOSchema)
- assert tool_interface_agent.output_schema == BaseAgentOutputSchema
-
-
-def test_tool_interface_agent_input_schema(tool_interface_agent):
- assert "tool_input" in tool_interface_agent.input_schema.model_fields
- assert tool_interface_agent.input_schema.model_fields["tool_input"].alias == "tool_input_MockTool"
-
-
-@patch("atomic_agents.agents.base_agent.BaseAgent.get_response")
-@patch("atomic_agents.lib.utils.format_tool_message.format_tool_message")
-def test_tool_interface_agent_get_response(mock_format_tool_message, mock_get_response, tool_interface_agent):
- mock_tool_input = tool_interface_agent.input_schema(tool_input_MockTool="Test query")
- mock_tool_output = MockTool.OutputSchema(result="Mocked result")
- mock_final_response = Mock()
-
- mock_get_response.side_effect = [mock_tool_input, mock_final_response]
- tool_interface_agent.tool_instance.run = Mock(return_value=mock_tool_output)
- mock_format_tool_message.return_value = {
- "id": "test_id",
- "type": "function",
- "function": {"name": "MockTool", "arguments": "{}"},
- }
-
- response = tool_interface_agent.get_response()
-
- tool_interface_agent.tool_instance.run.assert_called_once_with(mock_tool_input)
- assert mock_get_response.call_count == 2
- assert response == mock_final_response
-
-
-@patch("atomic_agents.agents.base_agent.BaseAgent.get_response")
-@patch("atomic_agents.lib.utils.format_tool_message.format_tool_message")
-def test_tool_interface_agent_memory_updates(mock_format_tool_message, mock_get_response, tool_interface_agent):
- mock_input = tool_interface_agent.input_schema(tool_input_MockTool="Test query")
- mock_tool_output = MockTool.OutputSchema(result="Mocked result")
- mock_final_response = BaseAgentOutputSchema(chat_message="Test response")
-
- mock_get_response.side_effect = [mock_input, mock_final_response]
- tool_interface_agent.tool_instance.run = Mock(return_value=mock_tool_output)
- mock_format_tool_message.return_value = {
- "id": "test_id",
- "type": "function",
- "function": {"name": "MockTool", "arguments": "{}"},
- }
-
- tool_interface_agent.run(mock_input)
-
- history = tool_interface_agent.memory.get_history()
-
- # Check for TOOL CALL message
- assert any("TOOL CALL:" in msg["content"] for msg in history if isinstance(msg["content"], str))
-
- # Check for TOOL RESPONSE message
- assert any("TOOL RESPONSE:" in msg["content"] for msg in history if isinstance(msg["content"], str))
-
- # Check if the mocked result is in the memory
- assert any("Mocked result" in msg["content"] for msg in history if isinstance(msg["content"], str))
-
- # Assert that at least 3 messages were added (TOOL CALL, TOOL RESPONSE, and possibly the final response)
- assert len(history) >= 3
diff --git a/atomic-agents/tests/lib/components/test_agent_memory.py b/atomic-agents/tests/lib/components/test_agent_memory.py
index 9dd784f..ff50e31 100644
--- a/atomic-agents/tests/lib/components/test_agent_memory.py
+++ b/atomic-agents/tests/lib/components/test_agent_memory.py
@@ -1,147 +1,249 @@
import pytest
+import json
+from typing import List, Dict
+from pydantic import BaseModel, Field
from atomic_agents.lib.components.agent_memory import AgentMemory, Message
+from atomic_agents.lib.base.base_io_schema import BaseIOSchema
-def agent_memory():
- return AgentMemory(max_messages=5)
+class TestInputSchema(BaseIOSchema):
+ """Test Input Schema"""
+ test_field: str = Field(..., description="A test field")
-def test_initialization(agent_memory):
- assert agent_memory.history == []
- assert agent_memory.max_messages == 5
+class TestOutputSchema(BaseIOSchema):
+ """Test Output Schema"""
-def test_add_message(agent_memory):
- agent_memory.add_message("user", "Hello")
- assert len(agent_memory.history) == 1
- assert agent_memory.history[0].role == "user"
- assert agent_memory.history[0].content == "Hello"
+ test_field: str = Field(..., description="A test field")
-def test_add_message_with_tool(agent_memory):
- tool_message = {
- "id": "weather_1",
- "type": "function",
- "function": {"name": "get_weather", "arguments": '{"location": "New York"}'},
- }
- agent_memory.add_message("assistant", "Checking weather", tool_message=tool_message)
- assert len(agent_memory.history) == 1
- assert agent_memory.history[0].role == "assistant"
- assert agent_memory.history[0].content == "Checking weather"
- assert agent_memory.history[0].tool_calls == [tool_message]
- assert agent_memory.history[0].tool_call_id == "weather_1"
+class TestNestedSchema(BaseIOSchema):
+ """Test Nested Schema"""
+ nested_field: str = Field(..., description="A nested field")
+ nested_int: int = Field(..., description="A nested integer")
-def test_add_tool_response(agent_memory):
- agent_memory.add_message("tool", "Weather is sunny", tool_id="weather_1")
- assert len(agent_memory.history) == 1
- assert agent_memory.history[0].role == "tool"
- assert agent_memory.history[0].content == "Weather is sunny"
- assert agent_memory.history[0].tool_call_id == "weather_1"
+class TestComplexInputSchema(BaseIOSchema):
+ """Test Complex Input Schema"""
-def test_manage_overflow(agent_memory):
- for i in range(7):
- agent_memory.add_message("user", f"Message {i}")
- assert len(agent_memory.history) == 5
- assert agent_memory.history[0].content == "Message 2"
- assert agent_memory.history[-1].content == "Message 6"
+ text_field: str = Field(..., description="A text field")
+ number_field: float = Field(..., description="A number field")
+ list_field: List[str] = Field(..., description="A list of strings")
+ nested_field: TestNestedSchema = Field(..., description="A nested schema")
-def test_get_history(agent_memory):
- agent_memory.add_message("user", "Hello")
- agent_memory.add_message("assistant", "Hi there")
- history = agent_memory.get_history()
- assert len(history) == 2
- assert history[0]["role"] == "user"
- assert history[0]["content"] == "Hello"
- assert history[1]["role"] == "assistant"
- assert history[1]["content"] == "Hi there"
- assert "turn_id" not in history[0]
- assert "turn_id" not in history[1]
+class TestComplexOutputSchema(BaseIOSchema):
+ """Test Complex Output Schema"""
+
+ response_text: str = Field(..., description="A response text")
+ calculated_value: int = Field(..., description="A calculated value")
+ data_dict: Dict[str, TestNestedSchema] = Field(..., description="A dictionary of nested schemas")
-def test_get_current_turn_id(agent_memory):
- # Initially, current_turn_id should be None
- assert agent_memory.get_current_turn_id() is None
+def memory():
+ return AgentMemory(max_messages=5)
+
- # After adding a message, current_turn_id should be set
- agent_memory.add_message("user", "Hello")
- first_turn_id = agent_memory.get_current_turn_id()
- assert first_turn_id is not None
- assert isinstance(first_turn_id, str)
+def test_initialization(memory):
+ assert memory.history == []
+ assert memory.max_messages == 5
+ assert memory.current_turn_id is None
- # Adding another message should not change the turn_id
- agent_memory.add_message("assistant", "Hi there")
- assert agent_memory.get_current_turn_id() == first_turn_id
- # Initializing a new turn should change the turn_id
- agent_memory.initialize_turn()
- second_turn_id = agent_memory.get_current_turn_id()
- assert second_turn_id != first_turn_id
+def test_initialize_turn(memory):
+ memory.initialize_turn()
+ assert memory.current_turn_id is not None
-def test_dump_and_load():
- original_memory = AgentMemory(max_messages=3)
- original_memory.add_message("user", "Hello")
- original_memory.add_message("assistant", "Hi there")
+def test_add_message(memory):
+ memory.add_message("user", TestInputSchema(test_field="Hello"))
+ assert len(memory.history) == 1
+ assert memory.history[0].role == "user"
+ assert isinstance(memory.history[0].content, TestInputSchema)
+ assert memory.history[0].turn_id is not None
+
- dumped_data = original_memory.dump()
+def test_manage_overflow(memory):
+ for i in range(7):
+ memory.add_message("user", TestInputSchema(test_field=f"Message {i}"))
+ assert len(memory.history) == 5
+ assert memory.history[0].content.test_field == "Message 2"
- new_memory = AgentMemory(max_messages=3)
+
+def test_serialize_content(memory):
+ content = TestInputSchema(test_field="Test")
+ serialized = memory._serialize_content(content)
+ assert isinstance(serialized, str)
+ assert json.loads(serialized) == {"test_field": "Test"}
+
+
+def test_get_history(memory):
+ memory.add_message("user", TestInputSchema(test_field="Hello"))
+ memory.add_message("assistant", TestOutputSchema(test_field="Hi there"))
+ history = memory.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", TestInputSchema(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_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_message_count(memory):
+ assert memory.get_message_count() == 0
+ memory.add_message("user", TestInputSchema(test_field="Hello"))
+ assert memory.get_message_count() == 1
+
+
+def test_dump_and_load(memory):
+ memory.add_message(
+ "user",
+ TestComplexInputSchema(
+ text_field="Hello",
+ number_field=3.14,
+ list_field=["item1", "item2"],
+ nested_field=TestNestedSchema(nested_field="Nested", nested_int=42),
+ ),
+ )
+ memory.add_message(
+ "assistant",
+ TestComplexOutputSchema(
+ response_text="Hi there",
+ calculated_value=100,
+ data_dict={"key": TestNestedSchema(nested_field="Nested Output", nested_int=10)},
+ ),
+ )
+
+ dumped_data = memory.dump()
+ new_memory = AgentMemory()
new_memory.load(dumped_data)
- assert len(new_memory.history) == 2
- assert new_memory.history[0].role == "user"
- assert new_memory.history[0].content == "Hello"
- assert new_memory.history[1].role == "assistant"
- assert new_memory.history[1].content == "Hi there"
+ 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, TestComplexInputSchema)
+ assert isinstance(new_memory.history[1].content, TestComplexOutputSchema)
+ assert new_memory.history[0].content.text_field == "Hello"
+ assert new_memory.history[1].content.response_text == "Hi there"
+
+
+def test_load_invalid_data(memory):
+ with pytest.raises(ValueError):
+ memory.load("invalid json")
+
+
+def test_get_class_from_string():
+ class_string = "tests.lib.components.test_agent_memory.TestInputSchema"
+ cls = AgentMemory._get_class_from_string(class_string)
+ assert cls.__name__ == TestInputSchema.__name__
+ assert cls.__module__.endswith("test_agent_memory")
+ assert issubclass(cls, BaseIOSchema)
+
+
+def test_get_class_from_string_invalid():
+ with pytest.raises((ImportError, AttributeError)):
+ AgentMemory._get_class_from_string("invalid.module.Class")
+
+
+def test_message_model():
+ message = Message(role="user", content=TestInputSchema(test_field="Test"), turn_id="123")
+ assert message.role == "user"
+ assert isinstance(message.content, TestInputSchema)
+ assert message.turn_id == "123"
+
+
+def test_complex_scenario(memory):
+ # Add complex input
+ memory.add_message(
+ "user",
+ TestComplexInputSchema(
+ text_field="Complex input",
+ number_field=2.718,
+ list_field=["a", "b", "c"],
+ nested_field=TestNestedSchema(nested_field="Nested input", nested_int=99),
+ ),
+ )
+
+ # Add complex output
+ memory.add_message(
+ "assistant",
+ TestComplexOutputSchema(
+ response_text="Complex output",
+ calculated_value=200,
+ data_dict={
+ "key1": TestNestedSchema(nested_field="Nested output 1", nested_int=10),
+ "key2": TestNestedSchema(nested_field="Nested output 2", nested_int=20),
+ },
+ ),
+ )
+
+ # Dump and load
+ dumped_data = memory.dump()
+ new_memory = AgentMemory()
+ new_memory.load(dumped_data)
+ # Verify loaded data
+ assert len(new_memory.history) == 2
+ assert isinstance(new_memory.history[0].content, TestComplexInputSchema)
+ assert isinstance(new_memory.history[1].content, TestComplexOutputSchema)
+ 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"
-def test_copy(agent_memory):
- agent_memory.add_message("user", "Hello")
- copied_memory = agent_memory.copy()
+ # Add a new message to the loaded memory
+ new_memory.add_message("user", TestInputSchema(test_field="New message"))
+ assert len(new_memory.history) == 3
+ assert new_memory.history[2].content.test_field == "New message"
- assert len(copied_memory.history) == 1
- assert copied_memory.history[0].role == "user"
- assert copied_memory.history[0].content == "Hello"
- assert copied_memory.max_messages == agent_memory.max_messages
- agent_memory.add_message("assistant", "Hi there")
- assert len(agent_memory.history) == 2
- assert len(copied_memory.history) == 1
+def test_memory_with_no_max_messages():
+ unlimited_memory = AgentMemory()
+ for i in range(100):
+ unlimited_memory.add_message("user", TestInputSchema(test_field=f"Message {i}"))
+ assert len(unlimited_memory.history) == 100
-def test_get_message_count(agent_memory):
- assert agent_memory.get_message_count() == 0
- agent_memory.add_message("user", "Hello")
- agent_memory.add_message("assistant", "Hi there")
- assert agent_memory.get_message_count() == 2
+def test_memory_with_zero_max_messages():
+ zero_max_memory = AgentMemory(max_messages=0)
+ for i in range(10):
+ zero_max_memory.add_message("user", TestInputSchema(test_field=f"Message {i}"))
+ assert len(zero_max_memory.history) == 0
-def test_load_with_invalid_data():
+def test_memory_turn_consistency():
memory = AgentMemory()
- invalid_data = [
- {"role": "user", "content": "Valid message"},
- {"role": "invalid_role", "content": "Invalid role"},
- {"role": "user", "invalid_field": "Missing content"},
- ]
- memory.load(invalid_data)
- assert len(memory.history) == 2
- assert memory.history[0].role == "user"
- assert memory.history[0].content == "Valid message"
- assert memory.history[1].role == "invalid_role"
- assert memory.history[1].content == "Invalid role"
+ memory.initialize_turn()
+ turn_id = memory.get_current_turn_id()
+ memory.add_message("user", TestInputSchema(test_field="Hello"))
+ memory.add_message("assistant", TestOutputSchema(test_field="Hi"))
+ assert memory.history[0].turn_id == turn_id
+ assert memory.history[1].turn_id == turn_id
+ memory.initialize_turn()
+ new_turn_id = memory.get_current_turn_id()
+ assert new_turn_id != turn_id
+ memory.add_message("user", TestInputSchema(test_field="Next turn"))
+ assert memory.history[2].turn_id == new_turn_id
-def test_add_message_with_dict_content(agent_memory):
- dict_content = {"text": "Hello", "confidence": 0.95}
- agent_memory.add_message("assistant", dict_content)
- assert len(agent_memory.history) == 1
- assert agent_memory.history[0].role == "assistant"
- assert agent_memory.history[0].content == dict_content
-
-if __name__ == "__main__":
- pytest.main()
+def test_serialize_non_baseioschema():
+ memory = AgentMemory()
+ result = memory._serialize_content("Not a BaseIOSchema")
+ assert result == "Not a BaseIOSchema"
diff --git a/atomic-examples/quickstart/poetry.lock b/atomic-examples/quickstart/poetry.lock
index 6afeba1..f3c688f 100644
--- a/atomic-examples/quickstart/poetry.lock
+++ b/atomic-examples/quickstart/poetry.lock
@@ -267,6 +267,20 @@ files = [
{file = "docstring_parser-0.16.tar.gz", hash = "sha256:538beabd0af1e2db0146b6bd3caa526c35a34d61af9fd2887f3a8a27a739aa6e"},
]
+[[package]]
+name = "eval-type-backport"
+version = "0.2.0"
+description = "Like `typing._eval_type`, but lets older Python versions use newer typing features."
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "eval_type_backport-0.2.0-py3-none-any.whl", hash = "sha256:ac2f73d30d40c5a30a80b8739a789d6bb5e49fdffa66d7912667e2015d9c9933"},
+ {file = "eval_type_backport-0.2.0.tar.gz", hash = "sha256:68796cfbc7371ebf923f03bdf7bef415f3ec098aeced24e054b253a0e78f7b37"},
+]
+
+[package.extras]
+tests = ["pytest"]
+
[[package]]
name = "frozenlist"
version = "1.4.1"
@@ -385,6 +399,25 @@ gitdb = ">=4.0.1,<5"
doc = ["sphinx (==4.3.2)", "sphinx-autodoc-typehints", "sphinx-rtd-theme", "sphinxcontrib-applehelp (>=1.0.2,<=1.0.4)", "sphinxcontrib-devhelp (==1.0.2)", "sphinxcontrib-htmlhelp (>=2.0.0,<=2.0.1)", "sphinxcontrib-qthelp (==1.0.3)", "sphinxcontrib-serializinghtml (==1.1.5)"]
test = ["coverage[toml]", "ddt (>=1.1.1,!=1.4.3)", "mock", "mypy", "pre-commit", "pytest (>=7.3.1)", "pytest-cov", "pytest-instafail", "pytest-mock", "pytest-sugar", "typing-extensions"]
+[[package]]
+name = "groq"
+version = "0.11.0"
+description = "The official Python library for the groq API"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "groq-0.11.0-py3-none-any.whl", hash = "sha256:e328531c979542e563668c62260aec13b43a6ee0ca9e2fb22dff1d26f8c8ce54"},
+ {file = "groq-0.11.0.tar.gz", hash = "sha256:dbb9aefedf388ddd4801ec7bf3eba7f5edb67948fec0cd2829d97244059f42a7"},
+]
+
+[package.dependencies]
+anyio = ">=3.5.0,<5"
+distro = ">=1.7.0,<2"
+httpx = ">=0.23.0,<1"
+pydantic = ">=1.9.0,<3"
+sniffio = "*"
+typing-extensions = ">=4.7,<5"
+
[[package]]
name = "h11"
version = "0.14.0"
@@ -559,6 +592,17 @@ files = [
{file = "jiter-0.5.0.tar.gz", hash = "sha256:1d916ba875bcab5c5f7d927df998c4cb694d27dceddf3392e58beaf10563368a"},
]
+[[package]]
+name = "jsonpath-python"
+version = "1.0.6"
+description = "A more powerful JSONPath implementation in modern python"
+optional = false
+python-versions = ">=3.6"
+files = [
+ {file = "jsonpath-python-1.0.6.tar.gz", hash = "sha256:dd5be4a72d8a2995c3f583cf82bf3cd1a9544cfdabf2d22595b67aff07349666"},
+ {file = "jsonpath_python-1.0.6-py3-none-any.whl", hash = "sha256:1e3b78df579f5efc23565293612decee04214609208a2335884b3ee3f786b575"},
+]
+
[[package]]
name = "linkify-it-py"
version = "2.0.3"
@@ -635,6 +679,28 @@ files = [
{file = "mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba"},
]
+[[package]]
+name = "mistralai"
+version = "1.1.0"
+description = "Python Client SDK for the Mistral AI API."
+optional = false
+python-versions = "<4.0,>=3.8"
+files = [
+ {file = "mistralai-1.1.0-py3-none-any.whl", hash = "sha256:eea0938975195f331d0ded12d14e3c982f09f1b68210200ed4ff0c6b9b22d0fb"},
+ {file = "mistralai-1.1.0.tar.gz", hash = "sha256:9d1fe778e0e8c6ddab714e6a64c6096bd39cfe119ff38ceb5019d8e089df08ba"},
+]
+
+[package.dependencies]
+eval-type-backport = ">=0.2.0,<0.3.0"
+httpx = ">=0.27.0,<0.28.0"
+jsonpath-python = ">=1.0.6,<2.0.0"
+pydantic = ">=2.9.0,<3.0.0"
+python-dateutil = "2.8.2"
+typing-inspect = ">=0.9.0,<0.10.0"
+
+[package.extras]
+gcp = ["google-auth (==2.27.0)", "requests (>=2.32.3,<3.0.0)"]
+
[[package]]
name = "multidict"
version = "6.1.0"
@@ -736,6 +802,17 @@ files = [
{file = "multidict-6.1.0.tar.gz", hash = "sha256:22ae2ebf9b0c69d206c003e2f6a914ea33f0a932d4aa16f236afc049d9958f4a"},
]
+[[package]]
+name = "mypy-extensions"
+version = "1.0.0"
+description = "Type system extensions for programs checked with the mypy type checker."
+optional = false
+python-versions = ">=3.5"
+files = [
+ {file = "mypy_extensions-1.0.0-py3-none-any.whl", hash = "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d"},
+ {file = "mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782"},
+]
+
[[package]]
name = "openai"
version = "1.51.2"
@@ -1032,6 +1109,20 @@ files = [
[package.extras]
windows-terminal = ["colorama (>=0.4.6)"]
+[[package]]
+name = "python-dateutil"
+version = "2.8.2"
+description = "Extensions to the standard Python datetime module"
+optional = false
+python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7"
+files = [
+ {file = "python-dateutil-2.8.2.tar.gz", hash = "sha256:0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86"},
+ {file = "python_dateutil-2.8.2-py2.py3-none-any.whl", hash = "sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9"},
+]
+
+[package.dependencies]
+six = ">=1.5"
+
[[package]]
name = "pyyaml"
version = "6.0.2"
@@ -1123,6 +1214,17 @@ files = [
{file = "shellingham-1.5.4.tar.gz", hash = "sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de"},
]
+[[package]]
+name = "six"
+version = "1.16.0"
+description = "Python 2 and 3 compatibility utilities"
+optional = false
+python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*"
+files = [
+ {file = "six-1.16.0-py2.py3-none-any.whl", hash = "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254"},
+ {file = "six-1.16.0.tar.gz", hash = "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926"},
+]
+
[[package]]
name = "smmap"
version = "5.0.1"
@@ -1228,6 +1330,21 @@ files = [
{file = "typing_extensions-4.12.2.tar.gz", hash = "sha256:1a7ead55c7e559dd4dee8856e3a88b41225abfe1ce8df57b7c13915fe121ffb8"},
]
+[[package]]
+name = "typing-inspect"
+version = "0.9.0"
+description = "Runtime inspection utilities for typing module."
+optional = false
+python-versions = "*"
+files = [
+ {file = "typing_inspect-0.9.0-py3-none-any.whl", hash = "sha256:9ee6fc59062311ef8547596ab6b955e1b8aa46242d854bfc78f4f6b0eff35f9f"},
+ {file = "typing_inspect-0.9.0.tar.gz", hash = "sha256:b23fc42ff6f6ef6954e4852c1fb512cdd18dbea03134f91f856a95ccc9461f78"},
+]
+
+[package.dependencies]
+mypy-extensions = ">=0.3.0"
+typing-extensions = ">=3.7.4"
+
[[package]]
name = "uc-micro-py"
version = "1.0.3"
@@ -1351,4 +1468,4 @@ propcache = ">=0.2.0"
[metadata]
lock-version = "2.0"
python-versions = "^3.11"
-content-hash = "2715a8bf2b609cccd0c86792a613a484c0de839d18c5a5abb5568841ffaf85b9"
+content-hash = "04b530036606dcc32530b8551644a7374306f0a7f91374e5345deb3416b011ab"
diff --git a/atomic-examples/quickstart/pyproject.toml b/atomic-examples/quickstart/pyproject.toml
index 48ba148..a9e9a79 100644
--- a/atomic-examples/quickstart/pyproject.toml
+++ b/atomic-examples/quickstart/pyproject.toml
@@ -8,6 +8,8 @@ readme = "README.md"
[tool.poetry.dependencies]
python = "^3.11"
atomic-agents = {path = "../..", develop = true}
+groq = "^0.11.0"
+mistralai = "^1.1.0"
[build-system]
diff --git a/atomic-examples/quickstart/quickstart/basic_chatbot.py b/atomic-examples/quickstart/quickstart/1_basic_chatbot.py
similarity index 100%
rename from atomic-examples/quickstart/quickstart/basic_chatbot.py
rename to atomic-examples/quickstart/quickstart/1_basic_chatbot.py
diff --git a/atomic-examples/quickstart/quickstart/basic_custom_chatbot.py b/atomic-examples/quickstart/quickstart/2_basic_custom_chatbot.py
similarity index 100%
rename from atomic-examples/quickstart/quickstart/basic_custom_chatbot.py
rename to atomic-examples/quickstart/quickstart/2_basic_custom_chatbot.py
diff --git a/atomic-examples/quickstart/quickstart/basic_custom_chatbot_with_custom_schema.py b/atomic-examples/quickstart/quickstart/3_basic_custom_chatbot_with_custom_schema.py
similarity index 68%
rename from atomic-examples/quickstart/quickstart/basic_custom_chatbot_with_custom_schema.py
rename to atomic-examples/quickstart/quickstart/3_basic_custom_chatbot_with_custom_schema.py
index 4003781..7dbc7ce 100644
--- a/atomic-examples/quickstart/quickstart/basic_custom_chatbot_with_custom_schema.py
+++ b/atomic-examples/quickstart/quickstart/3_basic_custom_chatbot_with_custom_schema.py
@@ -29,22 +29,22 @@ memory = AgentMemory()
# Custom output schema
class CustomOutputSchema(BaseIOSchema):
- """This schema represents the response generated by the chat agent, including follow-up questions."""
+ """This schema represents the response generated by the chat agent, including suggested follow-up questions."""
chat_message: str = Field(
...,
description="The chat message exchanged between the user and the chat agent.",
)
- quick_replies: List[str] = Field(
+ suggested_user_questions: List[str] = Field(
...,
- description="A list of suggested follow-up message suggesions the user could reply with to the assistant.",
+ description="A list of suggested follow-up questions the user could ask the agent.",
)
# Initialize memory with an initial message from the assistant
initial_message = CustomOutputSchema(
chat_message="Hello! How can I assist you today?",
- quick_replies=["What can you do?", "Tell me a joke", "Tell me about how you were made"],
+ suggested_user_questions=["What can you do?", "Tell me a joke", "Tell me about how you were made"],
)
memory.add_message("assistant", initial_message)
@@ -54,18 +54,18 @@ client = instructor.from_openai(openai.OpenAI(api_key=API_KEY))
# Custom system prompt
system_prompt_generator = SystemPromptGenerator(
background=[
- "This assistant is a knowledgeable AI designed to be helpful, friendly, and poetic.",
+ "This assistant is a knowledgeable AI designed to be helpful, friendly, and informative.",
+ "It has a wide range of knowledge on various topics and can engage in diverse conversations.",
],
steps=[
- "Understand the user's input and provide a relevant response.",
- "Generate 3 follow-up questions based on the context of the conversation.",
- "Respond to the user in rhyming verse.",
+ "Analyze the user's input to understand the context and intent.",
+ "Formulate a relevant and informative response based on the assistant's knowledge.",
+ "Generate 3 suggested follow-up questions for the user to explore the topic further.",
],
output_instructions=[
- "Provide helpful and relevant information to assist the user.",
- "Be friendly and respectful in all interactions.",
- "Always answer in rhyming verse.",
- "Include 3 follow-up questions in your response.",
+ "Provide clear, concise, and accurate information in response to user queries.",
+ "Maintain a friendly and professional tone throughout the conversation.",
+ "Conclude each response with 3 relevant suggested questions for the user.",
],
)
console.print(Panel(system_prompt_generator.generate_prompt(), width=console.width, style="bold cyan"), style="bold cyan")
@@ -85,6 +85,12 @@ agent = BaseAgent(
console.print(Text("Agent:", style="bold green"), end=" ")
console.print(Text(initial_message.chat_message, style="bold green"))
+# Display initial suggested questions
+console.print("\n[bold cyan]Suggested questions you could ask:[/bold cyan]")
+for i, question in enumerate(initial_message.suggested_user_questions, 1):
+ console.print(f"[cyan]{i}. {question}[/cyan]")
+console.print() # Add an empty line for better readability
+
# Start an infinite loop to handle user inputs and agent responses
while True:
# Prompt the user for input with a styled prompt
@@ -103,7 +109,7 @@ while True:
console.print(agent_message)
# Display follow-up questions
- console.print("\n[bold cyan]Follow-up Questions:[/bold cyan]")
- for i, question in enumerate(response.quick_replies, 1):
+ console.print("\n[bold cyan]Suggested questions you could ask:[/bold cyan]")
+ for i, question in enumerate(response.suggested_user_questions, 1):
console.print(f"[cyan]{i}. {question}[/cyan]")
console.print() # Add an empty line for better readability
diff --git a/atomic-examples/quickstart/quickstart/4_basic_chatbot_different_providers.py b/atomic-examples/quickstart/quickstart/4_basic_chatbot_different_providers.py
new file mode 100644
index 0000000..45f24a9
--- /dev/null
+++ b/atomic-examples/quickstart/quickstart/4_basic_chatbot_different_providers.py
@@ -0,0 +1,93 @@
+import os
+import instructor
+from rich.console import Console
+from rich.panel import Panel
+from rich.text import Text
+from atomic_agents.lib.components.agent_memory import AgentMemory
+from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseAgentInputSchema, BaseAgentOutputSchema
+from dotenv import load_dotenv
+
+load_dotenv()
+
+# Initialize a Rich Console for pretty console outputs
+console = Console()
+
+# Memory setup
+memory = AgentMemory()
+
+# Initialize memory 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)
+
+
+# Function to set up the client based on the chosen provider
+def setup_client(provider):
+ if provider == "openai":
+ from openai import OpenAI
+
+ api_key = os.getenv("OPENAI_API_KEY")
+ client = instructor.from_openai(OpenAI(api_key=api_key))
+ model = "gpt-4o-mini"
+ elif provider == "groq":
+ from groq import Groq
+
+ api_key = os.getenv("GROQ_API_KEY")
+ client = instructor.from_groq(Groq(api_key=api_key), mode=instructor.Mode.TOOLS)
+ model = "mixtral-8x7b-32768"
+ elif provider == "mistral":
+ from mistralai.client import MistralClient
+
+ api_key = os.getenv("MISTRAL_API_KEY")
+ client = instructor.from_mistral(MistralClient(api_key=api_key), model="mistral-large-latest")
+ model = "mistral-large-latest"
+ elif provider == "ollama":
+ from openai import OpenAI as OllamaClient
+
+ client = instructor.from_openai(OllamaClient(base_url="http://localhost:11434/v1", api_key="ollama"))
+ model = "llama3"
+ else:
+ raise ValueError(f"Unsupported provider: {provider}")
+
+ return client, model
+
+
+# Prompt the user to choose a provider
+provider = console.input("[bold yellow]Choose a provider (openai/groq/mistral/ollama): [/bold yellow]").lower()
+
+# Set up the client and model based on the chosen provider
+client, model = setup_client(provider)
+
+# Agent setup with specified configuration
+agent = BaseAgent(
+ config=BaseAgentConfig(
+ client=client,
+ model=model,
+ memory=memory,
+ )
+)
+
+# Generate the default system prompt for the agent
+default_system_prompt = agent.system_prompt_generator.generate_prompt()
+# Display the system prompt in a styled panel
+console.print(Panel(default_system_prompt, width=console.width, style="bold cyan"), style="bold cyan")
+
+# Display the initial message from the assistant
+console.print(Text("Agent:", style="bold green"), end=" ")
+console.print(Text(initial_message.chat_message, style="bold green"))
+
+# Start an infinite loop to handle user inputs and agent responses
+while True:
+ # Prompt the user for input with a styled prompt
+ user_input = console.input("[bold blue]You:[/bold blue] ")
+ # Check if the user wants to exit the chat
+ if user_input.lower() in ["/exit", "/quit"]:
+ console.print("Exiting chat...")
+ break
+
+ # Process the user's input through the agent and get the response
+ input_schema = BaseAgentInputSchema(chat_message=user_input)
+ response = agent.run(input_schema)
+
+ agent_message = Text(response.chat_message, style="bold green")
+ console.print(Text("Agent:", style="bold green"), end=" ")
+ console.print(agent_message)
diff --git a/poetry.lock b/poetry.lock
index 872c9cd..0152fa8 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -1273,6 +1273,20 @@ pytest = ">=4.6"
[package.extras]
testing = ["fields", "hunter", "process-tests", "pytest-xdist", "virtualenv"]
+[[package]]
+name = "python-dotenv"
+version = "1.0.1"
+description = "Read key-value pairs from a .env file and set them as environment variables"
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "python-dotenv-1.0.1.tar.gz", hash = "sha256:e324ee90a023d808f1959c46bcbc04446a10ced277783dc6ee09987c37ec10ca"},
+ {file = "python_dotenv-1.0.1-py3-none-any.whl", hash = "sha256:f7b63ef50f1b690dddf550d03497b66d609393b40b564ed0d674909a68ebf16a"},
+]
+
+[package.extras]
+cli = ["click (>=5.0)"]
+
[[package]]
name = "pyyaml"
version = "6.0.2"
@@ -1592,4 +1606,4 @@ propcache = ">=0.2.0"
[metadata]
lock-version = "2.0"
python-versions = ">=3.11,<4.0"
-content-hash = "8b2fe927713d2ec4de4d494a739f8fca769cbb8c560539efca5d2b55ec64f5b1"
+content-hash = "aec645b798c7f080897ab95d005defef062f7a78889dbc208c1f1cf849d05966"
diff --git a/pyproject.toml b/pyproject.toml
index d42c8c9..924c727 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -24,6 +24,7 @@ gitpython = ">=3.1.43,<4.0.0"
pyfiglet = ">=1.0.2,<2.0.0"
textual = ">=0.82.0,<1.0.0"
pyyaml = ">=6.0.2,<7.0.0"
+python-dotenv = "^1.0.1"
[tool.poetry.group.dev.dependencies]
black = ">=24.8.0,<25.0.0"