File size: 2,711 Bytes
e165512
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Run independent answer checks through an authenticated ClusterFK endpoint."""

import argparse
import json
import os
import time
from pathlib import Path

import requests


def qualify(url, model, cases, out):
    rows = []
    token = os.environ["CLUSTERFK_TOKEN"]
    for case in cases[model]:
        start = time.monotonic()
        first = None
        end = False
        chunks = []
        body = {
            "model": model,
            "messages": [{"role": "user", "content": case["question"]}],
            "temperature": 0,
            "max_tokens": 192,
            "stream": True,
        }
        with requests.post(
            url.rstrip("/") + "/v1/chat/completions",
            headers={"Authorization": "Bearer " + token},
            json=body,
            stream=True,
            timeout=(15, 360),
        ) as response:
            response.raise_for_status()
            for line in response.iter_lines(chunk_size=1):
                if not line.startswith(b"data:"):
                    continue
                payload = line[5:].strip()
                if payload == b"[DONE]":
                    end = True
                    break
                data = json.loads(payload)
                if data.get("error"):
                    raise RuntimeError(
                        "gateway error: " + str(data["error"].get("code"))
                    )
                for choice in data.get("choices", []):
                    text = choice.get("delta", {}).get("content")
                    if text:
                        if first is None:
                            first = time.monotonic() - start
                        chunks.append(text)
        answer = "".join(chunks)
        if not end or not answer:
            raise RuntimeError("incomplete stream on " + case["id"])
        rows.append(
            {
                **case,
                "answer": answer,
                "cited_expected_url": case["source"] in answer
                if case["source"]
                else None,
                "first_text_seconds": round(first, 2),
                "total_seconds": round(time.monotonic() - start, 2),
            }
        )
        out.write_text(json.dumps({"model": model, "responses": rows}, indent=2) + "\n")


if __name__ == "__main__":
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("model")
    p.add_argument("output", type=Path)
    p.add_argument(
        "--cases", type=Path, default=Path(__file__).with_name("qualification.json")
    )
    p.add_argument("--url", default="https://clusterfk.hgws.sh")
    args = p.parse_args()
    qualify(args.url, args.model, json.loads(args.cases.read_text()), args.output)