test_acompletion.py 7.4 KB

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