[Misc] Lint code and fix code smells (#1871)

This commit is contained in:
Deshraj Yadav
2024-09-16 17:39:54 -07:00
committed by GitHub
parent 0a78cb9f7a
commit 55c54beeab
57 changed files with 1178 additions and 1357 deletions

View File

@@ -37,9 +37,7 @@ def test_embed_custom_model(mock_sentence_transformer):
def test_embed_with_model_kwargs(mock_sentence_transformer):
config = BaseEmbedderConfig(
model="all-MiniLM-L6-v2", model_kwargs={"device": "cuda"}
)
config = BaseEmbedderConfig(model="all-MiniLM-L6-v2", model_kwargs={"device": "cuda"})
embedder = HuggingFaceEmbedding(config)
mock_sentence_transformer.encode.return_value = [0.7, 0.8, 0.9]

View File

@@ -23,9 +23,7 @@ def test_embed_text(mock_ollama_client):
text = "Sample text to embed."
embedding = embedder.embed(text)
mock_ollama_client.embeddings.assert_called_once_with(
model="nomic-embed-text", prompt=text
)
mock_ollama_client.embeddings.assert_called_once_with(model="nomic-embed-text", prompt=text)
assert embedding == [0.1, 0.2, 0.3, 0.4, 0.5]

View File

@@ -21,9 +21,7 @@ def test_embed_default_model(mock_openai_client):
result = embedder.embed("Hello world")
mock_openai_client.embeddings.create.assert_called_once_with(
input=["Hello world"], model="text-embedding-3-small"
)
mock_openai_client.embeddings.create.assert_called_once_with(input=["Hello world"], model="text-embedding-3-small")
assert result == [0.1, 0.2, 0.3]
@@ -51,9 +49,7 @@ def test_embed_removes_newlines(mock_openai_client):
result = embedder.embed("Hello\nworld")
mock_openai_client.embeddings.create.assert_called_once_with(
input=["Hello world"], model="text-embedding-3-small"
)
mock_openai_client.embeddings.create.assert_called_once_with(input=["Hello world"], model="text-embedding-3-small")
assert result == [0.7, 0.8, 0.9]

View File

@@ -1,4 +1,3 @@
from unittest.mock import Mock, patch
import httpx
@@ -7,26 +6,28 @@ import pytest
from mem0.configs.llms.base import BaseLlmConfig
from mem0.llms.azure_openai import AzureOpenAILLM
MODEL = "gpt-4o" # or your custom deployment name
MODEL = "gpt-4o" # or your custom deployment name
TEMPERATURE = 0.7
MAX_TOKENS = 100
TOP_P = 1.0
@pytest.fixture
def mock_openai_client():
with patch('mem0.llms.azure_openai.AzureOpenAI') as mock_openai:
with patch("mem0.llms.azure_openai.AzureOpenAI") as mock_openai:
mock_client = Mock()
mock_openai.return_value = mock_client
yield mock_client
def test_generate_response_without_tools(mock_openai_client):
config = BaseLlmConfig(model=MODEL, temperature=TEMPERATURE, max_tokens=MAX_TOKENS, top_p=TOP_P)
llm = AzureOpenAILLM(config)
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello, how are you?"}
{"role": "user", "content": "Hello, how are you?"},
]
mock_response = Mock()
mock_response.choices = [Mock(message=Mock(content="I'm doing well, thank you for asking!"))]
mock_openai_client.chat.completions.create.return_value = mock_response
@@ -34,11 +35,7 @@ def test_generate_response_without_tools(mock_openai_client):
response = llm.generate_response(messages)
mock_openai_client.chat.completions.create.assert_called_once_with(
model=MODEL,
messages=messages,
temperature=TEMPERATURE,
max_tokens=MAX_TOKENS,
top_p=TOP_P
model=MODEL, messages=messages, temperature=TEMPERATURE, max_tokens=MAX_TOKENS, top_p=TOP_P
)
assert response == "I'm doing well, thank you for asking!"
@@ -48,7 +45,7 @@ def test_generate_response_with_tools(mock_openai_client):
llm = AzureOpenAILLM(config)
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Add a new memory: Today is a sunny day."}
{"role": "user", "content": "Add a new memory: Today is a sunny day."},
]
tools = [
{
@@ -58,23 +55,21 @@ def test_generate_response_with_tools(mock_openai_client):
"description": "Add a memory",
"parameters": {
"type": "object",
"properties": {
"data": {"type": "string", "description": "Data to add to memory"}
},
"properties": {"data": {"type": "string", "description": "Data to add to memory"}},
"required": ["data"],
},
},
}
]
mock_response = Mock()
mock_message = Mock()
mock_message.content = "I've added the memory for you."
mock_tool_call = Mock()
mock_tool_call.function.name = "add_memory"
mock_tool_call.function.arguments = '{"data": "Today is a sunny day."}'
mock_message.tool_calls = [mock_tool_call]
mock_response.choices = [Mock(message=mock_message)]
mock_openai_client.chat.completions.create.return_value = mock_response
@@ -88,24 +83,33 @@ def test_generate_response_with_tools(mock_openai_client):
max_tokens=MAX_TOKENS,
top_p=TOP_P,
tools=tools,
tool_choice="auto"
tool_choice="auto",
)
assert response["content"] == "I've added the memory for you."
assert len(response["tool_calls"]) == 1
assert response["tool_calls"][0]["name"] == "add_memory"
assert response["tool_calls"][0]["arguments"] == {'data': 'Today is a sunny day.'}
assert response["tool_calls"][0]["arguments"] == {"data": "Today is a sunny day."}
def test_generate_with_http_proxies():
mock_http_client = Mock(spec=httpx.Client)
mock_http_client_instance = Mock(spec=httpx.Client)
mock_http_client.return_value = mock_http_client_instance
with (patch("mem0.llms.azure_openai.AzureOpenAI") as mock_azure_openai,
patch("httpx.Client", new=mock_http_client) as mock_http_client):
config = BaseLlmConfig(model=MODEL, temperature=TEMPERATURE, max_tokens=MAX_TOKENS, top_p=TOP_P,
api_key="test", http_client_proxies="http://testproxy.mem0.net:8000",
azure_kwargs= {"api_key" : "test"})
with (
patch("mem0.llms.azure_openai.AzureOpenAI") as mock_azure_openai,
patch("httpx.Client", new=mock_http_client) as mock_http_client,
):
config = BaseLlmConfig(
model=MODEL,
temperature=TEMPERATURE,
max_tokens=MAX_TOKENS,
top_p=TOP_P,
api_key="test",
http_client_proxies="http://testproxy.mem0.net:8000",
azure_kwargs={"api_key": "test"},
)
_ = AzureOpenAILLM(config)
@@ -114,6 +118,6 @@ def test_generate_with_http_proxies():
http_client=mock_http_client_instance,
azure_deployment=None,
azure_endpoint=None,
api_version=None
api_version=None,
)
mock_http_client.assert_called_once_with(proxies="http://testproxy.mem0.net:8000")

