|
| 1 | +"""Tests for LLM provider selection and retry logic.""" |
| 2 | + |
| 3 | +from unittest.mock import patch |
| 4 | + |
| 5 | +import httpx |
| 6 | +import pytest |
| 7 | +from app.assistant.service import _build_provider |
| 8 | +from app.config import Config |
| 9 | +from app.llm.base import LLM_MAX_RETRIES, LLMProvider |
| 10 | +from app.llm.providers.anthropic import AnthropicProvider |
| 11 | +from app.llm.providers.chat_completions import ChatCompletionsProvider |
| 12 | +from app.llm.providers.ollama import OllamaProvider |
| 13 | + |
| 14 | +pytestmark = pytest.mark.asyncio |
| 15 | + |
| 16 | + |
| 17 | +def _make_config(**overrides) -> Config: |
| 18 | + defaults = dict( |
| 19 | + db_url="sqlite:///:memory:", |
| 20 | + mode="read-only", |
| 21 | + limit_default=100, |
| 22 | + timeout_ms=5000, |
| 23 | + enable_ui=True, |
| 24 | + enable_explanations=True, |
| 25 | + allowed_origins=["http://localhost:8000"], |
| 26 | + allow_destructive=False, |
| 27 | + llm_provider="openai", |
| 28 | + llm_api_key="test-key", |
| 29 | + llm_model="test-model", |
| 30 | + llm_base_url=None, |
| 31 | + openai_api_mode="chat", |
| 32 | + llm_timeout_ms=60000, |
| 33 | + chat_history_enabled=True, |
| 34 | + chat_history_limit=10, |
| 35 | + ) |
| 36 | + defaults.update(overrides) |
| 37 | + return Config(**defaults) |
| 38 | + |
| 39 | + |
| 40 | +# ── Provider selection ───────────────────────────────────────────────────── |
| 41 | + |
| 42 | + |
| 43 | +def test_build_provider_openai() -> None: |
| 44 | + cfg = _make_config(llm_provider="openai") |
| 45 | + provider = _build_provider(cfg) |
| 46 | + assert isinstance(provider, ChatCompletionsProvider) |
| 47 | + assert provider.base_url == "https://api.openai.com" |
| 48 | + |
| 49 | + |
| 50 | +def test_build_provider_anthropic() -> None: |
| 51 | + cfg = _make_config(llm_provider="anthropic") |
| 52 | + provider = _build_provider(cfg) |
| 53 | + assert isinstance(provider, AnthropicProvider) |
| 54 | + |
| 55 | + |
| 56 | +def test_build_provider_ollama() -> None: |
| 57 | + cfg = _make_config(llm_provider="ollama") |
| 58 | + provider = _build_provider(cfg) |
| 59 | + assert isinstance(provider, OllamaProvider) |
| 60 | + assert provider.base_url == "http://localhost:11434" |
| 61 | + |
| 62 | + |
| 63 | +def test_build_provider_deepseek() -> None: |
| 64 | + cfg = _make_config(llm_provider="deepseek") |
| 65 | + provider = _build_provider(cfg) |
| 66 | + assert isinstance(provider, ChatCompletionsProvider) |
| 67 | + assert provider.base_url == "https://api.deepseek.com" |
| 68 | + |
| 69 | + |
| 70 | +def test_build_provider_gemini() -> None: |
| 71 | + cfg = _make_config(llm_provider="gemini") |
| 72 | + provider = _build_provider(cfg) |
| 73 | + assert isinstance(provider, ChatCompletionsProvider) |
| 74 | + assert "generativelanguage" in provider.base_url |
| 75 | + |
| 76 | + |
| 77 | +def test_build_provider_custom_base_url() -> None: |
| 78 | + cfg = _make_config(llm_provider="openai", llm_base_url="https://my-proxy.example.com") |
| 79 | + provider = _build_provider(cfg) |
| 80 | + assert isinstance(provider, ChatCompletionsProvider) |
| 81 | + assert provider.base_url == "https://my-proxy.example.com" |
| 82 | + |
| 83 | + |
| 84 | +def test_build_provider_timeout_passed() -> None: |
| 85 | + cfg = _make_config(llm_timeout_ms=30000) |
| 86 | + provider = _build_provider(cfg) |
| 87 | + assert provider.timeout == 30.0 |
| 88 | + |
| 89 | + |
| 90 | +# ── Retry logic ──────────────────────────────────────────────────────────── |
| 91 | + |
| 92 | + |
| 93 | +class _FlakyProvider(LLMProvider): |
| 94 | + """Provider that fails N times then succeeds.""" |
| 95 | + |
| 96 | + def __init__(self, fail_times: int, exc: Exception) -> None: |
| 97 | + self.fail_times = fail_times |
| 98 | + self.exc = exc |
| 99 | + self.attempts = 0 |
| 100 | + |
| 101 | + async def _generate(self, messages): |
| 102 | + self.attempts += 1 |
| 103 | + if self.attempts <= self.fail_times: |
| 104 | + raise self.exc |
| 105 | + return {"text": "ok", "raw": {}} |
| 106 | + |
| 107 | + |
| 108 | +def _make_http_error(status: int) -> httpx.HTTPStatusError: |
| 109 | + response = httpx.Response(status_code=status) |
| 110 | + return httpx.HTTPStatusError( |
| 111 | + message=f"{status}", request=httpx.Request("POST", "http://x"), response=response |
| 112 | + ) |
| 113 | + |
| 114 | + |
| 115 | +async def test_retry_on_500() -> None: |
| 116 | + provider = _FlakyProvider(fail_times=1, exc=_make_http_error(500)) |
| 117 | + with patch("app.llm.base.LLM_RETRY_BASE_DELAY", 0): |
| 118 | + result = await provider.generate([]) |
| 119 | + assert result["text"] == "ok" |
| 120 | + assert provider.attempts == 2 |
| 121 | + |
| 122 | + |
| 123 | +async def test_retry_on_429() -> None: |
| 124 | + provider = _FlakyProvider(fail_times=1, exc=_make_http_error(429)) |
| 125 | + with patch("app.llm.base.LLM_RETRY_BASE_DELAY", 0): |
| 126 | + result = await provider.generate([]) |
| 127 | + assert result["text"] == "ok" |
| 128 | + assert provider.attempts == 2 |
| 129 | + |
| 130 | + |
| 131 | +async def test_no_retry_on_400() -> None: |
| 132 | + provider = _FlakyProvider(fail_times=1, exc=_make_http_error(400)) |
| 133 | + with pytest.raises(httpx.HTTPStatusError): |
| 134 | + await provider.generate([]) |
| 135 | + assert provider.attempts == 1 # no retry for client errors |
| 136 | + |
| 137 | + |
| 138 | +async def test_retry_on_timeout() -> None: |
| 139 | + provider = _FlakyProvider(fail_times=1, exc=httpx.TimeoutException("timeout")) |
| 140 | + with patch("app.llm.base.LLM_RETRY_BASE_DELAY", 0): |
| 141 | + result = await provider.generate([]) |
| 142 | + assert result["text"] == "ok" |
| 143 | + assert provider.attempts == 2 |
| 144 | + |
| 145 | + |
| 146 | +async def test_retry_on_connect_error() -> None: |
| 147 | + provider = _FlakyProvider(fail_times=1, exc=httpx.ConnectError("refused")) |
| 148 | + with patch("app.llm.base.LLM_RETRY_BASE_DELAY", 0): |
| 149 | + result = await provider.generate([]) |
| 150 | + assert result["text"] == "ok" |
| 151 | + |
| 152 | + |
| 153 | +async def test_retry_exhausted_raises() -> None: |
| 154 | + provider = _FlakyProvider(fail_times=10, exc=_make_http_error(503)) |
| 155 | + with patch("app.llm.base.LLM_RETRY_BASE_DELAY", 0): |
| 156 | + with pytest.raises(httpx.HTTPStatusError): |
| 157 | + await provider.generate([]) |
| 158 | + assert provider.attempts == 1 + LLM_MAX_RETRIES |
0 commit comments