test_acompletion.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. import asyncio
  2. from unittest.mock import AsyncMock, patch
  3. import pytest
  4. from opendevin.core.config import load_app_config
  5. from opendevin.core.exceptions import UserCancelledError
  6. from opendevin.llm.llm import LLM
  7. config = load_app_config()
  8. @pytest.fixture
  9. def test_llm():
  10. # Create a mock config for testing
  11. return LLM(config=config.get_llm_config())
  12. @pytest.fixture
  13. def mock_response():
  14. return [
  15. {'choices': [{'delta': {'content': 'This is a'}}]},
  16. {'choices': [{'delta': {'content': ' test'}}]},
  17. {'choices': [{'delta': {'content': ' message.'}}]},
  18. {'choices': [{'delta': {'content': ' It is'}}]},
  19. {'choices': [{'delta': {'content': ' a bit'}}]},
  20. {'choices': [{'delta': {'content': ' longer'}}]},
  21. {'choices': [{'delta': {'content': ' than'}}]},
  22. {'choices': [{'delta': {'content': ' the'}}]},
  23. {'choices': [{'delta': {'content': ' previous'}}]},
  24. {'choices': [{'delta': {'content': ' one,'}}]},
  25. {'choices': [{'delta': {'content': ' but'}}]},
  26. {'choices': [{'delta': {'content': ' hopefully'}}]},
  27. {'choices': [{'delta': {'content': ' still'}}]},
  28. {'choices': [{'delta': {'content': ' short'}}]},
  29. {'choices': [{'delta': {'content': ' enough.'}}]},
  30. ]
  31. @pytest.mark.asyncio
  32. async def test_acompletion_non_streaming():
  33. with patch.object(LLM, '_call_acompletion') as mock_call_acompletion:
  34. mock_response = {
  35. 'choices': [{'message': {'content': 'This is a test message.'}}]
  36. }
  37. mock_call_acompletion.return_value = mock_response
  38. test_llm = LLM(config=config.get_llm_config())
  39. response = await test_llm.async_completion(
  40. messages=[{'role': 'user', 'content': 'Hello!'}],
  41. stream=False,
  42. drop_params=True,
  43. )
  44. # Assertions for non-streaming completion
  45. assert response['choices'][0]['message']['content'] != ''
  46. @pytest.mark.asyncio
  47. async def test_acompletion_streaming(mock_response):
  48. with patch.object(LLM, '_call_acompletion') as mock_call_acompletion:
  49. mock_call_acompletion.return_value.__aiter__.return_value = iter(mock_response)
  50. test_llm = LLM(config=config.get_llm_config())
  51. async for chunk in test_llm.async_streaming_completion(
  52. messages=[{'role': 'user', 'content': 'Hello!'}], stream=True
  53. ):
  54. print(f"Chunk: {chunk['choices'][0]['delta']['content']}")
  55. # Assertions for streaming completion
  56. assert chunk['choices'][0]['delta']['content'] in [
  57. r['choices'][0]['delta']['content'] for r in mock_response
  58. ]
  59. @pytest.mark.asyncio
  60. async def test_completion(test_llm):
  61. with patch.object(LLM, 'completion') as mock_completion:
  62. mock_completion.return_value = {
  63. 'choices': [{'message': {'content': 'This is a test message.'}}]
  64. }
  65. response = test_llm.completion(messages=[{'role': 'user', 'content': 'Hello!'}])
  66. assert response['choices'][0]['message']['content'] == 'This is a test message.'
  67. @pytest.mark.asyncio
  68. @pytest.mark.parametrize('cancel_delay', [0.1, 0.3, 0.5, 0.7, 0.9])
  69. async def test_async_completion_with_user_cancellation(cancel_delay):
  70. cancel_event = asyncio.Event()
  71. async def mock_on_cancel_requested():
  72. is_set = cancel_event.is_set()
  73. print(f'Cancel requested: {is_set}')
  74. return is_set
  75. config = load_app_config()
  76. config.on_cancel_requested_fn = mock_on_cancel_requested
  77. async def mock_acompletion(*args, **kwargs):
  78. print('Starting mock_acompletion')
  79. for i in range(20): # Increased iterations for longer running task
  80. print(f'mock_acompletion iteration {i}')
  81. await asyncio.sleep(0.1)
  82. if await mock_on_cancel_requested():
  83. print('Cancellation detected in mock_acompletion')
  84. raise UserCancelledError('LLM request cancelled by user')
  85. print('Completing mock_acompletion without cancellation')
  86. return {'choices': [{'message': {'content': 'This is a test message.'}}]}
  87. with patch.object(
  88. LLM, '_call_acompletion', new_callable=AsyncMock
  89. ) as mock_call_acompletion:
  90. mock_call_acompletion.side_effect = mock_acompletion
  91. test_llm = LLM(config=config.get_llm_config())
  92. async def cancel_after_delay():
  93. print(f'Starting cancel_after_delay with delay {cancel_delay}')
  94. await asyncio.sleep(cancel_delay)
  95. print('Setting cancel event')
  96. cancel_event.set()
  97. with pytest.raises(UserCancelledError):
  98. await asyncio.gather(
  99. test_llm.async_completion(
  100. messages=[{'role': 'user', 'content': 'Hello!'}],
  101. stream=False,
  102. ),
  103. cancel_after_delay(),
  104. )
  105. # Ensure the mock was called
  106. mock_call_acompletion.assert_called_once()
  107. @pytest.mark.asyncio
  108. @pytest.mark.parametrize('cancel_after_chunks', [1, 3, 5, 7, 9])
  109. async def test_async_streaming_completion_with_user_cancellation(cancel_after_chunks):
  110. cancel_requested = False
  111. async def mock_on_cancel_requested():
  112. nonlocal cancel_requested
  113. return cancel_requested
  114. config = load_app_config()
  115. config.on_cancel_requested_fn = mock_on_cancel_requested
  116. test_messages = [
  117. 'This is ',
  118. 'a test ',
  119. 'message ',
  120. 'with ',
  121. 'multiple ',
  122. 'chunks ',
  123. 'to ',
  124. 'simulate ',
  125. 'a ',
  126. 'longer ',
  127. 'streaming ',
  128. 'response.',
  129. ]
  130. async def mock_acompletion(*args, **kwargs):
  131. for i, content in enumerate(test_messages):
  132. yield {'choices': [{'delta': {'content': content}}]}
  133. if i + 1 == cancel_after_chunks:
  134. nonlocal cancel_requested
  135. cancel_requested = True
  136. if cancel_requested:
  137. raise UserCancelledError('LLM request cancelled by user')
  138. await asyncio.sleep(0.05) # Simulate some delay between chunks
  139. with patch.object(
  140. LLM, '_call_acompletion', new_callable=AsyncMock
  141. ) as mock_call_acompletion:
  142. mock_call_acompletion.return_value = mock_acompletion()
  143. test_llm = LLM(config=config.get_llm_config())
  144. received_chunks = []
  145. with pytest.raises(UserCancelledError):
  146. async for chunk in test_llm.async_streaming_completion(
  147. messages=[{'role': 'user', 'content': 'Hello!'}], stream=True
  148. ):
  149. received_chunks.append(chunk['choices'][0]['delta']['content'])
  150. print(f"Chunk: {chunk['choices'][0]['delta']['content']}")
  151. # Assert that we received the expected number of chunks before cancellation
  152. assert len(received_chunks) == cancel_after_chunks
  153. assert received_chunks == test_messages[:cancel_after_chunks]
  154. # Ensure the mock was called
  155. mock_call_acompletion.assert_called_once()