File size: 4,885 Bytes
5cae756
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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