titlegen-benchmark-luna / api_generate.py
ManhHoDinh's picture
Publish Luna benchmark f025bc48e911
018b80e verified
Raw History Blame Contribute Delete
9.51 kB
"""Generate benchmark predictions using an explicitly selected compatible endpoint."""
from __future__ import annotations
import argparse
from contextlib import contextmanager
import hashlib
import json
import os
from pathlib import Path
from urllib.parse import urlsplit
from urllib.request import Request, HTTPRedirectHandler, build_opener
PROTOCOL = "titlegen-public-api-generation-v1"
DEFAULT_INSTRUCTION = "Create one concise title for the conversation. Return only the title in the language of the conversation. Do not answer the conversation."
def canonical(value):
return json.dumps(
value, sort_keys=True, separators=(",", ":"), ensure_ascii=True
).encode()
def parse_response(response):
choices = response.get("choices")
if not isinstance(choices, list) or len(choices) != 1:
raise ValueError("Expected exactly one generated choice")
if choices[0].get("finish_reason") != "stop":
raise ValueError("Generation did not finish normally; no prediction saved")
title = choices[0].get("message", {}).get("content")
if not isinstance(title, str) or not title.strip():
raise ValueError("Expected a nonempty generated title")
return title
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, request, response, code, message, headers, new_url):
raise ValueError("Endpoint redirects are not allowed")
def validate_model(response, configuration):
expected = configuration.get("response_model") or configuration["model"]
if response.get("model") != expected:
raise ValueError(
"Provider response model differs from the explicit expected model"
)
def endpoint_request(configuration, messages, api_key):
headers = {"Content-Type": "application/json"}
if api_key:
headers["Authorization"] = "Bearer " + api_key
payload = {
"model": configuration["model"],
"messages": messages,
"temperature": 0,
"max_tokens": configuration["max_tokens"],
}
request = Request(
configuration["base_url"].rstrip("/") + "/chat/completions",
data=canonical(payload),
headers=headers,
)
with build_opener(NoRedirect()).open(request, timeout=120) as response:
result = json.load(response)
validate_model(result, configuration)
return parse_response(result)
@contextmanager
def output_lock(path):
lock = path.with_name(path.name + ".lock")
with lock.open("a+b") as stream:
try:
if os.name == "nt":
import msvcrt
if stream.tell() == 0:
stream.write(b"0")
stream.flush()
stream.seek(0)
msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError as error:
raise ValueError(
"Output is locked by another generation process"
) from error
try:
yield
finally:
if os.name == "nt":
stream.seek(0)
msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
else:
fcntl.flock(stream.fileno(), fcntl.LOCK_UN)
def run(argv=None, *, request=endpoint_request, environment=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--inputs", required=True)
parser.add_argument("--output", required=True)
parser.add_argument("--model", required=True)
parser.add_argument(
"--response-model",
help="Exact canonical model name returned by an aliased endpoint",
)
parser.add_argument(
"--base-url",
required=True,
help="Compatible base URL ending /v1; appends /chat/completions",
)
parser.add_argument("--api-key-env", default="OPENAI_API_KEY")
parser.add_argument("--max-tokens", type=int, default=32)
parser.add_argument("--task-instruction", default=DEFAULT_INSTRUCTION)
arguments = parser.parse_args(argv)
endpoint = urlsplit(arguments.base_url)
if (
endpoint.scheme not in ("http", "https")
or not endpoint.netloc
or endpoint.username
or endpoint.password
or endpoint.query
or endpoint.fragment
):
raise ValueError(
"Expected an HTTP(S) base URL without embedded credentials or query"
)
if not arguments.model.strip() or not 1 <= arguments.max_tokens <= 32768:
raise ValueError("Expected model name and max-tokens in 1..32768")
if endpoint.scheme == "http" and endpoint.hostname not in (
"localhost",
"127.0.0.1",
"::1",
):
raise ValueError(
"Remote endpoints must use HTTPS; HTTP is allowed only for loopback"
)
rows = [
json.loads(line)
for line in Path(arguments.inputs).read_text().splitlines()
if line.strip()
]
identifiers = set()
for row in rows:
identifier = row.get("id")
messages = row.get("messages")
if (
not isinstance(identifier, str)
or not identifier
or identifier in identifiers
):
raise ValueError("Input IDs must be unique nonempty strings")
if (
not isinstance(messages, list)
or not messages
or any(
not isinstance(message, dict)
or message.get("role") not in ("system", "user", "assistant")
or not isinstance(message.get("content"), str)
for message in messages
)
):
raise ValueError(
"Input messages must have supported roles and string content"
)
identifiers.add(identifier)
if not rows:
raise ValueError("Inputs must not be empty")
configuration = {
"protocol": PROTOCOL,
"input_sha256": hashlib.sha256(canonical(rows)).hexdigest(),
"model": arguments.model,
"response_model": arguments.response_model,
"base_url": arguments.base_url.rstrip("/"),
"max_tokens": arguments.max_tokens,
"temperature": 0,
"task_instruction": arguments.task_instruction,
}
output = Path(arguments.output)
output.parent.mkdir(parents=True, exist_ok=True)
identity_path = output.with_name(output.name + ".generation.json")
with output_lock(output):
if identity_path.exists():
if json.loads(identity_path.read_bytes()) != configuration:
raise ValueError(
"Generation identity changed; use a new output for a different configuration"
)
elif output.exists():
raise ValueError(
"Existing output has no generation identity; use a new output"
)
else:
with identity_path.open("x", encoding="utf-8") as identity_file:
identity_file.write(canonical(configuration).decode() + "\n")
identity_file.flush()
os.fsync(identity_file.fileno())
completed = {}
if output.exists():
for line in output.read_text().splitlines():
prediction = json.loads(line)
if (
set(prediction) != {"id", "title"}
or prediction["id"] not in identifiers
or prediction["id"] in completed
or not isinstance(prediction["title"], str)
or not prediction["title"].strip()
):
raise ValueError(
"Invalid saved predictions; do not silently overwrite"
)
completed[prediction["id"]] = prediction["title"]
api_key = (os.environ if environment is None else environment).get(
arguments.api_key_env, ""
)
with output.open("a", encoding="utf-8") as predictions:
for row in rows:
if row["id"] in completed:
continue
messages = row["messages"]
if arguments.task_instruction:
messages = [
{"role": "system", "content": arguments.task_instruction}
] + messages
title = request(configuration, messages, api_key)
if not isinstance(title, str) or not title.strip():
raise ValueError("Expected a nonempty generated title")
predictions.write(
canonical({"id": row["id"], "title": title}).decode() + "\n"
)
predictions.flush()
os.fsync(predictions.fileno())
completed[row["id"]] = title
return {"status": "GENERATED", "count": len(completed), "expected_count": len(rows)}
def main():
try:
print(json.dumps(run(), sort_keys=True))
except Exception as error:
print(
json.dumps(
{
"status": "FAILED",
"error_type": type(error).__name__,
"note": "Completed rows remain saved; inspect the input/configuration and retry. A failed in-flight provider call may have been charged.",
}
)
)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())