const body = {"kind":"decision","state":{"ticket":"I was charged twice this month and nobody answers my emails."},"questions":{"urgent":{"type":"noul","instructions":"reply within the hour?"}},"max_output_tokens":16};
async function createRunWithRetry(payload: unknown, maxAttempts = 2) {
for (let attempt = 1; ; attempt++) {
const res = await fetch("https://api.opentype.dev/v1/runs", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.OPENTYPE_API_KEY}`,
"Content-Type": "application/json",
// A new key per attempt: the failed run stays pending under the old key.
"Idempotency-Key": crypto.randomUUID(),
},
body: JSON.stringify(payload),
});
const data = await res.json();
if (res.ok) return data;
const { code, message, request_id } = data.error;
console.error(`POST /v1/runs -> ${res.status} ${code}: ${message} (${request_id})`);
if (res.status < 500 || attempt >= maxAttempts) throw new Error(`${code} (${request_id})`);
await new Promise((r) => setTimeout(r, 2 ** attempt * 1000));
}
}
const run = await createRunWithRetry(body);