import os from unittest.mock import MagicMock, patch from langchainopenai import…
- User
import os from unittest.mock import MagicMock, patch from langchain_openai import ChatOpenAI from langchain_core.prompts import PromptTemplate
def test_chain_invocation(): # Mocking the ChatOpenAI class with patch('langchain_openai.ChatOpenAI') as MockChatOpenAI: # Create a mock instance of ChatOpenAI mock_llm = MockChatOpenAI.return_value
# Mock the with_retry method to return self (the mock instance) mock_llm.with_retry.return_value = mock_llm # Mock the invoke method to return a specific joke mock_llm.invoke = MagicMock(return_value="Why do programmers prefer dark mode? Because light attracts bugs!") # Define prompt template template = PromptTemplate.from_template("Tell me a joke about {topic}.") # Add retry logic to the model invocation runnable_with_retries = mock_llm.with_retry( retry_if_exception_type=(ValueError,), wait_exponential_jitter=True, stop_after_attempt=3 ) # Create a chain with the template and the retry-enabled model chain = template | runnable_with_retries # Invoke the chain with input and get result result = chain.invoke({"topic": "programmers"}) # Print the result for debugging print(result) # Assertions to check if everything works as expected assert result == "Why do programmers prefer dark mode? Because light attracts bugs!" mock_llm.invoke.assert_called_once() # Check if invoke method was called mock_llm.with_retry.assert_called_once() # Check if retry logic was called print("Test passed!")test_chain_invocation()
Output:
AssertionError Traceback (most recent call last) Cell In[106], line 44 40 mock_llm.with_retry.assert_called_once() # Check if retry logic was called 42 print("Test passed!") ---> 44 test_chain_invocation()
Cell In[106], line 38 35 print(result) 37 # Assertions to check if everything works as expected ---> 38 assert result == "Why do programmers prefer dark mode? Because light attracts bugs!" 39 mock_llm.invoke.assert_called_once() # Check if invoke method was called 40 mock_llm.with_retry.assert_called_once() # Check if retry logic was called
AssertionError:
- Assistant
- User
OK I commented the assert result, and left the assert called once, and it gave me error it was called 0 times
- Assistant
- User
Now it seems to be working, what do you think?
Invoke Result: Why do programmers prefer dark mode? Because light attracts bugs! Assertion failed: expected call not found. Expected: invoke('Tell me a joke about programmers.') Actual: invoke(StringPromptValue(text='Tell me a joke about programmers.'), {'tags': [], 'metadata': {}, 'callbacks': <langchain_core.callbacks.manager.CallbackManager object at 0x00000231B1EDEE40>, 'recursion_limit': 25, 'configurable': {}}) Invoke was called these many times: 1 These were the calls: [call(StringPromptValue(text='Tell me a joke about programmers.'), {'tags': [], 'metadata': {}, 'callbacks': <langchain_core.callbacks.manager.CallbackManager object at 0x00000231B1EDEE40>, 'recursion_limit': 25, 'configurable': {}})]
- Assistant
- User
the import was wrong, it was like this:
from langchain_core.prompt_values import StringPromptValue
but still gave me errors:
Invoke Result: Why do programmers prefer dark mode? Because light attracts bugs! Assertion failed: expected call not found. Expected: invoke(StringPromptValue(text='Tell me a joke about programmers.'), {'tags': [], 'metadata': {}, 'callbacks': , 'recursion_limit': 25, 'configurable': {}}) Actual: invoke(StringPromptValue(text='Tell me a joke about programmers.'), {'tags': [], 'metadata': {}, 'callbacks': <langchain_core.callbacks.manager.CallbackManager object at 0x00000231ADBB8620>, 'recursion_limit': 25, 'configurable': {}}) Invoke was called these many times: 1 These were the calls: [call(StringPromptValue(text='Tell me a joke about programmers.'), {'tags': [], 'metadata': {}, 'callbacks': <langchain_core.callbacks.manager.CallbackManager object at 0x00000231ADBB8620>, 'recursion_limit': 25, 'configurable': {}})] C:...\AppData\Local\anaconda3\envs\p3-12-4\Lib\unittest\mock.py:2188: RuntimeWarning: coroutine 'test_method_1' was never awaited def (self, name, parent): RuntimeWarning: Enable tracemalloc to get the object allocation traceback C:...\AppData\Local\anaconda3\envs\p3-12-4\Lib\unittest\mock.py:2188: RuntimeWarning: coroutine 'mock_successful_invoke' was never awaited def (self, name, parent): RuntimeWarning: Enable tracemalloc to get the object allocation traceback C:...\AppData\Local\anaconda3\envs\p3-12-4\Lib\unittest\mock.py:2188: RuntimeWarning: coroutine 'mock_failing_invoke' was never awaited def (self, name, parent): RuntimeWarning: Enable tracemalloc to get the object allocation traceback
- Assistant
- User
It works!!!!
Invoke Result: Why do programmers prefer dark mode? Because light attracts bugs! Test passed!
Now, how can I test now that if it gets an error like ValueError, it retries correctly?
- Assistant
- User
this time, it gave me this error:
{ "name": "ValueError", "message": "Temporary error", "stack": "--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[116], line 47 44 print("Invoke was called these many times:", mock_llm.invoke.call_count) 45 print("These were the calls:", mock_llm.invoke.call_args_list) ---> 47 test_chain_invocation_with_retries()
Cell In[116], line 32, in test_chain_invocation_with_retries() 29 chain = template | runnable_with_retries 31 # Invoke the chain with input and get result ---> 32 result = chain.invoke({"topic": "programmers"}) 34 # Print statement for debugging 35 print("Invoke Result:", result)
- Assistant
- User
ok, this time was different:
Output:
Error after retries: Temporary error Error after retries: Temporary error Error after retries: Temporary error Error after retries: Temporary error Error after retries: Temporary error Error after retries: Temporary error Error after retries: Temporary error Error after retries: Temporary error
AssertionError Traceback (most recent call last) Cell In[117], line 49 46 logger.info("Test passed! Invoke called %s times as expected. %s", mock_llm.invoke.call_count, mock_llm.invoke.call_args_list) 48 # Run the test function ---> 49 test_chain_invocation_with_retries()
Cell In[117], line 45 42 logger.error(f"Error after retries: {e}") 44 # Assertions to check if the invoke method was called three times due to retries ---> 45 assert mock_llm.invoke.call_count == 3 46 logger.info("Test passed! Invoke called %s times as expected. %s", mock_llm.invoke.call_count, mock_llm.invoke.call_args_list)
AssertionError:
- Assistant
- User
now the output was this:
Error after retries: Temporary error Error after retries: Temporary error Error after retries: Temporary error Error after retries: Temporary error Error after retries: Temporary error Error after retries: Temporary error Error after retries: Temporary error Error after retries: Temporary error Expected 3 calls, made 1 calls Expected 3 calls, made 1 calls Expected 3 calls, made 1 calls Expected 3 calls, made 1 calls Expected 3 calls, made 1 calls Expected 3 calls, made 1 calls Expected 3 calls, made 1 calls Expected 3 calls, made 1 calls Invoke was called 1 times.
AssertionError Traceback (most recent call last) Cell In[118], line 57 54 assert actual_call_count == expected_call_count # Ensures that retries occur as configured 56 # Run the test function ---> 57 test_chain_invocation_with_retries()
Cell In[118], line 54 52 expected_call_count = 3 # When using
stop_after_attempt=353 logger.info("Expected %s calls, made %s calls", expected_call_count, actual_call_count) ---> 54 assert actual_call_count == expected_call_countAssertionError:
- Assistant
- User
nope, didn't fix the problem. Can we do something like, mock further down the line, like mocking the http response from the server instead of mocking the method itself?
- Assistant
- User
can you do it without using an external library?
- Assistant
- User
the last code gave this output:
Invoke Result: Number of HTTP POST requests: 0
{ "name": "AssertionError", "message": "", "stack": "--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) Cell In[123], line 58 55 assert actual_call_count == expected_call_count 57 # Use the test function ---> 58 test_chain_invocation_with_mock()
Cell In[123], line 55, in test_chain_invocation_with_mock() 53 actual_call_count = mock_requests_post.counter 54 print("Number of HTTP POST requests:", actual_call_count) ---> 55 assert actual_call_count == expected_call_count
AssertionError: " }
- Assistant
- User
Error after retries: test_chain_invocation_with_mock..() takes 1 positional argument but 2 were given Number of HTTP POST requests: 0
{ "name": "AssertionError", "message": "Expected 3, but got 0", "stack": "--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) Cell In[125], line 62 59 assert actual_call_count == expected_call_count, f"Expected {expected_call_count}, but got {actual_call_count}" 61 # Execute the test function ---> 62 test_chain_invocation_with_mock()
Cell In[125], line 59, in test_chain_invocation_with_mock() 57 print("Number of HTTP POST requests:", actual_call_count) 58 expected_call_count = 3 # Two failures, then one success ---> 59 assert actual_call_count == expected_call_count, f"Expected {expected_call_count}, but got {actual_call_count}"
AssertionError: Expected 3, but got 0" }
- Assistant
- User
Invoke Result: <Response [500]> Number of HTTP POST requests: 1
{ "name": "AssertionError", "message": "Expected 3, but got 1", "stack": "--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) Cell In[126], line 62 59 assert actual_call_count == expected_call_count, f"Expected {expected_call_count}, but got {actual_call_count}" 61 # Execute the test function ---> 62 test_chain_invocation_with_mock()
Cell In[126], line 59, in test_chain_invocation_with_mock() 57 print("Number of HTTP POST requests:", actual_call_count) 58 expected_call_count = 3 # Two failures, then one success ---> 59 assert actual_call_count == expected_call_count, f"Expected {expected_call_count}, but got {actual_call_count}"
AssertionError: Expected 3, but got 1" }
- Assistant
- User
Error after retries: 500 Server Error: None for url: None Number of HTTP POST requests: 1
{ "name": "AssertionError", "message": "Expected 3, but got 1", "stack": "--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) Cell In[127], line 62 59 assert actual_call_count == expected_call_count, f"Expected {expected_call_count}, but got {actual_call_count}" 61 # Execute the test function ---> 62 test_chain_invocation_with_mock()
Cell In[127], line 59, in test_chain_invocation_with_mock() 57 print("Number of HTTP POST requests:", actual_call_count) 58 expected_call_count = 3 # Two failures, then one success ---> 59 assert actual_call_count == expected_call_count, f"Expected {expected_call_count}, but got {actual_call_count}"
AssertionError: Expected 3, but got 1" }
- Assistant
- User
Invoke Result: Number of HTTP POST requests: 0
{ "name": "AssertionError", "message": "Expected 3 calls, got 0", "stack": "--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) Cell In[128], line 61 58 assert actual_call_count == 3, f"Expected 3 calls, got {actual_call_count}" 60 # Execute the test ---> 61 test_chain_invocation_with_mock()
Cell In[128], line 58, in test_chain_invocation_with_mock() 55 actual_call_count = mocked_requests_post.counter 56 print("Number of HTTP POST requests:", actual_call_count) ---> 58 assert actual_call_count == 3, f"Expected 3 calls, got {actual_call_count}"
AssertionError: Expected 3 calls, got 0" }
- Assistant
- User
Invoke Result: Number of HTTP POST requests: 0
{ "name": "AssertionError", "message": "Expected 3 calls, got 0", "stack": "--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) Cell In[131], line 64 61 assert actual_call_count == 3, f"Expected 3 calls, got {actual_call_count}" 63 # Running the test ---> 64 test_chain_invocation_with_mock()
Cell In[131], line 61, in test_chain_invocation_with_mock() 58 actual_call_count = mock_requests_post.counter 59 print("Number of HTTP POST requests:", actual_call_count) ---> 61 assert actual_call_count == 3, f"Expected 3 calls, got {actual_call_count}"
AssertionError: Expected 3 calls, got 0" }
Still the same error, why is this?
- Assistant
- User
this is strange, it gave me this error:
{ "name": "ValueError", "message": ""ChatOpenAI" object has no field "invoke"", "stack": "--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[135], line 67 64 assert actual_call_count == 3, f"Expected 3 calls, got {actual_call_count}" 66 # Running the test ---> 67 test_chain_invocation_with_mock()
Cell In[135], line 39, in test_chain_invocation_with_mock() 36 raise 38 # Patch the
invokewithin the chain ---> 39 llm.invoke = MagicMock(side_effect=invoke_with_retry) 41 # Define prompt template 42 template = PromptTemplate.from_template("Tell me a joke about {topic}.")File c:\Users\jorge.hollger\Documents\Accusys\core-ai\01_mvp\venv\Lib\site-packages\pydantic\main.py:884, in BaseModel.(self, name, value) 881 self..validate_assignment(self, name, value) 882 elif self.model_config.get('extra') != 'allow' and name not in self.model_fields: 883 # TODO - matching error --> 884 raise ValueError(f'"{self..}" object has no field "{name}"') 885 elif self.model_config.get('extra') == 'allow' and name not in self.model_fields: 886 if self.model_extra and name in self.model_extra:
- Assistant
- User
- Assistant
- User
{ "name": "AssertionError", "message": "Expected 3 calls, got 0", "stack": "--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) Cell In[139], line 57 54 assert actual_call_count == 3, f"Expected 3 calls, got {actual_call_count}" 56 # Run the test ---> 57 test_chain_invocation_with_mock()
Cell In[139], line 54, in test_chain_invocation_with_mock() 51 actual_call_count = mock_requests_post.counter 52 print("Number of HTTP POST requests:", actual_call_count) ---> 54 assert actual_call_count == 3, f"Expected 3 calls, got {actual_call_count}"
AssertionError: Expected 3 calls, got 0" }
- Assistant