Skip to content

Building AI agents, atomically

Remove SystemPromptInfo

KennyVaneetveldee6be1e1eb4f5
diff --git a/atomic_agents/agents/base_agent.py b/atomic_agents/agents/base_agent.py
index b5812dd..2bcf55f 100644
--- a/atomic_agents/agents/base_agent.py
+++ b/atomic_agents/agents/base_agent.py
@@ -165,9 +165,9 @@ class BaseAgent:
Raises:
KeyError: If the context provider is not found.
"""
- if provider_name not in self.system_prompt_generator.system_prompt_info.context_providers:
+ if provider_name not in self.system_prompt_generator.context_providers:
raise KeyError(f"Context provider '{provider_name}' not found.")
- return self.system_prompt_generator.system_prompt_info.context_providers[provider_name]
+ return self.system_prompt_generator.context_providers[provider_name]
def register_context_provider(self, provider_name: str, provider: SystemPromptContextProviderBase):
"""
@@ -177,7 +177,7 @@ class BaseAgent:
provider_name (str): The name of the context provider.
provider (SystemPromptContextProviderBase): The context provider instance.
"""
- self.system_prompt_generator.system_prompt_info.context_providers[provider_name] = provider
+ self.system_prompt_generator.context_providers[provider_name] = provider
def unregister_context_provider(self, provider_name: str):
"""
@@ -186,7 +186,7 @@ class BaseAgent:
Args:
provider_name (str): The name of the context provider to remove.
"""
- if provider_name in self.system_prompt_generator.system_prompt_info.context_providers:
- del self.system_prompt_generator.system_prompt_info.context_providers[provider_name]
+ if provider_name in self.system_prompt_generator.context_providers:
+ del self.system_prompt_generator.context_providers[provider_name]
else:
raise KeyError(f"Context provider '{provider_name}' not found.")
diff --git a/atomic_agents/agents/tool_interface_agent.py b/atomic_agents/agents/tool_interface_agent.py
index cf06291..4af7683 100644
--- a/atomic_agents/agents/tool_interface_agent.py
+++ b/atomic_agents/agents/tool_interface_agent.py
@@ -3,7 +3,7 @@ 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, SystemPromptInfo
+from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator
from atomic_agents.lib.tools.base_tool import BaseTool
from atomic_agents.lib.utils.format_tool_message import format_tool_message
@@ -74,19 +74,17 @@ class ToolInterfaceAgent(BaseAgent):
output_instructions.append("Return the raw output of the tool.")
self.system_prompt_generator = SystemPromptGenerator(
- system_prompt_info=SystemPromptInfo(
- 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.",
- "Respond to the user",
- ],
- output_instructions=output_instructions,
- )
+ 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.",
+ "Respond to the user",
+ ],
+ output_instructions=output_instructions
)
def get_response(self, response_model=None):
diff --git a/atomic_agents/lib/components/system_prompt_generator.py b/atomic_agents/lib/components/system_prompt_generator.py
index 0f69f63..952d366 100644
--- a/atomic_agents/lib/components/system_prompt_generator.py
+++ b/atomic_agents/lib/components/system_prompt_generator.py
@@ -1,8 +1,6 @@
from abc import ABC, abstractmethod
-from dataclasses import dataclass, field
from typing import Dict, List, Optional
-
class SystemPromptContextProviderBase(ABC):
def __init__(self, title: str):
self.title = title
@@ -14,33 +12,29 @@ class SystemPromptContextProviderBase(ABC):
def __repr__(self) -> str:
return self.get_info()
-
-@dataclass
-class SystemPromptInfo:
- background: List[str]
- steps: List[str] = field(default_factory=list)
- output_instructions: List[str] = field(default_factory=list)
- context_providers: Dict[str, SystemPromptContextProviderBase] = field(default_factory=dict)
-
-
class SystemPromptGenerator:
- def __init__(self, system_prompt_info: Optional[SystemPromptInfo] = None):
- self.system_prompt_info = system_prompt_info or SystemPromptInfo(
- background=["This is a conversation with a helpful and friendly AI assistant."]
- )
-
- self.system_prompt_info.output_instructions.extend(
- [
- "Always respond using the proper JSON schema.",
- "Always use the available additional information and context to enhance the response.",
- ]
- )
+ def __init__(
+ self,
+ background: Optional[List[str]] = None,
+ steps: Optional[List[str]] = None,
+ output_instructions: Optional[List[str]] = None,
+ context_providers: Optional[Dict[str, SystemPromptContextProviderBase]] = None
+ ):
+ self.background = background or ["This is a conversation with a helpful and friendly AI assistant."]
+ self.steps = steps or []
+ self.output_instructions = output_instructions or []
+ self.context_providers = context_providers or {}
+
+ self.output_instructions.extend([
+ "Always respond using the proper JSON schema.",
+ "Always use the available additional information and context to enhance the response.",
+ ])
def generate_prompt(self) -> str:
sections = [
- ("IDENTITY and PURPOSE", self.system_prompt_info.background),
- ("INTERNAL ASSISTANT STEPS", self.system_prompt_info.steps),
- ("OUTPUT INSTRUCTIONS", self.system_prompt_info.output_instructions),
+ ("IDENTITY and PURPOSE", self.background),
+ ("INTERNAL ASSISTANT STEPS", self.steps),
+ ("OUTPUT INSTRUCTIONS", self.output_instructions),
]
prompt_parts = []
@@ -51,13 +45,13 @@ class SystemPromptGenerator:
prompt_parts.extend(f"- {item}" for item in content)
prompt_parts.append("")
- if self.system_prompt_info.context_providers:
+ if self.context_providers:
prompt_parts.append("# EXTRA INFORMATION AND CONTEXT")
- for provider in self.system_prompt_info.context_providers.values():
+ for provider in self.context_providers.values():
info = provider.get_info()
if info:
prompt_parts.append(f"## {provider.title}")
prompt_parts.append(info)
prompt_parts.append("")
- return "\n".join(prompt_parts).strip()
+ return "\n".join(prompt_parts).strip()
\ No newline at end of file
diff --git a/tests/agents/test_base_agent.py b/tests/agents/test_base_agent.py
index 86d9dad..77c6165 100644
--- a/tests/agents/test_base_agent.py
+++ b/tests/agents/test_base_agent.py
@@ -12,7 +12,6 @@ from atomic_agents.agents.base_agent import (
AgentMemory,
SystemPromptContextProviderBase
)
-from atomic_agents.lib.components.system_prompt_generator import SystemPromptInfo
@pytest.fixture
def mock_instructor():
@@ -32,8 +31,7 @@ def mock_memory():
def mock_system_prompt_generator():
mock = Mock(spec=SystemPromptGenerator)
mock.generate_prompt.return_value = "Mocked system prompt"
- mock.system_prompt_info = Mock(spec=SystemPromptInfo)
- mock.system_prompt_info.context_providers = {}
+ mock.context_providers = {}
return mock
@pytest.fixture
@@ -102,7 +100,7 @@ def test_run(agent):
def test_get_context_provider(agent, mock_system_prompt_generator):
mock_provider = Mock(spec=SystemPromptContextProviderBase)
- mock_system_prompt_generator.system_prompt_info.context_providers = {
+ mock_system_prompt_generator.context_providers = {
'test_provider': mock_provider
}
@@ -116,17 +114,17 @@ def test_register_context_provider(agent, mock_system_prompt_generator):
mock_provider = Mock(spec=SystemPromptContextProviderBase)
agent.register_context_provider('new_provider', mock_provider)
- assert 'new_provider' in mock_system_prompt_generator.system_prompt_info.context_providers
- assert mock_system_prompt_generator.system_prompt_info.context_providers['new_provider'] == mock_provider
+ assert 'new_provider' in mock_system_prompt_generator.context_providers
+ assert mock_system_prompt_generator.context_providers['new_provider'] == mock_provider
def test_unregister_context_provider(agent, mock_system_prompt_generator):
mock_provider = Mock(spec=SystemPromptContextProviderBase)
- mock_system_prompt_generator.system_prompt_info.context_providers = {
+ mock_system_prompt_generator.context_providers = {
'test_provider': mock_provider
}
agent.unregister_context_provider('test_provider')
- assert 'test_provider' not in mock_system_prompt_generator.system_prompt_info.context_providers
+ assert 'test_provider' not in mock_system_prompt_generator.context_providers
with pytest.raises(KeyError):
agent.unregister_context_provider('non_existent_provider')
@@ -184,4 +182,4 @@ def test_run(agent, mock_memory):
])
if __name__ == '__main__':
- pytest.main()
\ No newline at end of file
+ pytest.main()
diff --git a/tests/agents/test_tool_interface_agent.py b/tests/agents/test_tool_interface_agent.py
index 8c5d954..f0fd91d 100644
--- a/tests/agents/test_tool_interface_agent.py
+++ b/tests/agents/test_tool_interface_agent.py
@@ -122,10 +122,5 @@ def test_tool_interface_agent_memory_updates(mock_format_tool_message, mock_get_
# 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))
- # Print the memory contents for debugging
- print("Memory contents:")
- for msg in history:
- print(f"Role: {msg.role}, Content: {msg.content}")
-
# Assert that at least 3 messages were added (TOOL CALL, TOOL RESPONSE, and possibly the final response)
- assert len(history) >= 3
\ No newline at end of file
+ assert len(history) >= 3
diff --git a/tests/lib/components/test_system_prompt_generator.py b/tests/lib/components/test_system_prompt_generator.py
index 86109cd..49fa282 100644
--- a/tests/lib/components/test_system_prompt_generator.py
+++ b/tests/lib/components/test_system_prompt_generator.py
@@ -1,212 +1,135 @@
import pytest
-from datetime import datetime
-from unittest.mock import Mock
-
-from atomic_agents.lib.components.system_prompt_generator import (
- SystemPromptContextProviderBase,
- SystemPromptInfo,
- SystemPromptGenerator,
-)
+from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator, SystemPromptContextProviderBase
class MockContextProvider(SystemPromptContextProviderBase):
- def get_info(self):
- return "Mock info"
-
-class CurrentDateProvider(SystemPromptContextProviderBase):
- def __init__(self, title, format: str = '%Y-%m-%d %H:%M:%S'):
+ def __init__(self, title: str, info: str):
super().__init__(title)
- self.format = format
-
- def get_current_datetime(self):
- return datetime.now()
+ self._info = info
def get_info(self) -> str:
- current_datetime = self.get_current_datetime()
- return f'The current date, in the format "{self.format}", is {current_datetime.strftime(self.format)}'
+ return self._info
+
+def test_system_prompt_generator_default_initialization():
+ generator = SystemPromptGenerator()
+ assert generator.background == ["This is a conversation with a helpful and friendly AI assistant."]
+ assert generator.steps == []
+ assert generator.output_instructions == [
+ "Always respond using the proper JSON schema.",
+ "Always use the available additional information and context to enhance the response."
+ ]
+ assert generator.context_providers == {}
+
+def test_system_prompt_generator_custom_initialization():
+ background = ["Custom background"]
+ steps = ["Step 1", "Step 2"]
+ output_instructions = ["Custom instruction"]
+ context_providers = {
+ "provider1": MockContextProvider("Provider 1", "Info 1"),
+ "provider2": MockContextProvider("Provider 2", "Info 2")
+ }
+
+ generator = SystemPromptGenerator(
+ background=background,
+ steps=steps,
+ output_instructions=output_instructions,
+ context_providers=context_providers
+ )
-class LoremIpsumProvider(SystemPromptContextProviderBase):
- def get_info(self) -> str:
- return (
- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
- "Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "
- "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
- )
-
-def default_generator():
- return SystemPromptGenerator()
-
-def custom_info():
- current_date_provider = CurrentDateProvider(title="Current date", format="%Y-%m-%d %H:%M:%S")
- return SystemPromptInfo(
- background=["Custom background"],
- steps=["Custom step"],
+ assert generator.background == background
+ assert generator.steps == steps
+ assert generator.output_instructions == [
+ "Custom instruction",
+ "Always respond using the proper JSON schema.",
+ "Always use the available additional information and context to enhance the response."
+ ]
+ assert generator.context_providers == context_providers
+
+def test_generate_prompt_without_context_providers():
+ generator = SystemPromptGenerator(
+ background=["Background info"],
+ steps=["Step 1", "Step 2"],
+ output_instructions=["Custom instruction"]
+ )
+
+ expected_prompt = """# IDENTITY and PURPOSE
+- Background info
+
+# INTERNAL ASSISTANT STEPS
+- Step 1
+- Step 2
+
+# OUTPUT INSTRUCTIONS
+- Custom instruction
+- Always respond using the proper JSON schema.
+- Always use the available additional information and context to enhance the response."""
+
+ assert generator.generate_prompt() == expected_prompt
+
+def test_generate_prompt_with_context_providers():
+ generator = SystemPromptGenerator(
+ background=["Background info"],
+ steps=["Step 1"],
output_instructions=["Custom instruction"],
context_providers={
- "test": MockContextProvider("Test Provider"),
- "date": current_date_provider,
- "lorem": LoremIpsumProvider(title="Lorem Ipsum")
+ "provider1": MockContextProvider("Provider 1", "Info 1"),
+ "provider2": MockContextProvider("Provider 2", "Info 2")
}
)
-def custom_generator(custom_info):
- return SystemPromptGenerator(custom_info)
-
-class TestSystemPromptContextProviderBase:
- def test_abstract_base_class(self):
- with pytest.raises(TypeError):
- SystemPromptContextProviderBase("Test")
-
- def test_repr(self):
- class ConcreteProvider(SystemPromptContextProviderBase):
- def get_info(self):
- return "Test Info"
-
- provider = ConcreteProvider("Test")
- assert repr(provider) == "Test Info"
-
-class TestSystemPromptInfo:
- def test_default_values(self):
- info = SystemPromptInfo(background=["Test background"])
- assert info.background == ["Test background"]
- assert info.steps == []
- assert info.output_instructions == []
- assert info.context_providers == {}
-
- def test_custom_values(self):
- info = SystemPromptInfo(
- background=["Test background"],
- steps=["Step 1", "Step 2"],
- output_instructions=["Instruction 1"],
- context_providers={"test": None}
- )
- assert info.background == ["Test background"]
- assert info.steps == ["Step 1", "Step 2"]
- assert info.output_instructions == ["Instruction 1"]
- assert info.context_providers == {"test": None}
-
-class TestSystemPromptGeneratorBasic:
- def test_default_initialization(self, default_generator):
- assert default_generator.system_prompt_info.background == ['This is a conversation with a helpful and friendly AI assistant.']
- assert len(default_generator.system_prompt_info.output_instructions) == 2
-
- def test_custom_initialization(self, custom_generator, custom_info):
- assert custom_generator.system_prompt_info == custom_info
- assert len(custom_generator.system_prompt_info.output_instructions) == 3
-
- def test_generate_prompt_default(self, default_generator):
- prompt = default_generator.generate_prompt()
- assert "# IDENTITY and PURPOSE" in prompt
- assert "# OUTPUT INSTRUCTIONS" in prompt
- assert "# INTERNAL ASSISTANT STEPS" not in prompt
- assert "# EXTRA INFORMATION AND CONTEXT" not in prompt
-
- def test_generate_prompt_custom(self, custom_generator):
- prompt = custom_generator.generate_prompt()
-
- assert "# IDENTITY and PURPOSE" in prompt
- assert "# INTERNAL ASSISTANT STEPS" in prompt
- assert "# OUTPUT INSTRUCTIONS" in prompt
- assert "# EXTRA INFORMATION AND CONTEXT" in prompt
- assert "Custom background" in prompt
- assert "Custom step" in prompt
- assert "Custom instruction" in prompt
- assert "Mock info" in prompt
-
- def test_empty_system_prompt_info(self):
- empty_info = SystemPromptInfo(background=[])
- empty_generator = SystemPromptGenerator(empty_info)
- prompt = empty_generator.generate_prompt()
- expected_prompt = "# OUTPUT INSTRUCTIONS\n- Always respond using the proper JSON schema.\n- Always use the available additional information and context to enhance the response."
- assert prompt == expected_prompt
-
- def test_partial_system_prompt_info(self):
- partial_info = SystemPromptInfo(
- background=["Test background"],
- steps=["Test step"],
- )
- partial_generator = SystemPromptGenerator(partial_info)
- prompt = partial_generator.generate_prompt()
- assert "# IDENTITY and PURPOSE" in prompt
- assert "Test background" in prompt
- assert "# INTERNAL ASSISTANT STEPS" in prompt
- assert "Test step" in prompt
- assert "# OUTPUT INSTRUCTIONS" in prompt
- assert "# EXTRA INFORMATION AND CONTEXT" not in prompt
-
-class TestSystemPromptGeneratorContextProviders:
- def test_generate_prompt_with_context_providers(self, custom_generator):
- prompt = custom_generator.generate_prompt()
-
- assert "# IDENTITY and PURPOSE" in prompt
- assert "# INTERNAL ASSISTANT STEPS" in prompt
- assert "# OUTPUT INSTRUCTIONS" in prompt
- assert "# EXTRA INFORMATION AND CONTEXT" in prompt
- assert "Custom background" in prompt
- assert "Custom step" in prompt
- assert "Custom instruction" in prompt
- assert "Mock info" in prompt
- assert "## Current date" in prompt
- assert "The current date, in the format" in prompt
- assert "## Lorem Ipsum" in prompt
- assert "Lorem ipsum dolor sit amet" in prompt
-
- def test_current_date_provider(self, custom_generator, monkeypatch):
- mock_datetime = datetime(2023, 5, 1, 12, 0, 0)
- monkeypatch.setattr(custom_generator.system_prompt_info.context_providers['date'], 'get_current_datetime', lambda: mock_datetime)
- prompt = custom_generator.generate_prompt()
- assert 'The current date, in the format "%Y-%m-%d %H:%M:%S", is 2023-05-01 12:00:00' in prompt
-
- def test_custom_output_instructions(self):
- custom_instructions = ["Custom instruction 1", "Custom instruction 2"]
- custom_info = SystemPromptInfo(
- background=["Test background"],
- output_instructions=custom_instructions
- )
- custom_generator = SystemPromptGenerator(custom_info)
- prompt = custom_generator.generate_prompt()
- for instruction in custom_instructions:
- assert instruction in prompt
- assert "Always respond using the proper JSON schema." in prompt
- assert "Always use the available additional information and context to enhance the response." in prompt
-
- def test_empty_context_provider(self):
- class EmptyProvider(SystemPromptContextProviderBase):
- def get_info(self):
- return ""
-
- info = SystemPromptInfo(
- background=["Test"],
- context_providers={"empty": EmptyProvider("Empty")}
- )
- generator = SystemPromptGenerator(info)
- prompt = generator.generate_prompt()
- assert "## Empty" not in prompt
-
- def test_multiple_context_providers(self):
- class Provider1(SystemPromptContextProviderBase):
- def get_info(self):
- return "Info 1"
-
- class Provider2(SystemPromptContextProviderBase):
- def get_info(self):
- return "Info 2"
-
- info = SystemPromptInfo(
- background=["Test"],
- context_providers={
- "provider1": Provider1("Provider 1"),
- "provider2": Provider2("Provider 2")
- }
- )
- generator = SystemPromptGenerator(info)
- prompt = generator.generate_prompt()
- assert "## Provider 1" in prompt
- assert "Info 1" in prompt
- assert "## Provider 2" in prompt
- assert "Info 2" in prompt
-
-if __name__ == '__main__':
- pytest.main()
\ No newline at end of file
+ expected_prompt = """# IDENTITY and PURPOSE
+- Background info
+
+# INTERNAL ASSISTANT STEPS
+- Step 1
+
+# OUTPUT INSTRUCTIONS
+- Custom instruction
+- Always respond using the proper JSON schema.
+- Always use the available additional information and context to enhance the response.
+
+# EXTRA INFORMATION AND CONTEXT
+## Provider 1
+Info 1
+
+## Provider 2
+Info 2"""
+
+ assert generator.generate_prompt() == expected_prompt
+
+def test_generate_prompt_with_empty_sections():
+ generator = SystemPromptGenerator(
+ background=[],
+ steps=[],
+ output_instructions=[]
+ )
+
+ expected_prompt = """# IDENTITY and PURPOSE
+- This is a conversation with a helpful and friendly AI assistant.
+
+# OUTPUT INSTRUCTIONS
+- Always respond using the proper JSON schema.
+- Always use the available additional information and context to enhance the response."""
+
+ assert generator.generate_prompt() == expected_prompt
+
+def test_context_provider_repr():
+ provider = MockContextProvider("Test Provider", "Test Info")
+ assert repr(provider) == "Test Info"
+
+def test_generate_prompt_with_empty_context_provider():
+ empty_provider = MockContextProvider("Empty Provider", "")
+ generator = SystemPromptGenerator(
+ background=["Background"],
+ context_providers={"empty": empty_provider}
+ )
+
+ expected_prompt = """# IDENTITY and PURPOSE
+- Background
+
+# OUTPUT INSTRUCTIONS
+- Always respond using the proper JSON schema.
+- Always use the available additional information and context to enhance the response.
+
+# EXTRA INFORMATION AND CONTEXT"""
+
+ assert generator.generate_prompt() == expected_prompt
\ No newline at end of file
diff --git a/tests/lib/tools/test_base.py b/tests/lib/tools/test_base_tool.py
similarity index 100%
rename from tests/lib/tools/test_base.py
rename to tests/lib/tools/test_base_tool.py
diff --git a/tests/lib/tools/test_yt_transcript_scraper.py b/tests/lib/tools/test_yt_transcript_scraper_tool.py
similarity index 100%
rename from tests/lib/tools/test_yt_transcript_scraper.py
rename to tests/lib/tools/test_yt_transcript_scraper_tool.py