# Run a batch on Batchrate with the official OpenAI Python SDK.
#   pip install openai
#   export BATCHRATE_API_KEY=br_live_...
#   python batch.py batch.jsonl
import json
import os
import sys
import time

from openai import OpenAI

client = OpenAI(api_key=os.environ["BATCHRATE_API_KEY"], base_url="https://api.batchrate.ai/v1")
path = sys.argv[1] if len(sys.argv) > 1 else "batch.jsonl"

with open(path, "rb") as handle:
    batch_file = client.files.create(file=handle, purpose="batch")
print("uploaded", batch_file.id)

batch = client.batches.create(
    input_file_id=batch_file.id,
    endpoint="/v1/chat/completions",
    completion_window="24h",
)
print("batch", batch.id, batch.status)

while batch.status not in ("completed", "failed", "cancelled", "expired"):
    time.sleep(30)
    batch = client.batches.retrieve(batch.id)
    counts = batch.request_counts
    print(batch.status, f"{counts.completed}/{counts.total} done, {counts.failed} failed")

if batch.output_file_id:
    for line in client.files.content(batch.output_file_id).text.splitlines():
        result = json.loads(line)
        message = result["response"]["body"]["choices"][0]["message"]["content"]
        print(result["custom_id"], "->", message)

if batch.error_file_id:
    print("errors:")
    print(client.files.content(batch.error_file_id).text)