View File

@@ -8,7 +8,7 @@ from mem0.llms.groq import GroqLLM
@pytest.fixture
def mock_groq_client():
with patch('mem0.llms.groq.Groq') as mock_groq:
with patch("mem0.llms.groq.Groq") as mock_groq:
mock_client = Mock()
mock_groq.return_value = mock_client
yield mock_client
@@ -19,9 +19,9 @@ def test_generate_response_without_tools(mock_groq_client):
llm = GroqLLM(config)
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello, how are you?"}
{"role": "user", "content": "Hello, how are you?"},
]
mock_response = Mock()
mock_response.choices = [Mock(message=Mock(content="I'm doing well, thank you for asking!"))]
mock_groq_client.chat.completions.create.return_value = mock_response
@@ -29,11 +29,7 @@ def test_generate_response_without_tools(mock_groq_client):
response = llm.generate_response(messages)
mock_groq_client.chat.completions.create.assert_called_once_with(
model="llama3-70b-8192",
messages=messages,
temperature=0.7,
max_tokens=100,
top_p=1.0
model="llama3-70b-8192", messages=messages, temperature=0.7, max_tokens=100, top_p=1.0
)
assert response == "I'm doing well, thank you for asking!"
@@ -43,7 +39,7 @@ def test_generate_response_with_tools(mock_groq_client):
llm = GroqLLM(config)
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Add a new memory: Today is a sunny day."}
{"role": "user", "content": "Add a new memory: Today is a sunny day."},
]
tools = [
{
@@ -53,23 +49,21 @@ def test_generate_response_with_tools(mock_groq_client):
"description": "Add a memory",
"parameters": {
"type": "object",
"properties": {
"data": {"type": "string", "description": "Data to add to memory"}
},
"properties": {"data": {"type": "string", "description": "Data to add to memory"}},
"required": ["data"],
},
},
}
]
mock_response = Mock()
mock_message = Mock()
mock_message.content = "I've added the memory for you."
mock_tool_call = Mock()
mock_tool_call.function.name = "add_memory"
mock_tool_call.function.arguments = '{"data": "Today is a sunny day."}'
mock_message.tool_calls = [mock_tool_call]
mock_response.choices = [Mock(message=mock_message)]
mock_groq_client.chat.completions.create.return_value = mock_response
@@ -83,11 +77,10 @@ def test_generate_response_with_tools(mock_groq_client):
max_tokens=100,
top_p=1.0,
tools=tools,
tool_choice="auto"
tool_choice="auto",
)
assert response["content"] == "I've added the memory for you."
assert len(response["tool_calls"]) == 1
assert response["tool_calls"][0]["name"] == "add_memory"
assert response["tool_calls"][0]["arguments"] == {'data': 'Today is a sunny day.'}
assert response["tool_calls"][0]["arguments"] == {"data": "Today is a sunny day."}

