Spaces:
Sleeping

File size: 4,806 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
#!/usr/bin/env python3
"""End-to-end smoke test for a running local or deployed gateway."""
from __future__ import annotations

import json
import sys
import urllib.error
import urllib.request

BASE = (sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:7860").rstrip("/")


def request(path: str, payload=None, stream=False):
    data = json.dumps(payload).encode() if payload is not None else None
    req = urllib.request.Request(
        BASE + path,
        data=data,
        headers={
            "Content-Type": "application/json",
            "Authorization": "Bearer public",
            "User-Agent": "upstage-zcode-smoke/2.0",
        },
    )
    try:
        response = urllib.request.urlopen(req, timeout=360)
        raw = response.read().decode("utf-8", "replace")
        return response.status, raw
    except urllib.error.HTTPError as exc:
        raise AssertionError(f"HTTP {exc.code} {path}: {exc.read().decode()}") from exc


def tool_definition():
    return {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather in a city",
            "parameters": {
                "type": "object",
                "properties": {"city": {"type": "string"}},
                "required": ["city"],
                "additionalProperties": False,
            },
        },
    }


def main():
    status, raw = request("/healthz")
    assert status == 200 and json.loads(raw)["ok"] is True
    print("PASS health")

    _, raw = request("/v1/models")
    ids = [item["id"] for item in json.loads(raw)["data"]]
    assert "solar-pro3" in ids and "solar-pro2" in ids
    print(f"PASS models ({len(ids)})")

    _, raw = request(
        "/v1/chat/completions",
        {
            "model": "solar-pro3",
            "stream": False,
            "messages": [{"role": "user", "content": "Reply with exactly OK"}],
            "max_tokens": 32,
        },
    )
    body = json.loads(raw)
    text = body["choices"][0]["message"]["content"]
    assert text and "OK" in text.upper()
    assert body["usage"]["total_tokens"] > 0
    print("PASS non-streaming chat")

    _, raw = request(
        "/v1/chat/completions",
        {
            "model": "solar-pro3",
            "stream": True,
            "stream_options": {"include_usage": True},
            "messages": [{"role": "user", "content": "Reply with exactly STREAM_OK"}],
            "max_tokens": 32,
        },
    )
    chunks = []
    for line in raw.splitlines():
        if not line.startswith("data: ") or line == "data: [DONE]":
            continue
        item = json.loads(line[6:])
        choices = item.get("choices") or []
        if choices:
            chunks.append(choices[0].get("delta", {}).get("content", ""))
    assert "STREAM_OK" in "".join(chunks)
    assert "data: [DONE]" in raw
    assert '"choices":[]' in raw and '"usage"' in raw
    print("PASS realtime SSE + usage")

    _, raw = request(
        "/v1/chat/completions",
        {
            "model": "solar-pro3",
            "stream": False,
            "messages": [
                {
                    "role": "user",
                    "content": "Use get_weather to check Delhi. Do not guess the weather.",
                }
            ],
            "tools": [tool_definition()],
            "tool_choice": "required",
            "temperature": 0.1,
            "max_tokens": 256,
        },
    )
    body = json.loads(raw)
    choice = body["choices"][0]
    assert choice["finish_reason"] == "tool_calls"
    call = choice["message"]["tool_calls"][0]
    assert call["function"]["name"] == "get_weather"
    arguments = json.loads(call["function"]["arguments"])
    assert "delhi" in arguments["city"].lower()
    print("PASS required function call")

    _, raw = request(
        "/v1/chat/completions",
        {
            "model": "solar-pro3",
            "stream": False,
            "messages": [
                {"role": "user", "content": "Use get_weather to check Delhi, then summarize."},
                {"role": "assistant", "content": None, "tool_calls": [call]},
                {
                    "role": "tool",
                    "tool_call_id": call["id"],
                    "content": json.dumps({"city": "Delhi", "temperature_c": 31, "condition": "clear"}),
                },
            ],
            "tools": [tool_definition()],
            "tool_choice": "auto",
            "temperature": 0.1,
            "max_tokens": 256,
        },
    )
    body = json.loads(raw)
    followup = body["choices"][0]
    assert followup["finish_reason"] == "stop"
    assert followup["message"]["content"]
    print("PASS tool-result continuation")
    print("ALL SMOKE TESTS PASSED")


if __name__ == "__main__":
    main()