Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

fix: mem0 mypy test and doc, openrouter key, mcp test (#1943)

Wendong-Fan3dc9c05d73b5
diff --git a/.github/workflows/build_package.yml b/.github/workflows/build_package.yml
index 145efab2a..27fcb5305 100644
--- a/.github/workflows/build_package.yml
+++ b/.github/workflows/build_package.yml
@@ -98,6 +98,7 @@ jobs:
AIML_API_KEY: "${{ secrets.AIML_API_KEY }}"
NVIDIA_API_KEY: "${{ secrets.NVIDIA_API_KEY }}"
VOLCANO_API_KEY: "${{ secrets.VOLCANO_API_KEY }}"
+ OPENROUTER_API_KEY: "${{ secrets.OPENROUTER_API_KEY }}"
run: |
source test_venv/bin/activate
pytest --fast-test-mode ./test
diff --git a/.github/workflows/pytest_package.yml b/.github/workflows/pytest_package.yml
index 27808290c..65897cc80 100644
--- a/.github/workflows/pytest_package.yml
+++ b/.github/workflows/pytest_package.yml
@@ -63,6 +63,7 @@ jobs:
SILICONFLOW_API_KEY: "${{ secrets.SILICONFLOW_API_KEY }}"
AIML_API_KEY: "${{ secrets.AIML_API_KEY }}"
VOLCANO_API_KEY: "${{ secrets.VOLCANO_API_KEY }}"
+ OPENROUTER_API_KEY: "${{ secrets.OPENROUTER_API_KEY }}"
run: |
source .venv/bin/activate
uv pip install -e ".[all, dev, docs]"
@@ -118,6 +119,7 @@ jobs:
SILICONFLOW_API_KEY: "${{ secrets.SILICONFLOW_API_KEY }}"
AIML_API_KEY: "${{ secrets.AIML_API_KEY }}"
VOLCANO_API_KEY: "${{ secrets.VOLCANO_API_KEY }}"
+ OPENROUTER_API_KEY: "${{ secrets.OPENROUTER_API_KEY }}"
run: |
source .venv/bin/activate
uv pip install -e ".[all, dev, docs]"
@@ -171,6 +173,7 @@ jobs:
JINA_API_KEY: "${{ secrets.JINA_API_KEY }}"
MOONSHOT_API_KEY: "${{ secrets.MOONSHOT_API_KEY }}"
VOLCANO_API_KEY: "${{ secrets.VOLCANO_API_KEY }}"
+ OPENROUTER_API_KEY: "${{ secrets.OPENROUTER_API_KEY }}"
run: |
source .venv/bin/activate
uv pip install -e ".[all, dev, docs]"
diff --git a/camel/memories/agent_memories.py b/camel/memories/agent_memories.py
index 03eb959bb..d379e4343 100644
--- a/camel/memories/agent_memories.py
+++ b/camel/memories/agent_memories.py
@@ -18,10 +18,8 @@ from typing import List, Optional
from camel.memories.base import AgentMemory, BaseContextCreator
from camel.memories.blocks import ChatHistoryBlock, VectorDBBlock
from camel.memories.records import ContextRecord, MemoryRecord
-from camel.storages import (
- BaseKeyValueStorage,
- BaseVectorStorage,
-)
+from camel.storages.key_value_storages.base import BaseKeyValueStorage
+from camel.storages.vectordb_storages.base import BaseVectorStorage
from camel.types import OpenAIBackendRole
diff --git a/camel/memories/blocks/chat_history_block.py b/camel/memories/blocks/chat_history_block.py
index 68218dbb4..02671ec66 100644
--- a/camel/memories/blocks/chat_history_block.py
+++ b/camel/memories/blocks/chat_history_block.py
@@ -16,7 +16,8 @@ from typing import List, Optional
from camel.memories.base import MemoryBlock
from camel.memories.records import ContextRecord, MemoryRecord
-from camel.storages import BaseKeyValueStorage, InMemoryKeyValueStorage
+from camel.storages.key_value_storages.base import BaseKeyValueStorage
+from camel.storages.key_value_storages.in_memory import InMemoryKeyValueStorage
from camel.types import OpenAIBackendRole
diff --git a/camel/storages/key_value_storages/mem0_cloud.py b/camel/storages/key_value_storages/mem0_cloud.py
index 76875bf00..40fb98426 100644
--- a/camel/storages/key_value_storages/mem0_cloud.py
+++ b/camel/storages/key_value_storages/mem0_cloud.py
@@ -32,12 +32,14 @@ class Mem0Storage(BaseKeyValueStorage):
search, and manage text with context.
Args:
- api_key (str, optional): The API key for authentication. If not provided,
- will try to get from environment variable MEM0_API_KEY.
- user_id (str, optional): Default user ID to associate memories with.
- agent_id (str, optional): Default agent ID to associate memories with.
+ agent_id (str): Default agent ID to associate memories with.
+ api_key (str, optional): The API key for authentication. If not
+ provided, will try to get from environment variable MEM0_API_KEY
+ (default: :obj:`None`).
+ user_id (str, optional): Default user ID to associate memories with
+ (default: :obj:`None`).
metadata (Dict[str, Any], optional): Default metadata to include with
- all memories.
+ all memories (default: :obj:`None`).
References:
https://docs.mem0.ai
@@ -78,7 +80,20 @@ class Mem0Storage(BaseKeyValueStorage):
metadata: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> Dict[str, Any]:
- """Helper method to prepare options for Mem0 API calls."""
+ r"""Helper method to prepare options for Mem0 API calls.
+
+ Args:
+ agent_id (Optional[str], optional): Agent ID to use (default:
+ :obj:`None`).
+ user_id (Optional[str], optional): User ID to use (default:
+ :obj:`None`).
+ metadata (Optional[Dict[str, Any]], optional): Additional metadata
+ to include (default: :obj:`None`).
+ **kwargs (Any): Additional keyword arguments.
+
+ Returns:
+ Dict[str, Any]: Prepared options dictionary for API calls.
+ """
options = {
"agent_id": agent_id or self.agent_id,
"user_id": user_id or self.user_id,
@@ -94,8 +109,20 @@ class Mem0Storage(BaseKeyValueStorage):
user_id: Optional[str] = None,
filters: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
- """Helper method to prepare filters for Mem0 API calls."""
- base_filters = {"AND": []}
+ r"""Helper method to prepare filters for Mem0 API calls.
+
+ Args:
+ agent_id (Optional[str], optional): Agent ID to filter by
+ (default: :obj:`None`).
+ user_id (Optional[str], optional): User ID to filter by (default:
+ :obj:`None`).
+ filters (Optional[Dict[str, Any]], optional): Additional filters
+ (default: :obj:`None`).
+
+ Returns:
+ Dict[str, Any]: Prepared filters dictionary for API calls.
+ """
+ base_filters: Dict[str, Any] = {"AND": []}
if filters:
base_filters["AND"].append(filters)
if agent_id or self.agent_id:
@@ -108,6 +135,14 @@ class Mem0Storage(BaseKeyValueStorage):
self,
records: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
+ r"""Prepare messages from records for Mem0 API calls.
+
+ Args:
+ records (List[Dict[str, Any]]): List of record dictionaries.
+
+ Returns:
+ List[Dict[str, Any]]: List of prepared message dictionaries.
+ """
messages = []
for record in records:
content = record["message"]["content"]
@@ -115,8 +150,13 @@ class Mem0Storage(BaseKeyValueStorage):
messages.append({"role": role, "content": content})
return messages
- def save(self, records: List[Dict[str, Any]]) -> Dict[str, Any]:
- """Add a memory or list of memories to Mem0 storage."""
+ def save(self, records: List[Dict[str, Any]]) -> None:
+ r"""Saves a batch of records to the Mem0 storage system.
+
+ Args:
+ records (List[Dict[str, Any]]): A list of dictionaries, where each
+ dictionary represents a unique record to be stored.
+ """
try:
messages = self._prepare_messages(records)
@@ -125,13 +165,18 @@ class Mem0Storage(BaseKeyValueStorage):
user_id=self.user_id,
metadata=self.metadata,
)
- return self.client.add(messages, **options)
+ self.client.add(messages, **options)
except Exception as e:
logger.error(f"Error adding memory: {e}")
- return {"error": str(e)}
+ logger.error(f"Error: {e}")
def load(self) -> List[Dict[str, Any]]:
- """Load all memories from Mem0 storage."""
+ r"""Loads all stored records from the Mem0 storage system.
+
+ Returns:
+ List[Dict[str, Any]]: A list of dictionaries, where each dictionary
+ represents a stored record.
+ """
try:
filters = self._prepare_filters(
agent_id=self.agent_id,
@@ -166,14 +211,14 @@ class Mem0Storage(BaseKeyValueStorage):
def clear(
self,
- ) -> Dict[str, Any]:
- """Delete all memories from Mem0 storage."""
+ ) -> None:
+ r"""Removes all records from the Mem0 storage system."""
try:
filters = self._prepare_filters(
agent_id=self.agent_id,
user_id=self.user_id,
)
- return self.client.delete_users(**filters)
+ self.client.delete_users(**filters)
except Exception as e:
logger.error(f"Error deleting memories: {e}")
- return {"error": str(e)}
+ logger.error(f"Error: {e}")
diff --git a/pyproject.toml b/pyproject.toml
index 97f69ba63..67aeb07a2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -458,5 +458,6 @@ module = [
"fpdf",
"mcp",
"typer",
+ "mem0",
]
ignore_missing_imports = true
diff --git a/test/storages/key_value_storages/test_mem0_cloud.py b/test/storages/key_value_storages/test_mem0_cloud.py
index 74c52588a..56e320771 100644
--- a/test/storages/key_value_storages/test_mem0_cloud.py
+++ b/test/storages/key_value_storages/test_mem0_cloud.py
@@ -23,7 +23,7 @@ from camel.types import OpenAIBackendRole
class TestMem0Storage(unittest.TestCase):
- """Unit tests for the Mem0Storage class."""
+ r"""Unit tests for the Mem0Storage class."""
def setUp(self):
"""Set up test fixtures before each test method."""
@@ -48,18 +48,18 @@ class TestMem0Storage(unittest.TestCase):
)
def tearDown(self):
- """Clean up test fixtures after each test method."""
+ r"""Clean up test fixtures after each test method."""
self.patcher.stop()
def test_initialization(self):
- """Test proper initialization of Mem0Storage."""
+ r"""Test proper initialization of Mem0Storage."""
self.assertIsInstance(self.storage, BaseKeyValueStorage)
self.assertEqual(self.storage.user_id, self.user_id)
self.assertEqual(self.storage.agent_id, self.agent_id)
self.assertEqual(self.storage.metadata, self.metadata)
def test_initialization_required_agent_id(self):
- """Test initialization with required agent_id parameter."""
+ r"""Test initialization with required agent_id parameter."""
storage = Mem0Storage(api_key=self.api_key, agent_id="required_agent")
self.assertIsNotNone(storage)
self.assertIsNone(storage.user_id)
@@ -67,7 +67,7 @@ class TestMem0Storage(unittest.TestCase):
self.assertEqual(storage.metadata, {})
def test_save(self):
- """Test saving records to Mem0 storage."""
+ r"""Test saving records to Mem0 storage."""
# Create test records
records = [
{
@@ -100,7 +100,7 @@ class TestMem0Storage(unittest.TestCase):
self.assertEqual(kwargs.get("metadata"), self.metadata)
def test_load(self):
- """Test loading records from Mem0 storage."""
+ r"""Test loading records from Mem0 storage."""
# Setup mock return value
mock_results = [
{
@@ -145,7 +145,7 @@ class TestMem0Storage(unittest.TestCase):
)
def test_clear(self):
- """Test clearing all records from Mem0 storage."""
+ r"""Test clearing all records from Mem0 storage."""
# Call clear method
self.storage.clear()
@@ -162,7 +162,7 @@ class TestMem0Storage(unittest.TestCase):
self.assertEqual(kwargs[key], value)
def test_error_handling_save(self):
- """Test error handling for save method."""
+ r"""Test error handling for save method."""
self.mock_mem0_client.add.side_effect = Exception("API Error")
records = [
@@ -172,27 +172,43 @@ class TestMem0Storage(unittest.TestCase):
}
]
- result = self.storage.save(records)
- self.assertIn("error", result)
- self.assertEqual(result["error"], "API Error")
+ # The method doesn't return anything, it just logs the error
+ with self.assertLogs(level='ERROR') as log_context:
+ self.storage.save(records)
+
+ # Check that the error was logged
+ self.assertTrue(
+ any(
+ "Error adding memory: API Error" in message
+ for message in log_context.output
+ )
+ )
def test_error_handling_load(self):
- """Test error handling for load method."""
+ r"""Test error handling for load method."""
self.mock_mem0_client.get_all.side_effect = Exception("API Error")
results = self.storage.load()
self.assertEqual(results, [])
def test_error_handling_clear(self):
- """Test error handling for clear method."""
+ r"""Test error handling for clear method."""
self.mock_mem0_client.delete_users.side_effect = Exception("API Error")
- result = self.storage.clear()
- self.assertIn("error", result)
- self.assertEqual(result["error"], "API Error")
+ # The method doesn't return anything, it just logs the error
+ with self.assertLogs(level='ERROR') as log_context:
+ self.storage.clear()
+
+ # Check that the error was logged
+ self.assertTrue(
+ any(
+ "Error deleting memories: API Error" in message
+ for message in log_context.output
+ )
+ )
def test_prepare_messages(self):
- """Test message preparation helper method."""
+ r"""Test message preparation helper method."""
records = [
{
"message": {"content": "test message 1"},
@@ -217,7 +233,7 @@ class TestMem0Storage(unittest.TestCase):
not os.getenv("MEM0_API_KEY"), reason="MEM0_API_KEY not set"
)
def test_integration(self):
- """Integration test with actual Mem0 API.
+ r"""Integration test with actual Mem0 API.
This test is skipped unless MEM0_API_KEY environment variable is set.
"""
diff --git a/test/toolkits/test_code_execution.py b/test/toolkits/test_code_execution.py
index b62915b0e..c0e732e47 100644
--- a/test/toolkits/test_code_execution.py
+++ b/test/toolkits/test_code_execution.py
@@ -57,7 +57,7 @@ def test_execute_code(code_execution_toolkit):
result = code_execution_toolkit.execute_code(code)
# ruff: noqa: E501
- expected_result = f"Executed the code below:\n```py\n{code}\n```\n> Executed Results:\nab"
+ expected_result = f"Executed the code below:\n```py\n{code}\n```\n> Executed Results:\n'ab'\n"
assert expected_result == result
diff --git a/test/toolkits/test_mcp_toolkit.py b/test/toolkits/test_mcp_toolkit.py
index 025d76d97..20ce8d005 100644
--- a/test/toolkits/test_mcp_toolkit.py
+++ b/test/toolkits/test_mcp_toolkit.py
@@ -83,7 +83,9 @@ class Test_MCPServer:
assert connected_server._mcp_tools == ["tool1", "tool2"]
# Verify mocks were called correctly
- mock_sse_client.assert_called_once_with("https://example.com/api")
+ mock_sse_client.assert_called_once_with(
+ "https://example.com/api", headers={}
+ )
mock_session.assert_called_once()
mock_session_instance.initialize.assert_called_once()
mock_session_instance.list_tools.assert_called_once()
@@ -369,7 +371,9 @@ class Test_MCPServer:
assert server._session is not None
# Verify mocks were called correctly
- mock_sse_client.assert_called_once_with("https://example.com/api")
+ mock_sse_client.assert_called_once_with(
+ "https://example.com/api", headers={}
+ )
mock_session.assert_called_once()
mock_session_instance.initialize.assert_called_once()
mock_session_instance.list_tools.assert_called_once()