View File

@@ -8,14 +8,15 @@ from mem0.llms import litellm
@pytest.fixture
def mock_litellm():
with patch('mem0.llms.litellm.litellm') as mock_litellm:
with patch("mem0.llms.litellm.litellm") as mock_litellm:
yield mock_litellm
def test_generate_response_with_unsupported_model(mock_litellm):
config = BaseLlmConfig(model="unsupported-model", temperature=0.7, max_tokens=100, top_p=1)
llm = litellm.LiteLLM(config)
messages = [{"role": "user", "content": "Hello"}]
mock_litellm.supports_function_calling.return_value = False
with pytest.raises(ValueError, match="Model 'unsupported-model' in litellm does not support function calling."):
@@ -27,9 +28,9 @@ def test_generate_response_without_tools(mock_litellm):
llm = litellm.LiteLLM(config)
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello, how are you?"}
{"role": "user", "content": "Hello, how are you?"},
]
mock_response = Mock()
mock_response.choices = [Mock(message=Mock(content="I'm doing well, thank you for asking!"))]
mock_litellm.completion.return_value = mock_response
@@ -38,11 +39,7 @@ def test_generate_response_without_tools(mock_litellm):
response = llm.generate_response(messages)
mock_litellm.completion.assert_called_once_with(
model="gpt-4o",
messages=messages,
temperature=0.7,
max_tokens=100,
top_p=1.0
model="gpt-4o", messages=messages, temperature=0.7, max_tokens=100, top_p=1.0
)
assert response == "I'm doing well, thank you for asking!"
@@ -52,7 +49,7 @@ def test_generate_response_with_tools(mock_litellm):
llm = litellm.LiteLLM(config)
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Add a new memory: Today is a sunny day."}
{"role": "user", "content": "Add a new memory: Today is a sunny day."},
]
tools = [
{
@@ -62,23 +59,21 @@ def test_generate_response_with_tools(mock_litellm):
"description": "Add a memory",
"parameters": {
"type": "object",
"properties": {
"data": {"type": "string", "description": "Data to add to memory"}
},
"properties": {"data": {"type": "string", "description": "Data to add to memory"}},
"required": ["data"],
},
},
}
]
mock_response = Mock()
mock_message = Mock()
mock_message.content = "I've added the memory for you."
mock_tool_call = Mock()
mock_tool_call.function.name = "add_memory"
mock_tool_call.function.arguments = '{"data": "Today is a sunny day."}'
mock_message.tool_calls = [mock_tool_call]
mock_response.choices = [Mock(message=mock_message)]
mock_litellm.completion.return_value = mock_response
@@ -87,16 +82,10 @@ def test_generate_response_with_tools(mock_litellm):
response = llm.generate_response(messages, tools=tools)
mock_litellm.completion.assert_called_once_with(
model="gpt-4o",
messages=messages,
temperature=0.7,
max_tokens=100,
top_p=1,
tools=tools,
tool_choice="auto"
model="gpt-4o", messages=messages, temperature=0.7, max_tokens=100, top_p=1, tools=tools, tool_choice="auto"
)
assert response["content"] == "I've added the memory for you."
assert len(response["tool_calls"]) == 1
assert response["tool_calls"][0]["name"] == "add_memory"
assert response["tool_calls"][0]["arguments"] == {'data': 'Today is a sunny day.'}
assert response["tool_calls"][0]["arguments"] == {"data": "Today is a sunny day."}

View File

