Spaces:
Sleeping

File size: 13,583 Bytes
f45a595
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
from __future__ import annotations

import json
from collections import deque
from types import SimpleNamespace

import httpx
import pytest

import app as gateway
from upstage_provider import StreamEvent, UpstageStreamError


@pytest.fixture
def anyio_backend():
    return "asyncio"


class FakeProvider:
    def __init__(self, events=None, error=None, capture=None):
        self.events = events or []
        self.error = error
        self.capture = capture
        self.last_response = ""
        self.last_reasoning = ""
        self.last_sources = []
        self.last_usage = None

    async def stream(self, **kwargs):
        if self.capture is not None:
            self.capture.append(kwargs)
        if self.error:
            raise self.error
        content, reasoning = [], []
        for event in self.events:
            if event.kind == "content":
                content.append(event.text)
            elif event.kind == "thinking":
                reasoning.append(event.text)
            elif event.kind == "sources":
                self.last_sources = json.loads(event.text).get("sources", [])
            yield event
        self.last_response = "".join(content)
        self.last_reasoning = "".join(reasoning)
        self.last_usage = SimpleNamespace(
            api_usage={"prompt_tokens": 5, "completion_tokens": 3, "total_tokens": 8}
        )


def factory_queue(monkeypatch, providers):
    queue = deque(providers)
    monkeypatch.setattr(gateway, "provider_factory", lambda: queue.popleft())
    return queue


@pytest.fixture(autouse=True)
def reset_config(monkeypatch):
    gateway.rate_buckets.clear()
    monkeypatch.setattr(gateway, "PUBLIC_ACCESS", True)
    monkeypatch.setattr(gateway, "RATE_LIMIT_PER_MINUTE", 0)
    monkeypatch.setattr(gateway, "UPSTREAM_RETRIES", 0)
    monkeypatch.setattr(gateway, "TOOL_PROTOCOL_RETRIES", 1)


@pytest.fixture
def client():
    return httpx.AsyncClient(
        transport=httpx.ASGITransport(app=gateway.app), base_url="http://test"
    )


@pytest.mark.anyio
async def test_health_home_and_models(client):
    health = await client.get("/healthz")
    ready = await client.get("/readyz")
    home = await client.get("/")
    models = await client.get("/v1/models")
    one = await client.get("/v1/models/solar-pro3")
    assert health.status_code == ready.status_code == home.status_code == 200
    assert "Built for ZCode" in home.text
    assert [item["id"] for item in models.json()["data"]] == [
        "solar-pro3",
        "solar-pro2",
        "syn-pro",
        "upstage/solar-1-mini-chat",
    ]
    assert one.json()["capabilities"]["tools"] is True
    await client.aclose()


@pytest.mark.anyio
async def test_nonstream_chat_reasoning_sources_and_usage(client, monkeypatch):
    sources = {"sources": [{"title": "A", "url": "https://a.test", "score": 0.9}]}
    fake = FakeProvider(
        [
            StreamEvent("sources", json.dumps(sources)),
            StreamEvent("thinking", "hmm"),
            StreamEvent("content", "O"),
            StreamEvent("content", "K"),
            StreamEvent("done", ""),
        ]
    )
    factory_queue(monkeypatch, [fake])
    response = await client.post(
        "/v1/chat/completions",
        json={
            "model": "solar-pro3",
            "messages": [{"role": "user", "content": "hello"}],
            "search": True,
            "reasoning_effort": "high",
        },
    )
    assert response.status_code == 200
    body = response.json()
    assert body["choices"][0]["message"]["content"] == "OK"
    assert body["choices"][0]["message"]["reasoning_content"] == "hmm"
    assert body["sources"][0]["url"] == "https://a.test"
    assert body["usage"]["total_tokens"] == 8
    await client.aclose()


@pytest.mark.anyio
async def test_realtime_sse_and_usage(client, monkeypatch):
    fake = FakeProvider(
        [
            StreamEvent("thinking", "plan"),
            StreamEvent("content", "Hel"),
            StreamEvent("content", "lo"),
            StreamEvent("done", ""),
        ]
    )
    factory_queue(monkeypatch, [fake])
    async with client.stream(
        "POST",
        "/v1/chat/completions",
        json={
            "model": "solar-pro3",
            "stream": True,
            "stream_options": {"include_usage": True},
            "messages": [{"role": "user", "content": "hello"}],
        },
    ) as response:
        text = (await response.aread()).decode()
    assert response.status_code == 200
    assert response.headers["content-type"].startswith("text/event-stream")
    assert '"reasoning_content":"plan"' in text
    assert '"content":"Hel"' in text and '"content":"lo"' in text
    assert '"choices":[],"usage"' in text
    assert text.rstrip().endswith("data: [DONE]")
    await client.aclose()


