test_openai.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import pytest
  2. from unittest.mock import Mock, patch
  3. from mem0.llms.openai import OpenAILLM
  4. @pytest.fixture
  5. def mock_openai_client():
  6. with patch('mem0.llms.openai.OpenAI') as mock_openai:
  7. mock_client = Mock()
  8. mock_openai.return_value = mock_client
  9. yield mock_client
  10. def test_generate_response_without_tools(mock_openai_client):
  11. llm = OpenAILLM()
  12. messages = [
  13. {"role": "system", "content": "You are a helpful assistant."},
  14. {"role": "user", "content": "Hello, how are you?"}
  15. ]
  16. mock_response = Mock()
  17. mock_response.choices = [Mock(message=Mock(content="I'm doing well, thank you for asking!"))]
  18. mock_openai_client.chat.completions.create.return_value = mock_response
  19. response = llm.generate_response(messages)
  20. mock_openai_client.chat.completions.create.assert_called_once_with(
  21. model="gpt-4o",
  22. messages=messages
  23. )
  24. assert response == "I'm doing well, thank you for asking!"
  25. def test_generate_response_with_tools(mock_openai_client):
  26. llm = OpenAILLM()
  27. messages = [
  28. {"role": "system", "content": "You are a helpful assistant."},
  29. {"role": "user", "content": "Add a new memory: Today is a sunny day."}
  30. ]
  31. tools = [
  32. {
  33. "type": "function",
  34. "function": {
  35. "name": "add_memory",
  36. "description": "Add a memory",
  37. "parameters": {
  38. "type": "object",
  39. "properties": {
  40. "data": {"type": "string", "description": "Data to add to memory"}
  41. },
  42. "required": ["data"],
  43. },
  44. },
  45. }
  46. ]
  47. mock_response = Mock()
  48. mock_message = Mock()
  49. mock_message.content = "I've added the memory for you."
  50. mock_tool_call = Mock()
  51. mock_tool_call.function.name = "add_memory"
  52. mock_tool_call.function.arguments = '{"data": "Today is a sunny day."}'
  53. mock_message.tool_calls = [mock_tool_call]
  54. mock_response.choices = [Mock(message=mock_message)]
  55. mock_openai_client.chat.completions.create.return_value = mock_response
  56. response = llm.generate_response(messages, tools=tools)
  57. mock_openai_client.chat.completions.create.assert_called_once_with(
  58. model="gpt-4o",
  59. messages=messages,
  60. tools=tools,
  61. tool_choice="auto"
  62. )
  63. assert response["content"] == "I've added the memory for you."
  64. assert len(response["tool_calls"]) == 1
  65. assert response["tool_calls"][0]["name"] == "add_memory"
  66. assert response["tool_calls"][0]["arguments"] == {'data': 'Today is a sunny day.'}