@@ -9,61 +9,48 @@ from mem0.llms.utils.tools import ADD_MEMORY_TOOL
@pytest.fixture
def mock_ollama_client():
with patch('mem0.llms.ollama.Client') as mock_ollama:
with patch("mem0.llms.ollama.Client") as mock_ollama:
mock_client = Mock()
mock_client.list.return_value = {"models": [{"name": "llama3.1:70b"}]}
mock_ollama.return_value = mock_client
yield mock_client
def test_generate_response_without_tools(mock_ollama_client):
config = BaseLlmConfig(model="llama3.1:70b", temperature=0.7, max_tokens=100, top_p=1.0)
llm = OllamaLLM(config)
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello, how are you?"}
{"role": "user", "content": "Hello, how are you?"},
]
mock_response = {
'message': {"content": "I'm doing well, thank you for asking!"}
}
mock_response = {"message": {"content": "I'm doing well, thank you for asking!"}}
mock_ollama_client.chat.return_value = mock_response
response = llm.generate_response(messages)
mock_ollama_client.chat.assert_called_once_with(
model="llama3.1:70b",
messages=messages,
options={
"temperature": 0.7,
"num_predict": 100,
"top_p": 1.0
}
model="llama3.1:70b", messages=messages, options={"temperature": 0.7, "num_predict": 100, "top_p": 1.0}
)
assert response == "I'm doing well, thank you for asking!"
def test_generate_response_with_tools(mock_ollama_client):
config = BaseLlmConfig(model="llama3.1:70b", temperature=0.7, max_tokens=100, top_p=1.0)
llm = OllamaLLM(config)
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Add a new memory: Today is a sunny day."}
{"role": "user", "content": "Add a new memory: Today is a sunny day."},
]
tools = [ADD_MEMORY_TOOL]
mock_response = {
'message': {
"message": {
"content": "I've added the memory for you.",
"tool_calls": [
{
"function": {
"name": "add_memory",
"arguments": {"data": "Today is a sunny day."}
}
}
]
"tool_calls": [{"function": {"name": "add_memory", "arguments": {"data": "Today is a sunny day."}}}],
}
}
mock_ollama_client.chat.return_value = mock_response
response = llm.generate_response(messages, tools=tools)
@@ -71,16 +58,11 @@ def test_generate_response_with_tools(mock_ollama_client):
mock_ollama_client.chat.assert_called_once_with(
model="llama3.1:70b",
messages=messages,
options={
"temperature": 0.7,
"num_predict": 100,
"top_p": 1.0
},
tools=tools
options={"temperature": 0.7, "num_predict": 100, "top_p": 1.0},
tools=tools,
)
assert response["content"] == "I've added the memory for you."
assert len(response["tool_calls"]) == 1
assert response["tool_calls"][0]["name"] == "add_memory"
assert response["tool_calls"][0]["arguments"] == {'data': 'Today is a sunny day.'}
assert response["tool_calls"][0]["arguments"] == {"data": "Today is a sunny day."}

View File

@@ -8,7 +8,7 @@ from mem0.llms.openai import OpenAILLM
@pytest.fixture
def mock_openai_client():
with patch('mem0.llms.openai.OpenAI') as mock_openai:
with patch("mem0.llms.openai.OpenAI") as mock_openai:
mock_client = Mock()
mock_openai.return_value = mock_client
yield mock_client
@@ -19,9 +19,9 @@ def test_generate_response_without_tools(mock_openai_client):
llm = OpenAILLM(config)
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello, how are you?"}
{"role": "user", "content": "Hello, how are you?"},
]
mock_response = Mock()
mock_response.choices = [Mock(message=Mock(content="I'm doing well, thank you for asking!"))]
mock_openai_client.chat.completions.create.return_value = mock_response
@@ -29,11 +29,7 @@ def test_generate_response_without_tools(mock_openai_client):
response = llm.generate_response(messages)
mock_openai_client.chat.completions.create.assert_called_once_with(
model="gpt-4o",
messages=messages,
temperature=0.7,
max_tokens=100,
top_p=1.0
model="gpt-4o", messages=messages, temperature=0.7, max_tokens=100, top_p=1.0
)
assert response == "I'm doing well, thank you for asking!"
@@ -43,7 +39,7 @@ def test_generate_response_with_tools(mock_openai_client):
llm = OpenAILLM(config)
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Add a new memory: Today is a sunny day."}
{"role": "user", "content": "Add a new memory: Today is a sunny day."},
]
tools = [
{
@@ -53,23 +49,21 @@ def test_generate_response_with_tools(mock_openai_client):
"description": "Add a memory",
"parameters": {
"type": "object",
"properties": {
"data": {"type": "string", "description": "Data to add to memory"}
},
"properties": {"data": {"type": "string", "description": "Data to add to memory"}},
"required": ["data"],
},
},
}
]
mock_response = Mock()
mock_message = Mock()
mock_message.content = "I've added the memory for you."
mock_tool_call = Mock()
mock_tool_call.function.name = "add_memory"
mock_tool_call.function.arguments = '{"data": "Today is a sunny day."}'
mock_message.tool_calls = [mock_tool_call]
mock_response.choices = [Mock(message=mock_message)]
mock_openai_client.chat.completions.create.return_value = mock_response
@@ -77,17 +71,10 @@ def test_generate_response_with_tools(mock_openai_client):
response = llm.generate_response(messages, tools=tools)
mock_openai_client.chat.completions.create.assert_called_once_with(
model="gpt-4o",
messages=messages,
temperature=0.7,
max_tokens=100,
top_p=1.0,
tools=tools,
tool_choice="auto"
model="gpt-4o", messages=messages, temperature=0.7, max_tokens=100, top_p=1.0, tools=tools, tool_choice="auto"
)
assert response["content"] == "I've added the memory for you."
assert len(response["tool_calls"]) == 1
assert response["tool_calls"][0]["name"] == "add_memory"
assert response["tool_calls"][0]["arguments"] == {'data': 'Today is a sunny day.'}
assert response["tool_calls"][0]["arguments"] == {"data": "Today is a sunny day."}

