|
| 1 | +from typing import cast |
| 2 | +from unittest.mock import MagicMock, patch |
| 3 | + |
| 4 | +import pytest |
| 5 | +from pydantic import BaseModel |
| 6 | + |
| 7 | +from radis.chats.utils.testing_helpers import ( |
| 8 | + create_async_openai_client_mock, |
| 9 | + create_openai_client_mock, |
| 10 | + make_rate_limit_error, |
| 11 | +) |
| 12 | +from radis.core.utils.llm_client import ( |
| 13 | + _LLM_GATE, |
| 14 | + AsyncChatClient, |
| 15 | + LLMClient, |
| 16 | + LLMResponseError, |
| 17 | +) |
| 18 | +from radis.core.utils.rate_limit import RateLimited |
| 19 | + |
| 20 | + |
| 21 | +class _Schema(BaseModel): |
| 22 | + value: str |
| 23 | + |
| 24 | + |
| 25 | +@pytest.fixture(autouse=True) |
| 26 | +def reset_gate(): |
| 27 | + _LLM_GATE.reset() |
| 28 | + yield |
| 29 | + _LLM_GATE.reset() |
| 30 | + |
| 31 | + |
| 32 | +def test_llm_client_sets_max_retries_and_timeout(settings): |
| 33 | + settings.LLM_REQUEST_TIMEOUT_SECONDS = 42.0 |
| 34 | + with patch("openai.OpenAI") as openai_cls: |
| 35 | + LLMClient() |
| 36 | + kwargs = openai_cls.call_args.kwargs |
| 37 | + assert kwargs["max_retries"] == 0 |
| 38 | + assert kwargs["timeout"] == 42.0 |
| 39 | + |
| 40 | + |
| 41 | +def test_extract_data_uses_user_message_and_extra_body(settings): |
| 42 | + settings.LLM_EXTRA_BODY = {"foo": "bar"} |
| 43 | + mock = cast(MagicMock, create_openai_client_mock(_Schema(value="hi"))) |
| 44 | + with patch("openai.OpenAI", return_value=mock): |
| 45 | + result = LLMClient().extract_data("the prompt", _Schema) |
| 46 | + assert isinstance(result, _Schema) |
| 47 | + call = mock.beta.chat.completions.parse.call_args.kwargs |
| 48 | + assert call["messages"] == [{"role": "user", "content": "the prompt"}] |
| 49 | + assert call["extra_body"] == {"foo": "bar"} |
| 50 | + |
| 51 | + |
| 52 | +def test_extract_data_recovers_after_one_rate_limit(): |
| 53 | + # No real wait: the injected 429 carries retry-after: 0. (`_LLM_GATE` reads its backoff |
| 54 | + # settings once at import time, so overriding them via `settings` here would be a no-op.) |
| 55 | + mock = cast(MagicMock, create_openai_client_mock(_Schema(value="ok"))) |
| 56 | + calls = {"n": 0} |
| 57 | + success_response = mock.beta.chat.completions.parse.return_value |
| 58 | + |
| 59 | + def flaky(**kwargs): |
| 60 | + calls["n"] += 1 |
| 61 | + if calls["n"] == 1: |
| 62 | + raise make_rate_limit_error({"retry-after": "0"}) |
| 63 | + return success_response |
| 64 | + |
| 65 | + mock.beta.chat.completions.parse.side_effect = flaky |
| 66 | + with patch("openai.OpenAI", return_value=mock): |
| 67 | + result = LLMClient().extract_data("p", _Schema) |
| 68 | + assert isinstance(result, _Schema) |
| 69 | + assert result.value == "ok" |
| 70 | + assert calls["n"] == 2 |
| 71 | + |
| 72 | + |
| 73 | +def test_extract_data_defers_when_rate_limit_exceeds_budget(): |
| 74 | + mock = cast(MagicMock, create_openai_client_mock(_Schema(value="never"))) |
| 75 | + |
| 76 | + def always_429(**kwargs): |
| 77 | + raise make_rate_limit_error({"retry-after": "600"}) |
| 78 | + |
| 79 | + mock.beta.chat.completions.parse.side_effect = always_429 |
| 80 | + with patch("openai.OpenAI", return_value=mock): |
| 81 | + with pytest.raises(RateLimited): |
| 82 | + LLMClient().extract_data("p", _Schema, max_wait=300.0) |
| 83 | + |
| 84 | + |
| 85 | +@pytest.mark.asyncio |
| 86 | +async def test_chat_returns_content(): |
| 87 | + mock = create_async_openai_client_mock("the answer") |
| 88 | + with patch("openai.AsyncOpenAI", return_value=mock): |
| 89 | + answer = await AsyncChatClient().chat([{"role": "user", "content": "hi"}]) |
| 90 | + assert answer == "the answer" |
| 91 | + |
| 92 | + |
| 93 | +@pytest.mark.asyncio |
| 94 | +async def test_chat_defers_when_rate_limit_exceeds_budget(): |
| 95 | + mock = cast(MagicMock, create_async_openai_client_mock("never")) |
| 96 | + |
| 97 | + async def always_429(**kwargs): |
| 98 | + raise make_rate_limit_error({"retry-after": "600"}) |
| 99 | + |
| 100 | + mock.chat.completions.create.side_effect = always_429 |
| 101 | + with patch("openai.AsyncOpenAI", return_value=mock): |
| 102 | + with pytest.raises(RateLimited): |
| 103 | + await AsyncChatClient().chat([{"role": "user", "content": "hi"}], max_wait=20.0) |
| 104 | + |
| 105 | + |
| 106 | +@pytest.mark.asyncio |
| 107 | +async def test_chat_raises_when_content_is_none(): |
| 108 | + # A refusal/empty completion yields content=None; surface it explicitly instead of |
| 109 | + # asserting (which would be stripped under python -O). |
| 110 | + mock = create_async_openai_client_mock(None) |
| 111 | + with patch("openai.AsyncOpenAI", return_value=mock): |
| 112 | + with pytest.raises(LLMResponseError): |
| 113 | + await AsyncChatClient().chat([{"role": "user", "content": "hi"}]) |
| 114 | + |
| 115 | + |
| 116 | +def test_extract_data_raises_when_parsed_is_none(): |
| 117 | + mock = create_openai_client_mock(None) |
| 118 | + with patch("openai.OpenAI", return_value=mock): |
| 119 | + with pytest.raises(LLMResponseError): |
| 120 | + LLMClient().extract_data("p", _Schema) |
0 commit comments