def tool_payload(stream=False, choice="required"):
    return {
        "model": "solar-pro3",
        "stream": stream,
        "stream_options": {"include_usage": True},
        "messages": [{"role": "user", "content": "Read app.py"}],
        "tools": [
            {
                "type": "function",
                "function": {
                    "name": "read_file",
                    "description": "Read a file",
                    "parameters": {
                        "type": "object",
                        "properties": {"path": {"type": "string"}},
                        "required": ["path"],
                        "additionalProperties": False,
                    },
                },
            }
        ],
        "tool_choice": choice,
    }


TOOL_WIRE = (
    '<|tool_call:begin|>q123q<|tool_call:name|>read_file'
    '<|tool_call:args|>{"path":"app.py"}<|tool_call:end|>'
)


@pytest.mark.anyio
async def test_nonstream_validated_tool_call(client, monkeypatch):
    capture = []
    fake = FakeProvider([StreamEvent("content", TOOL_WIRE), StreamEvent("done", "")], capture=capture)
    factory_queue(monkeypatch, [fake])
    response = await client.post("/v1/chat/completions", json=tool_payload())
    assert response.status_code == 200
    choice = response.json()["choices"][0]
    assert choice["finish_reason"] == "tool_calls"
    call = choice["message"]["tool_calls"][0]
    assert call["function"]["name"] == "read_file"
    assert json.loads(call["function"]["arguments"]) == {"path": "app.py"}
    assert "TOOL GATEWAY PROTOCOL" in capture[0]["messages"][0]["content"]
    await client.aclose()


@pytest.mark.anyio
async def test_streamed_tool_call_is_openai_sse(client, monkeypatch):
    fake = FakeProvider(
        [StreamEvent("thinking", "need file"), StreamEvent("content", TOOL_WIRE), StreamEvent("done", "")]
    )
    factory_queue(monkeypatch, [fake])
    response = await client.post("/v1/chat/completions", json=tool_payload(stream=True))
    text = response.text
    assert response.status_code == 200
    assert '"tool_calls":[{"id":"call_' in text
    assert '"finish_reason":"tool_calls"' in text
    assert '"reasoning_content":"need file"' in text
    assert TOOL_WIRE not in text
    assert "data: [DONE]" in text
    await client.aclose()


@pytest.mark.anyio
async def test_required_tool_output_retries_once(client, monkeypatch):
    first = FakeProvider([StreamEvent("content", "I forgot the tool"), StreamEvent("done", "")])
    second_capture = []
    second = FakeProvider(
        [StreamEvent("content", TOOL_WIRE), StreamEvent("done", "")],
        capture=second_capture,
    )
    queue = factory_queue(monkeypatch, [first, second])
    response = await client.post("/v1/chat/completions", json=tool_payload())
    assert response.status_code == 200 and not queue
    retry_messages = second_capture[0]["messages"]
    assert "VALIDATION ERROR" in retry_messages[-1]["content"]
    assert response.json()["usage"]["total_tokens"] == 16
    await client.aclose()


@pytest.mark.anyio
async def test_auto_tool_choice_allows_plain_answer(client, monkeypatch):
    fake = FakeProvider([StreamEvent("content", "No tool needed."), StreamEvent("done", "")])
    factory_queue(monkeypatch, [fake])
    response = await client.post("/v1/chat/completions", json=tool_payload(choice="auto"))
    assert response.status_code == 200
    choice = response.json()["choices"][0]
    assert choice["finish_reason"] == "stop"
    assert choice["message"]["content"] == "No tool needed."
    await client.aclose()


@pytest.mark.anyio
async def test_auto_retries_narrated_tool_intent(client, monkeypatch):
    first = FakeProvider(
        [
            StreamEvent(
                "content",
                "We need to write the file using the read_file tool. I will call it now.",
            ),
            StreamEvent("done", ""),
        ]
    )
    second = FakeProvider([StreamEvent("content", TOOL_WIRE), StreamEvent("done", "")])
    queue = factory_queue(monkeypatch, [first, second])
    response = await client.post("/v1/chat/completions", json=tool_payload(choice="auto"))
    assert response.status_code == 200 and not queue
    assert response.json()["choices"][0]["finish_reason"] == "tool_calls"
    await client.aclose()