View File

@@ -8,7 +8,7 @@ from mem0.llms.together import TogetherLLM
@pytest.fixture
def mock_together_client():
with patch('mem0.llms.together.Together') as mock_together:
with patch("mem0.llms.together.Together") as mock_together:
mock_client = Mock()
mock_together.return_value = mock_client
yield mock_client
@@ -19,9 +19,9 @@ def test_generate_response_without_tools(mock_together_client):
llm = TogetherLLM(config)
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello, how are you?"}
{"role": "user", "content": "Hello, how are you?"},
]
mock_response = Mock()
mock_response.choices = [Mock(message=Mock(content="I'm doing well, thank you for asking!"))]
mock_together_client.chat.completions.create.return_value = mock_response
@@ -29,11 +29,7 @@ def test_generate_response_without_tools(mock_together_client):
response = llm.generate_response(messages)
mock_together_client.chat.completions.create.assert_called_once_with(
model="mistralai/Mixtral-8x7B-Instruct-v0.1",
messages=messages,
temperature=0.7,
max_tokens=100,
top_p=1.0
model="mistralai/Mixtral-8x7B-Instruct-v0.1", messages=messages, temperature=0.7, max_tokens=100, top_p=1.0
)
assert response == "I'm doing well, thank you for asking!"
@@ -43,7 +39,7 @@ def test_generate_response_with_tools(mock_together_client):
llm = TogetherLLM(config)
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Add a new memory: Today is a sunny day."}
{"role": "user", "content": "Add a new memory: Today is a sunny day."},
]
tools = [
{
@@ -53,23 +49,21 @@ def test_generate_response_with_tools(mock_together_client):
"description": "Add a memory",
"parameters": {
"type": "object",
"properties": {
"data": {"type": "string", "description": "Data to add to memory"}
},
"properties": {"data": {"type": "string", "description": "Data to add to memory"}},
"required": ["data"],
},
},
}
]
mock_response = Mock()
mock_message = Mock()
mock_message.content = "I've added the memory for you."
mock_tool_call = Mock()
mock_tool_call.function.name = "add_memory"
mock_tool_call.function.arguments = '{"data": "Today is a sunny day."}'
mock_message.tool_calls = [mock_tool_call]
mock_response.choices = [Mock(message=mock_message)]
mock_together_client.chat.completions.create.return_value = mock_response
@@ -83,11 +77,10 @@ def test_generate_response_with_tools(mock_together_client):
max_tokens=100,
top_p=1.0,
tools=tools,
tool_choice="auto"
tool_choice="auto",
)
assert response["content"] == "I've added the memory for you."
assert len(response["tool_calls"]) == 1
assert response["tool_calls"][0]["name"] == "add_memory"
assert response["tool_calls"][0]["arguments"] == {'data': 'Today is a sunny day.'}
assert response["tool_calls"][0]["arguments"] == {"data": "Today is a sunny day."}

View File

