"""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)