diff --git a/dzen-assistant/app/worker.py b/dzen-assistant/app/worker.py index 0a5c9f2..566fd13 100644 --- a/dzen-assistant/app/worker.py +++ b/dzen-assistant/app/worker.py @@ -945,6 +945,13 @@ def call_llm(user_prompt: str) -> str: except httpx.HTTPStatusError as exc: status_code = exc.response.status_code detail = exc.response.text[:1000] + if status_code == 400 and "DataInspectionFailed" in detail: + if attempt < attempts: + time.sleep(2 * attempt) + continue + raise RuntimeError( + f"Timeweb LLM отклонил проверку входных данных после {attempts} попыток: {detail}" + ) from exc if status_code >= 500: raise RuntimeError( f"Timeweb LLM вернул {status_code} после {attempts} попыток. " diff --git a/dzen-assistant/tests/test_worker_llm_http_retry.py b/dzen-assistant/tests/test_worker_llm_http_retry.py new file mode 100644 index 0000000..f0d48a6 --- /dev/null +++ b/dzen-assistant/tests/test_worker_llm_http_retry.py @@ -0,0 +1,95 @@ +import unittest +from unittest.mock import MagicMock, call, patch + +import httpx + +from app.worker import call_llm + + +def response(status_code: int, payload: dict) -> httpx.Response: + request = httpx.Request("POST", "https://example.test/chat/completions") + return httpx.Response(status_code, json=payload, request=request) + + +class CallLlmHttpRetryTest(unittest.TestCase): + def setUp(self): + self.session = MagicMock() + self.session.scalar.return_value = "" + self.session_context = MagicMock() + self.session_context.__enter__.return_value = self.session + + self.client = MagicMock() + self.client_context = MagicMock() + self.client_context.__enter__.return_value = self.client + + self.session_local_patcher = patch( + "app.worker.SessionLocal", return_value=self.session_context + ) + self.http_client_patcher = patch( + "app.worker.httpx.Client", return_value=self.client_context + ) + self.retry_attempts_patcher = patch( + "app.worker.settings.llm_retry_attempts", 3 + ) + self.sleep_patcher = patch("app.worker.time.sleep") + + self.session_local_patcher.start() + self.http_client_patcher.start() + self.retry_attempts_patcher.start() + self.sleep = self.sleep_patcher.start() + + def tearDown(self): + patch.stopall() + + def test_retries_data_inspection_failure_then_returns_success(self): + self.client.post.side_effect = [ + response( + 400, + {"error": {"message": "Request rejected: DataInspectionFailed"}}, + ), + response( + 200, + {"choices": [{"message": {"content": "valid completion"}}]}, + ), + ] + + result = call_llm("prompt") + + self.assertEqual(result, "valid completion") + self.assertEqual(self.client.post.call_count, 2) + self.sleep.assert_called_once_with(2) + + def test_does_not_retry_unrelated_http_400(self): + self.client.post.return_value = response( + 400, + {"error": {"message": "invalid_request_error"}}, + ) + + with self.assertRaisesRegex( + RuntimeError, + "LLM-редактор отклонил запрос с кодом 400", + ): + call_llm("prompt") + + self.client.post.assert_called_once() + self.sleep.assert_not_called() + + def test_raises_specific_error_after_three_data_inspection_failures(self): + inspection_failure = response( + 400, + {"error": {"message": "Request rejected: DataInspectionFailed"}}, + ) + self.client.post.side_effect = [inspection_failure] * 3 + + with self.assertRaisesRegex( + RuntimeError, + "Timeweb LLM отклонил проверку входных данных после 3 попыток", + ): + call_llm("prompt") + + self.assertEqual(self.client.post.call_count, 3) + self.assertEqual(self.sleep.call_args_list, [call(2), call(4)]) + + +if __name__ == "__main__": + unittest.main()