@@ -4,42 +4,39 @@ from unittest.mock import Mock, patch
from mem0.memory.main import Memory
from mem0.configs.base import MemoryConfig
@pytest.fixture(autouse=True)
def mock_openai():
os.environ['OPENAI_API_KEY'] = "123"
with patch('openai.OpenAI') as mock:
os.environ["OPENAI_API_KEY"] = "123"
with patch("openai.OpenAI") as mock:
mock.return_value = Mock()
yield mock
@pytest.fixture
def memory_instance():
with patch('mem0.utils.factory.EmbedderFactory') as mock_embedder, \
patch('mem0.utils.factory.VectorStoreFactory') as mock_vector_store, \
patch('mem0.utils.factory.LlmFactory') as mock_llm, \
patch('mem0.memory.telemetry.capture_event'), \
patch('mem0.memory.graph_memory.MemoryGraph'):
with patch("mem0.utils.factory.EmbedderFactory") as mock_embedder, patch(
"mem0.utils.factory.VectorStoreFactory"
) as mock_vector_store, patch("mem0.utils.factory.LlmFactory") as mock_llm, patch(
"mem0.memory.telemetry.capture_event"
), patch("mem0.memory.graph_memory.MemoryGraph"):
mock_embedder.create.return_value = Mock()
mock_vector_store.create.return_value = Mock()
mock_llm.create.return_value = Mock()
config = MemoryConfig(version="v1.1")
config.graph_store.config = {"some_config": "value"}
return Memory(config)
@pytest.mark.parametrize("version, enable_graph", [
("v1.0", False),
("v1.1", True)
])
@pytest.mark.parametrize("version, enable_graph", [("v1.0", False), ("v1.1", True)])
def test_add(memory_instance, version, enable_graph):
memory_instance.config.version = version
memory_instance.enable_graph = enable_graph
memory_instance._add_to_vector_store = Mock(return_value=[{"memory": "Test memory", "event": "ADD"}])
memory_instance._add_to_graph = Mock(return_value=[])
result = memory_instance.add(
messages=[{"role": "user", "content": "Test message"}],
user_id="test_user"
)
result = memory_instance.add(messages=[{"role": "user", "content": "Test message"}], user_id="test_user")
assert "results" in result
assert result["results"] == [{"memory": "Test memory", "event": "ADD"}]
@@ -47,26 +44,27 @@ def test_add(memory_instance, version, enable_graph):
assert result["relations"] == []
memory_instance._add_to_vector_store.assert_called_once_with(
[{"role": "user", "content": "Test message"}],
{"user_id": "test_user"},
{"user_id": "test_user"}
)
# Remove the conditional assertion for _add_to_graph
memory_instance._add_to_graph.assert_called_once_with(
[{"role": "user", "content": "Test message"}],
{"user_id": "test_user"}
[{"role": "user", "content": "Test message"}], {"user_id": "test_user"}, {"user_id": "test_user"}
)
# Remove the conditional assertion for _add_to_graph
memory_instance._add_to_graph.assert_called_once_with(
[{"role": "user", "content": "Test message"}], {"user_id": "test_user"}
)
def test_get(memory_instance):
mock_memory = Mock(id="test_id", payload={
"data": "Test memory",
"user_id": "test_user",
"hash": "test_hash",
"created_at": "2023-01-01T00:00:00",
"updated_at": "2023-01-02T00:00:00",
"extra_field": "extra_value"
})
mock_memory = Mock(
id="test_id",
payload={
"data": "Test memory",
"user_id": "test_user",
"hash": "test_hash",
"created_at": "2023-01-01T00:00:00",
"updated_at": "2023-01-02T00:00:00",
"extra_field": "extra_value",
},
)
memory_instance.vector_store.get = Mock(return_value=mock_memory)
result = memory_instance.get("test_id")
@@ -79,16 +77,14 @@ def test_get(memory_instance):
assert result["updated_at"] == "2023-01-02T00:00:00"
assert result["metadata"] == {"extra_field": "extra_value"}
@pytest.mark.parametrize("version, enable_graph", [
("v1.0", False),
("v1.1", True)
])
@pytest.mark.parametrize("version, enable_graph", [("v1.0", False), ("v1.1", True)])
def test_search(memory_instance, version, enable_graph):
memory_instance.config.version = version
memory_instance.enable_graph = enable_graph
mock_memories = [
Mock(id="1", payload={"data": "Memory 1", "user_id": "test_user"}, score=0.9),
Mock(id="2", payload={"data": "Memory 2", "user_id": "test_user"}, score=0.8)
Mock(id="2", payload={"data": "Memory 2", "user_id": "test_user"}, score=0.8),
]
memory_instance.vector_store.search = Mock(return_value=mock_memories)
memory_instance.embedding_model.embed = Mock(return_value=[0.1, 0.2, 0.3])
@@ -118,17 +114,16 @@ def test_search(memory_instance, version, enable_graph):
assert result["results"][0]["score"] == 0.9
memory_instance.vector_store.search.assert_called_once_with(
query=[0.1, 0.2, 0.3],
limit=100,
filters={"user_id": "test_user"}
query=[0.1, 0.2, 0.3], limit=100, filters={"user_id": "test_user"}
)
memory_instance.embedding_model.embed.assert_called_once_with("test query")
if enable_graph:
memory_instance.graph.search.assert_called_once_with("test query", {"user_id": "test_user"})
else:
memory_instance.graph.search.assert_not_called()
def test_update(memory_instance):
memory_instance._update_memory = Mock()
@@ -137,6 +132,7 @@ def test_update(memory_instance):
memory_instance._update_memory.assert_called_once_with("test_id", "Updated memory")
assert result["message"] == "Memory updated successfully!"
def test_delete(memory_instance):
memory_instance._delete_memory = Mock()
@@ -145,10 +141,8 @@ def test_delete(memory_instance):
memory_instance._delete_memory.assert_called_once_with("test_id")
assert result["message"] == "Memory deleted successfully!"
@pytest.mark.parametrize("version, enable_graph", [
("v1.0", False),
("v1.1", True)
])
@pytest.mark.parametrize("version, enable_graph", [("v1.0", False), ("v1.1", True)])
def test_delete_all(memory_instance, version, enable_graph):
memory_instance.config.version = version
memory_instance.enable_graph = enable_graph
@@ -160,14 +154,15 @@ def test_delete_all(memory_instance, version, enable_graph):
result = memory_instance.delete_all(user_id="test_user")
assert memory_instance._delete_memory.call_count == 2
if enable_graph:
memory_instance.graph.delete_all.assert_called_once_with({"user_id": "test_user"})
else:
memory_instance.graph.delete_all.assert_not_called()
assert result["message"] == "Memories deleted successfully!"
def test_reset(memory_instance):
memory_instance.vector_store.delete_col = Mock()
memory_instance.db.reset = Mock()
@@ -177,22 +172,30 @@ def test_reset(memory_instance):
memory_instance.vector_store.delete_col.assert_called_once()
memory_instance.db.reset.assert_called_once()
@pytest.mark.parametrize("version, enable_graph, expected_result", [
("v1.0", False, {"results": [{"id": "1", "memory": "Memory 1", "user_id": "test_user"}]}),
("v1.1", False, {"results": [{"id": "1", "memory": "Memory 1", "user_id": "test_user"}]}),
("v1.1", True, {
"results": [{"id": "1", "memory": "Memory 1", "user_id": "test_user"}],
"relations": [{"source": "entity1", "relationship": "rel", "target": "entity2"}]
})
])
@pytest.mark.parametrize(
"version, enable_graph, expected_result",
[
("v1.0", False, {"results": [{"id": "1", "memory": "Memory 1", "user_id": "test_user"}]}),
("v1.1", False, {"results": [{"id": "1", "memory": "Memory 1", "user_id": "test_user"}]}),
(
"v1.1",
True,
{
"results": [{"id": "1", "memory": "Memory 1", "user_id": "test_user"}],
"relations": [{"source": "entity1", "relationship": "rel", "target": "entity2"}],
},
),
],
)
def test_get_all(memory_instance, version, enable_graph, expected_result):
memory_instance.config.version = version
memory_instance.enable_graph = enable_graph
mock_memories = [Mock(id="1", payload={"data": "Memory 1", "user_id": "test_user"})]
memory_instance.vector_store.list = Mock(return_value=(mock_memories, None))
memory_instance.graph.get_all = Mock(return_value=[
{"source": "entity1", "relationship": "rel", "target": "entity2"}
])
memory_instance.graph.get_all = Mock(
return_value=[{"source": "entity1", "relationship": "rel", "target": "entity2"}]
)
result = memory_instance.get_all(user_id="test_user")
@@ -204,7 +207,7 @@ def test_get_all(memory_instance, version, enable_graph, expected_result):
assert result_item["id"] == expected_item["id"]
assert result_item["memory"] == expected_item["memory"]
assert result_item["user_id"] == expected_item["user_id"]
if enable_graph:
assert "relations" in result
assert result["relations"] == expected_result["relations"]
@@ -212,7 +215,7 @@ def test_get_all(memory_instance, version, enable_graph, expected_result):
assert "relations" not in result
memory_instance.vector_store.list.assert_called_once_with(filters={"user_id": "test_user"}, limit=100)
if enable_graph:
memory_instance.graph.get_all.assert_called_once_with({"user_id": "test_user"})
else:

View File

@@ -7,6 +7,7 @@ from mem0 import Memory
def memory_store():
return Memory()
@pytest.mark.skip(reason="Not implemented")
def test_create_memory(memory_store):
data = "Name is John Doe."

View File

@@ -11,23 +11,26 @@ from mem0.proxy.main import Chat, Completions, Mem0
def mock_memory_client():
return Mock(spec=MemoryClient)
@pytest.fixture
def mock_openai_embedding_client():
with patch('mem0.embeddings.openai.OpenAI') as mock_openai:
with patch("mem0.embeddings.openai.OpenAI") as mock_openai:
mock_client = Mock()
mock_openai.return_value = mock_client
yield mock_client
@pytest.fixture
def mock_openai_llm_client():
with patch('mem0.llms.openai.OpenAI') as mock_openai:
with patch("mem0.llms.openai.OpenAI") as mock_openai:
mock_client = Mock()
mock_openai.return_value = mock_client
yield mock_client
@pytest.fixture
def mock_litellm():
with patch('mem0.proxy.main.litellm') as mock:
with patch("mem0.proxy.main.litellm") as mock:
yield mock
@@ -39,16 +42,16 @@ def test_mem0_initialization_with_api_key(mock_openai_embedding_client, mock_ope
def test_mem0_initialization_with_config():
config = {"some_config": "value"}
with patch('mem0.Memory.from_config') as mock_from_config:
with patch("mem0.Memory.from_config") as mock_from_config:
mem0 = Mem0(config=config)
mock_from_config.assert_called_once_with(config)
assert isinstance(mem0.chat, Chat)
def test_mem0_initialization_without_params(mock_openai_embedding_client, mock_openai_llm_client):
mem0 = Mem0()
assert isinstance(mem0.mem0_client, Memory)
assert isinstance(mem0.chat, Chat)
mem0 = Mem0()
assert isinstance(mem0.mem0_client, Memory)
assert isinstance(mem0.chat, Chat)
def test_chat_initialization(mock_memory_client):
@@ -58,48 +61,37 @@ def test_chat_initialization(mock_memory_client):
def test_completions_create(mock_memory_client, mock_litellm):
completions = Completions(mock_memory_client)
messages = [
{"role": "user", "content": "Hello, how are you?"}
]
messages = [{"role": "user", "content": "Hello, how are you?"}]
mock_memory_client.search.return_value = [{"memory": "Some relevant memory"}]
mock_litellm.completion.return_value = {"choices": [{"message": {"content": "I'm doing well, thank you!"}}]}
response = completions.create(
model="gpt-4o-mini",
messages=messages,
user_id="test_user",
temperature=0.7
)
response = completions.create(model="gpt-4o-mini", messages=messages, user_id="test_user", temperature=0.7)
mock_memory_client.add.assert_called_once()
mock_memory_client.search.assert_called_once()
mock_litellm.completion.assert_called_once()
call_args = mock_litellm.completion.call_args[1]
assert call_args['model'] == "gpt-4o-mini"
assert len(call_args['messages']) == 2
assert call_args['temperature'] == 0.7
assert call_args["model"] == "gpt-4o-mini"
assert len(call_args["messages"]) == 2
assert call_args["temperature"] == 0.7
assert response == {"choices": [{"message": {"content": "I'm doing well, thank you!"}}]}
def test_completions_create_with_system_message(mock_memory_client, mock_litellm):
completions = Completions(mock_memory_client)
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello, how are you?"}
{"role": "user", "content": "Hello, how are you?"},
]
mock_memory_client.search.return_value = [{"memory": "Some relevant memory"}]
mock_litellm.completion.return_value = {"choices": [{"message": {"content": "I'm doing well, thank you!"}}]}
completions.create(
model="gpt-4o-mini",
messages=messages,
user_id="test_user"
)
completions.create(model="gpt-4o-mini", messages=messages, user_id="test_user")
call_args = mock_litellm.completion.call_args[1]
assert call_args['messages'][0]['role'] == "system"
assert call_args['messages'][0]['content'] == MEMORY_ANSWER_PROMPT
assert call_args["messages"][0]["role"] == "system"
assert call_args["messages"][0]["content"] == MEMORY_ANSWER_PROMPT

View File

@@ -7,23 +7,28 @@ MEM0_TELEMETRY = os.environ.get("MEM0_TELEMETRY", "True")
if isinstance(MEM0_TELEMETRY, str):
MEM0_TELEMETRY = MEM0_TELEMETRY.lower() in ("true", "1", "yes")
def use_telemetry():
if os.getenv('MEM0_TELEMETRY', "true").lower() == "true":
if os.getenv("MEM0_TELEMETRY", "true").lower() == "true":
return True
return False
@pytest.fixture(autouse=True)
def reset_env():
with patch.dict(os.environ, {}, clear=True):
yield
def test_telemetry_enabled():
with patch.dict(os.environ, {'MEM0_TELEMETRY': "true"}):
with patch.dict(os.environ, {"MEM0_TELEMETRY": "true"}):
assert use_telemetry() is True
def test_telemetry_disabled():
with patch.dict(os.environ, {'MEM0_TELEMETRY': "false"}):
with patch.dict(os.environ, {"MEM0_TELEMETRY": "false"}):
assert use_telemetry() is False
def test_telemetry_default_enabled():
assert use_telemetry() is True