from datetime import date from types import SimpleNamespace from unittest.mock import patch import pytest from fastapi.testclient import TestClient from app.core.config import Settings from app.core.exceptions import GenerationError from app.services.llm_client import DailyBudget, OpenAIClient, get_llm_client from tests.conftest import TEST_SESSION_ID, make_jwt def _chunk(content): return SimpleNamespace(choices=[SimpleNamespace(delta=SimpleNamespace(content=content))]) class _FakeCompletions: """OpenAI's chat completions endpoint, recording what it was asked for.""" def __init__(self, chunks=None, error=None): self.calls = [] self._chunks = chunks or [] self._error = error async def create(self, **kwargs): self.calls.append(kwargs) if self._error: raise self._error async def stream(): for chunk in self._chunks: yield chunk return stream() def _client(completions, limit=10): fake = SimpleNamespace(chat=SimpleNamespace(completions=completions)) return OpenAIClient(api_key="unused", model="gpt-5-nano", budget=DailyBudget(limit), client=fake) async def _collect(stream): return [token async for token in stream] def test_daily_budget_refuses_past_its_limit_until_the_next_day(): today = [date(2026, 10, 3)] budget = DailyBudget(2, today=lambda: today[0]) assert [budget.take(), budget.take(), budget.take()] == [True, True, False] today[0] = date(2026, 10, 4) assert budget.take() is True @pytest.mark.asyncio async def test_openai_streams_only_answer_text_with_minimal_reasoning_and_capped_length(): # Reasoning-only chunks carry no content, and the last chunk of a stream can have no choices. completions = _FakeCompletions([_chunk("Darshan "), _chunk(None), _chunk(""), _chunk("built Cortex [1]."), SimpleNamespace(choices=[])]) tokens = await _collect(_client(completions).complete_with_complexity("prompt", "system", stream=True, complexity="complex")) assert tokens == ["Darshan ", "built Cortex [1]."] [call] = completions.calls assert call["model"] == "gpt-5-nano" assert call["reasoning_effort"] == "minimal" assert call["max_completion_tokens"] == 700 assert call["stream"] is True @pytest.mark.asyncio async def test_openai_makes_no_call_once_the_day_is_spent(): completions = _FakeCompletions([_chunk("never")]) with pytest.raises(GenerationError): await _collect(_client(completions, limit=0).complete_with_complexity("prompt", "system", stream=True, complexity="simple")) assert completions.calls == [] @pytest.mark.asyncio async def test_openai_failure_is_a_generation_error(): completions = _FakeCompletions(error=RuntimeError("401 invalid_api_key")) with pytest.raises(GenerationError): await _collect(_client(completions).complete_with_complexity("prompt", "system", stream=True, complexity="simple")) def test_openai_provider_without_a_key_fails_at_startup(): settings = Settings(LLM_PROVIDER="openai", OPENAI_API_KEY=None) with pytest.raises(ValueError): get_llm_client(settings) class _RecordingLLM: def __init__(self, suggests_follow_ups): self.suggests_follow_ups = suggests_follow_ups self.prompts = [] async def complete_with_complexity(self, prompt, system, stream, complexity): self.prompts.append(prompt) yield "What stack does Cortex use?" def _chat_with(llm): async def astream(state, stream_mode=None): yield ("custom", {"type": "token", "text": "Darshan built Cortex."}) yield ("updates", {"generate": {"answer": "Darshan built Cortex.", "sources": []}}) pipeline = SimpleNamespace(astream=astream) with patch("app.main.build_pipeline", return_value=pipeline), \ patch("app.main.get_llm_client", return_value=llm), \ patch("app.main.QdrantClient"), \ patch("app.services.embedder.Embedder"), \ patch("app.services.reranker.Reranker"): from app.main import create_app app = create_app() app.state.pipeline = pipeline with TestClient(app) as client: response = client.post( "/chat", json={"message": "What has Darshan built?", "session_id": TEST_SESSION_ID}, headers={"Authorization": f"Bearer {make_jwt()}"}, ) assert response.status_code == 200 return response.text def test_a_paid_provider_spends_nothing_on_follow_up_suggestions(): llm = _RecordingLLM(suggests_follow_ups=False) body = _chat_with(llm) assert "Darshan built Cortex." in body assert llm.prompts == [] def test_a_free_provider_is_still_asked_for_follow_ups(): llm = _RecordingLLM(suggests_follow_ups=True) _chat_with(llm) assert len(llm.prompts) == 1