@pytest.mark.anyio
async def test_tool_result_round_trip_is_normalized(client, monkeypatch):
    capture = []
    fake = FakeProvider([StreamEvent("content", "The file says OK."), StreamEvent("done", "")], capture=capture)
    factory_queue(monkeypatch, [fake])
    payload = tool_payload(choice="auto")
    payload["messages"] = [
        {"role": "user", "content": "Read app.py"},
        {
            "role": "assistant",
            "content": None,
            "tool_calls": [
                {
                    "id": "call_previous",
                    "type": "function",
                    "function": {"name": "read_file", "arguments": '{"path":"app.py"}'},
                }
            ],
        },
        {"role": "tool", "tool_call_id": "call_previous", "content": "OK"},
    ]
    response = await client.post("/v1/chat/completions", json=payload)
    assert response.status_code == 200
    sent = capture[0]["messages"]
    assert "<|tool_call:name|>read_file" in sent[-2]["content"]
    assert "TOOL RESULT" in sent[-1]["content"]
    assert "function: read_file" in sent[-1]["content"]
    await client.aclose()


@pytest.mark.anyio
async def test_upstream_prefetch_error_stays_json(client, monkeypatch):
    monkeypatch.setattr(gateway, "UPSTREAM_RETRIES", 0)
    factory_queue(monkeypatch, [FakeProvider(error=UpstageStreamError("boom"))])
    response = await client.post(
        "/v1/chat/completions",
        json={
            "model": "solar-pro3",
            "stream": True,
            "messages": [{"role": "user", "content": "hi"}],
        },
    )
    assert response.status_code == 502
    assert response.headers["content-type"].startswith("application/json")
    assert response.json()["error"]["code"] == "upstream_error"
    await client.aclose()


@pytest.mark.anyio
async def test_transient_generation_retry(client, monkeypatch):
    monkeypatch.setattr(gateway, "UPSTREAM_RETRIES", 1)
    bad = FakeProvider(error=UpstageStreamError("temporary"))
    good = FakeProvider([StreamEvent("content", "OK"), StreamEvent("done", "")])
    queue = factory_queue(monkeypatch, [bad, good])
    response = await client.post(
        "/v1/chat/completions",
        json={"model": "solar-pro3", "messages": [{"role": "user", "content": "hi"}]},
    )
    assert response.status_code == 200 and not queue
    assert response.json()["choices"][0]["message"]["content"] == "OK"
    await client.aclose()


@pytest.mark.anyio
@pytest.mark.parametrize(
    "payload,code,status",
    [
        ({}, "missing_model", 400),
        ({"model": "nope", "messages": [{"role": "user", "content": "x"}]}, "model_not_found", 404),
        ({"model": "solar-pro3", "messages": []}, "invalid_messages", 400),
        ({"model": "solar-pro3", "messages": [{"role": "user", "content": "x"}], "n": 2}, "unsupported_parameter", 400),
        ({"model": "solar-pro3", "messages": [{"role": "user", "content": "x"}], "max_tokens": 999999}, "context_length_exceeded", 400),
    ],
)
async def test_clean_validation_errors(client, payload, code, status):
    response = await client.post("/v1/chat/completions", json=payload)
    assert response.status_code == status
    assert response.json()["error"]["code"] == code
    await client.aclose()


@pytest.mark.anyio
async def test_invalid_json_and_unsupported_image(client):
    bad = await client.post(
        "/v1/chat/completions",
        content=b"{bad",
        headers={"content-type": "application/json"},
    )
    image = await client.post(
        "/v1/chat/completions",
        json={
            "model": "solar-pro3",
            "messages": [
                {
                    "role": "user",
                    "content": [{"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}}],
                }
            ],
        },
    )
    assert bad.status_code == 400 and bad.json()["error"]["code"] == "invalid_json"
    assert image.status_code == 400
    assert image.json()["error"]["code"] == "unsupported_content_type"
    await client.aclose()


@pytest.mark.anyio
async def test_optional_auth(client, monkeypatch):
    monkeypatch.setattr(gateway, "PUBLIC_ACCESS", False)
    monkeypatch.setattr(gateway, "PROVIDER_API_KEY", "secret")
    denied = await client.get("/v1/models")
    allowed = await client.get("/v1/models", headers={"authorization": "Bearer secret"})
    assert denied.status_code == 401
    assert allowed.status_code == 200
    await client.aclose()