File size: 7,380 Bytes
88c0e85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
"""Streaming contract tests for OpenAI-compatible SSE endpoints."""
from __future__ import annotations

import asyncio
import json
from collections import deque

import pytest
from fastapi.responses import StreamingResponse

from app.core.model_registry import ModelSpec
from app.routers import chat, completions, responses
from app.schemas.chat import ChatCompletionRequest
from app.schemas.completions import CompletionRequest
from app.schemas.responses import ResponseRequest


class DummyStream:
    def __init__(
        self,
        *,
        tokens: list[str],
        prompt_tokens: int,
        completion_tokens: int,
        finish_reason: str = "stop",
    ) -> None:
        self._tokens = tokens
        self.prompt_tokens = prompt_tokens
        self.completion_tokens = completion_tokens
        self.finish_reason = finish_reason

    def iter_tokens(self):
        for token in self._tokens:
            yield token


async def _read_stream_body(response: StreamingResponse) -> str:
    chunks: list[str] = []
    async for chunk in response.body_iterator:
        if isinstance(chunk, bytes):
            chunks.append(chunk.decode("utf-8"))
        else:
            chunks.append(chunk)
    return "".join(chunks)


def _parse_sse_data_frames(raw_body: str) -> list[str]:
    frames = [frame.strip() for frame in raw_body.split("\n\n") if frame.strip()]
    data_frames: list[str] = []
    for frame in frames:
        assert frame.startswith("data: ")
        data_frames.append(frame[len("data: ") :])
    return data_frames


def test_completions_stream_emits_sse_chunks_usage_and_done(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setattr("app.routers.completions.get_model_spec", lambda _: None)
    monkeypatch.setattr(
        "app.routers.completions.engine.create_stream",
        lambda *_, **__: DummyStream(
            tokens=["Hel", "lo"],
            prompt_tokens=3,
            completion_tokens=2,
            finish_reason="stop",
        ),
    )

    payload = CompletionRequest.model_validate(
        {
            "model": "GPT3-dev",
            "prompt": "Hello",
            "stream": True,
        }
    )
    response = asyncio.run(completions.create_completion(payload))
    assert isinstance(response, StreamingResponse)

    body = asyncio.run(_read_stream_body(response))
    data_frames = _parse_sse_data_frames(body)
    assert data_frames[-1] == "[DONE]"

    chunks = [json.loads(frame) for frame in data_frames[:-1]]
    assert chunks[0]["object"] == "text_completion.chunk"
    assert chunks[0]["choices"][0]["text"] == "Hel"
    assert chunks[1]["choices"][0]["text"] == "lo"
    assert chunks[2]["choices"][0]["finish_reason"] == "stop"

    tail = chunks[-1]
    assert tail["choices"] == []
    assert tail["usage"] == {
        "prompt_tokens": 3,
        "completion_tokens": 2,
        "total_tokens": 5,
    }


def test_chat_stream_emits_initial_role_delta_and_done(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setattr(
        "app.routers.chat.get_model_spec",
        lambda model: ModelSpec(name=model, hf_repo="dummy/instruct", is_instruct=True),
    )
    monkeypatch.setattr("app.routers.chat.engine.apply_chat_template", lambda *_: "formatted")
    monkeypatch.setattr(
        "app.routers.chat.engine.create_stream",
        lambda *_, **__: DummyStream(
            tokens=["Hi", " there"],
            prompt_tokens=4,
            completion_tokens=2,
            finish_reason="stop",
        ),
    )

    payload = ChatCompletionRequest.model_validate(
        {
            "model": "GPT4-dev-177M-1511-Instruct",
            "messages": [{"role": "user", "content": "hello"}],
            "stream": True,
        }
    )
    response = asyncio.run(chat.create_chat_completion(payload))
    assert isinstance(response, StreamingResponse)

    body = asyncio.run(_read_stream_body(response))
    data_frames = _parse_sse_data_frames(body)
    assert data_frames[-1] == "[DONE]"

    chunks = [json.loads(frame) for frame in data_frames[:-1]]
    assert chunks[0]["choices"][0]["delta"]["role"] == "assistant"
    assert chunks[1]["choices"][0]["delta"]["content"] == "Hi"
    assert chunks[2]["choices"][0]["delta"]["content"] == " there"
    assert chunks[3]["choices"][0]["finish_reason"] == "stop"


def test_responses_stream_emits_created_delta_completed_done(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setattr(
        "app.routers.responses.get_model_spec",
        lambda model: ModelSpec(name=model, hf_repo="dummy/base", is_instruct=False),
    )
    monkeypatch.setattr(
        "app.routers.responses.engine.create_stream",
        lambda *_, **__: DummyStream(
            tokens=["Hi", " there"],
            prompt_tokens=5,
            completion_tokens=2,
            finish_reason="stop",
        ),
    )

    payload = ResponseRequest.model_validate(
        {
            "model": "GPT3-dev",
            "input": "Say hi",
            "stream": True,
        }
    )
    response = asyncio.run(responses.create_response(payload))
    assert isinstance(response, StreamingResponse)

    body = asyncio.run(_read_stream_body(response))
    data_frames = _parse_sse_data_frames(body)
    assert data_frames[-1] == "[DONE]"

    events = [json.loads(frame) for frame in data_frames[:-1]]
    assert events[0]["type"] == "response.created"
    assert events[1]["type"] == "response.output_text.delta"
    assert events[1]["delta"] == "Hi"
    assert events[2]["type"] == "response.output_text.delta"
    assert events[2]["delta"] == " there"
    assert events[3]["type"] == "response.completed"
    assert events[3]["response"]["output"][0]["content"][0]["text"] == "Hi there"
    assert events[3]["response"]["usage"] == {
        "input_tokens": 5,
        "output_tokens": 2,
        "total_tokens": 7,
    }


def test_completions_stream_usage_aggregates_prompt_and_completion_tokens(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    calls: list[str] = []
    streams = deque(
        [
            DummyStream(tokens=["a1"], prompt_tokens=10, completion_tokens=1),
            DummyStream(tokens=["a2"], prompt_tokens=999, completion_tokens=2),
            DummyStream(tokens=["b1"], prompt_tokens=20, completion_tokens=3),
            DummyStream(tokens=["b2"], prompt_tokens=888, completion_tokens=4),
        ]
    )

    def fake_create_stream(model: str, prompt: str, **_: object) -> DummyStream:
        calls.append(prompt)
        return streams.popleft()

    monkeypatch.setattr("app.routers.completions.get_model_spec", lambda _: None)
    monkeypatch.setattr("app.routers.completions.engine.create_stream", fake_create_stream)

    payload = CompletionRequest.model_validate(
        {
            "model": "GPT3-dev",
            "prompt": ["alpha", "beta"],
            "n": 2,
            "stream": True,
        }
    )
    response = asyncio.run(completions.create_completion(payload))
    body = asyncio.run(_read_stream_body(response))
    data_frames = _parse_sse_data_frames(body)
    assert data_frames[-1] == "[DONE]"

    chunks = [json.loads(frame) for frame in data_frames[:-1]]
    tail = chunks[-1]

    assert calls == ["alpha", "alpha", "beta", "beta"]
    assert tail["usage"] == {
        "prompt_tokens": 30,
        "completion_tokens": 10,
        "total_tokens": 40,
    }