File size: 3,289 Bytes
970e644
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Verify model identity and three typed probability readouts over System One."""

import argparse
import json
import math
import os
import urllib.request

MODEL = "APUS-Reflex2.1"


def call(url, payload=None):
    headers = {"User-Agent": "APUS-Eval/1.0", "Content-Type": "application/json"}
    if os.environ.get("APUS_TOKEN"):
        headers["Authorization"] = "Bearer " + os.environ["APUS_TOKEN"]
    body = json.dumps(payload).encode() if payload is not None else None
    with urllib.request.urlopen(
        urllib.request.Request(url, data=body, headers=headers), timeout=90
    ) as response:
        data = response.read()
        return json.loads(data) if data else {}


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--url", default="http://127.0.0.1:8000")
    url = p.parse_args().url.rstrip("/")
    call(url + "/health")
    if [x["id"] for x in call(url + "/v1/models")["data"]] != [MODEL]:
        raise ValueError("Unexpected served-model identity")
    req = {
        "model": MODEL,
        "state": "The customer reports a duplicate invoice charge.",
        "questions": {
            "queue": {
                "type": "choice",
                "instructions": "Choose a support queue.",
                "criteria": {"billing": "Billing", "shipping": "Delivery"},
            },
            "duplicate": {"type": "noul", "instructions": "Is the charge duplicated?"},
            "relevance": {
                "type": "score",
                "instructions": "How relevant is this to billing?",
                "criteria": ["unrelated", "partly relevant", "directly relevant"],
            },
        },
    }
    response = call(url + "/v1/systemone", req)
    if response["model"] != MODEL or set(response["answers"]) != set(req["questions"]):
        raise ValueError("Unexpected inference response identity or question keys")
    for key, answer in response["answers"].items():
        prob = answer["probabilities"]
        if (
            answer["type"] != req["questions"][key]["type"]
            or not prob
            or not all(
                math.isfinite(value) and 0 <= value <= 1 for value in prob.values()
            )
            or not math.isclose(sum(prob.values()), 1, abs_tol=1e-5)
        ):
            raise ValueError(f"Invalid probabilities for {key}")
        if key == "queue" and (
            set(prob) != {"billing", "shipping"}
            or prob[answer["choice"]] != max(prob.values())
        ):
            raise ValueError("Invalid choice readout")
        if key == "duplicate":
            yes = "yes" if set(prob) == {"yes", "no"} else "true"
            if set(prob) not in ({"yes", "no"}, {"true", "false"}) or not math.isclose(
                answer["noul"], prob[yes], abs_tol=1e-5
            ):
                raise ValueError("Invalid binary readout")
        if key == "relevance" and (
            set(prob) != {"0", "1", "2"}
            or not math.isclose(
                answer["score"],
                sum(int(level) * val for level, val in prob.items()),
                abs_tol=1e-5,
            )
        ):
            raise ValueError("Invalid ordinal readout")
    print(json.dumps(response, ensure_ascii=False))


if __name__ == "__main__":
    main()