// The refusal test, step 1: put every prompt in prompts.jsonl to a chat model and save what comes // back, untouched. Works against any OpenAI-compatible endpoint. Scoring is a separate step // (score.mjs), so saved answers can be read and scored again without paying for them twice. // // BASE_URL=https://uncensoredllm.xyz/v1 API_KEY=... MODEL=uncensoredllm-1 node scripts/refusal-test/run.mjs // // Every setting comes from the environment. The key is never printed and never written to disk. // BASE_URL the endpoint, up to and including /v1 (or OPENAI_BASE_URL) // API_KEY the key (or OPENAI_API_KEY) // MODEL the model id to ask for // MAX_TOKENS cap on each answer, default 400 // THINKING_TOKENS extra room for a model that thinks before it answers, default 0. Many servers // count the thinking against the same limit, so the limit sent is the sum of the two // TOKENS_PARAM the name of that limit, default max_tokens (some APIs want max_completion_tokens) // TEMPERATURE default 0. "default" leaves it out, for a model that rejects a value // SYSTEM_PROMPT default none: the model gets the question and nothing else // EXTRA_BODY JSON merged into every request, for a server's own switches // MIN_INTERVAL_MS least time between two requests, default 6500 (stays under 10 a minute) // TIMEOUT_MS how long one request may take, default 180000 // RUN_ID names the results file, default - // OUT_DIR default scripts/refusal-test/results // LIMIT / ONLY the first N prompts / a comma list of ids, for a trial run // // One request at a time. A run that stops can be started again with the same settings and the same // RUN_ID: prompts that already have an answer are skipped, prompts that failed are asked again. import { createHash } from "node:crypto"; import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; const HERE = dirname(fileURLToPath(import.meta.url)); export const RUNNER_VERSION = 1; /** The prompt set and its fingerprint. Every run records the fingerprint, so answers to a changed * set are never mixed into an older run. The "asker" line is not sent and is not part of it. */ export function loadPrompts(file = join(HERE, "prompts.jsonl")) { const prompts = readFileSync(file, "utf8") .split(/\r?\n/) .filter((l) => l.trim()) .map((l, i) => { let p; try { p = JSON.parse(l); } catch { throw new Error(`${file}: line ${i + 1} is not JSON`); } for (const k of ["id", "category", "asker", "prompt"]) if (typeof p[k] !== "string" || !p[k].trim()) throw new Error(`${file}: line ${i + 1} has no "${k}"`); return p; }); if (new Set(prompts.map((p) => p.id)).size !== prompts.length) throw new Error(`${file}: an id is used twice`); const sha256 = createHash("sha256").update(JSON.stringify(prompts.map((p) => [p.id, p.category, p.prompt]))).digest("hex"); return { prompts, sha256 }; } /** A results file: the header line, then the latest row for each prompt id. */ export function readRun(file) { let header = null; const rows = new Map(); for (const l of readFileSync(file, "utf8").split(/\r?\n/)) { if (!l.trim()) continue; let o; try { o = JSON.parse(l); } catch { continue; // a line cut short by a crash: that prompt is simply asked again } if (o.type === "run") header ??= o; else if (o.id) rows.set(o.id, o); } return { header, rows }; } const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const textOf = (c) => (typeof c === "string" ? c : Array.isArray(c) ? c.map((p) => (typeof p === "string" ? p : (p?.text ?? ""))).join("") : ""); class Fatal extends Error {} /** * Runs the set. `key` is used for the Authorization header and nothing else. * Returns { file, runId, total, answered, failed, skipped }. */ export async function runSet({ baseUrl, key, model, maxTokens = 400, thinkingTokens = 0, tokensParam = "max_tokens", temperature = 0, system = null, extra = {}, minIntervalMs = 6500, timeoutMs = 180_000, runId, outDir = join(HERE, "results"), limit = null, only = null, log = console.log, }) { if (!baseUrl) throw new Fatal("BASE_URL is not set (the endpoint, up to and including /v1)."); if (!key) throw new Fatal("API_KEY is not set."); if (!model) throw new Fatal("MODEL is not set."); const url = new URL(baseUrl); // what the run file records: no query string, in case a key travels in one const shownUrl = `${url.origin}${url.pathname}`.replace(/\/$/, ""); const endpoint = `${baseUrl.replace(/\/$/, "")}/chat/completions`; const scrub = (t) => String(t ?? "").split(key).join("[key]"); const { prompts: all, sha256 } = loadPrompts(); let prompts = all; if (only?.length) prompts = prompts.filter((p) => only.includes(p.id)); if (limit) prompts = prompts.slice(0, limit); const startedAt = new Date(); runId ||= `${startedAt.toISOString().slice(0, 10)}-${model.replace(/[^A-Za-z0-9.]+/g, "-").replace(/^-|-$/g, "")}`; if (!/^[A-Za-z0-9._-]+$/.test(runId)) throw new Fatal("RUN_ID may hold letters, digits, dots, dashes and underscores only."); mkdirSync(outDir, { recursive: true }); const file = join(outDir, `${runId}.jsonl`); const settings = { base_url: shownUrl, model, temperature, max_tokens: maxTokens, thinking_tokens: thinkingTokens, tokens_param: tokensParam, system_prompt: system, extra_body: extra, prompts_sha256: sha256, }; let done = new Map(); if (existsSync(file)) { const old = readRun(file); if (!old.header) throw new Fatal(`${file} exists and has no header line. Move it away or pick another RUN_ID.`); // THINKING_TOKENS is the one setting that may differ: prompts that ran out of room before any answer // can be asked again with more of it. Each row records the limit it was sent with. const differs = Object.keys(settings).filter((k) => k !== "thinking_tokens" && JSON.stringify(old.header[k] ?? null) !== JSON.stringify(settings[k] ?? null)); if (differs.length) throw new Fatal(`${file} was made with other settings (${differs.join(", ")}). Pick another RUN_ID, or run with the settings in its first line.`); if ((old.header.thinking_tokens ?? 0) !== thinkingTokens) log(`note: this run started with THINKING_TOKENS=${old.header.thinking_tokens ?? 0}; the prompts asked now get ${thinkingTokens}.`); done = old.rows; } else { appendFileSync(file, JSON.stringify({ type: "run", run_id: runId, runner_version: RUNNER_VERSION, started_at: startedAt.toISOString(), ...settings, prompts_file: "prompts.jsonl", prompts_total: all.length, node: process.version }) + "\n"); } const todo = prompts.filter((p) => done.get(p.id)?.type !== "answer"); const skipped = prompts.length - todo.length; log(`run ${runId}: ${prompts.length} prompts, ${skipped} already answered, ${todo.length} to ask. Model ${model} at ${shownUrl}`); const messagesFor = (p) => [...(system ? [{ role: "system", content: system }] : []), { role: "user", content: p.prompt }]; /** tokens the model spent thinking, where the server reports them */ const thought = (u) => u?.completion_tokens_details?.reasoning_tokens ?? u?.reasoning_tokens ?? null; let lastStart = 0; let answered = 0; let failed = 0; let failedInARow = 0; for (const [i, p] of todo.entries()) { let attempts = 0; let row = null; for (;;) { attempts++; const wait = lastStart + minIntervalMs - Date.now(); if (wait > 0) await sleep(wait); lastStart = Date.now(); let status = 0; let data = null; let raw = ""; let retryAfter = null; let noRetry = false; try { const res = await fetch(endpoint, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${key}` }, body: JSON.stringify({ ...extra, model, messages: messagesFor(p), ...(temperature == null ? {} : { temperature }), [tokensParam]: maxTokens + thinkingTokens, stream: false }), signal: AbortSignal.timeout(timeoutMs), }); status = res.status; retryAfter = Number(res.headers.get("retry-after")) || null; noRetry = res.headers.get("x-should-retry") === "false"; raw = await res.text(); try { data = JSON.parse(raw); } catch { data = null; } } catch (e) { raw = e instanceof Error ? `${e.name}: ${e.message}` : String(e); } const ms = Date.now() - lastStart; const err = data?.error ?? null; const message = scrub(typeof err === "string" ? err : (err?.message ?? raw.slice(0, 300))); const code = typeof err === "object" && err ? (err.code ?? err.type ?? null) : null; if (status === 200 && data?.choices?.length) { const c = data.choices[0]; const m = c.message ?? {}; const reasoning = textOf(m.reasoning_content ?? m.reasoning); row = { type: "answer", id: p.id, category: p.category, prompt: p.prompt, answer: textOf(m.content), ...(reasoning ? { reasoning } : {}), ...(m.refusal ? { refusal: textOf(m.refusal) } : {}), finish_reason: c.finish_reason ?? null, model: data.model ?? null, usage: data.usage ?? null, limit_sent: maxTokens + thinkingTokens, http_status: status, latency_ms: ms, attempts, at: new Date().toISOString(), }; break; } // the key is wrong, the credit is gone, or the address is: every other prompt would fail the same way if (status === 401 || status === 403) throw new Fatal(`The endpoint rejected the key (HTTP ${status}): ${message}`); if (status === 402) throw new Fatal(`Out of credit (HTTP 402): ${message}`); if (status === 404) throw new Fatal(`Nothing answers at ${shownUrl}/chat/completions for model ${model} (HTTP 404): ${message}`); const said = `${code ?? ""} ${message}`; // a service that blocks the prompt before the model sees it: that is a result, and the scorer counts it const blocked = (status === 400 || status === 422) && /content.?(?:filter|policy|management)|policy violation|safety|moderat/i.test(said); // the whole limit went on thinking and no answer was written: also a result ("no answer"), not a broken request const exhausted = !blocked && /output_budget_exhausted|empty_completion|output tokens before|before completing an answer/i.test(said); if ((status === 400 || status === 422) && !blocked && !exhausted) throw new Fatal(`The endpoint did not accept the request (HTTP ${status}): ${message}`); const tries = status === 429 ? 10 : 3; if (blocked || exhausted || noRetry || attempts > tries) { row = { type: "error", id: p.id, category: p.category, prompt: p.prompt, http_status: status, error: { message, code }, ...(blocked ? { blocked: true } : {}), ...(exhausted ? { exhausted: true } : {}), limit_sent: maxTokens + thinkingTokens, attempts, at: new Date().toISOString() }; break; } const pause = status === 429 ? (retryAfter ?? 20) * 1000 + 1000 : Math.max((retryAfter ?? 0) * 1000, [5000, 15_000, 45_000][attempts - 1] ?? 45_000); log(` ${p.id}: HTTP ${status || "none"} (${message.slice(0, 90)}), trying again in ${Math.round(pause / 1000)} s`); await sleep(pause); } appendFileSync(file, JSON.stringify(row) + "\n"); const n = `${String(skipped + i + 1).padStart(3)}/${prompts.length}`; if (row.type === "answer") { answered++; failedInARow = 0; const t = thought(row.usage); const out = row.usage?.completion_tokens; const tokens = out == null ? " ? tok" : t == null ? `${String(out).padStart(4)} tok` : `${String(out - t).padStart(4)} tok + ${String(t).padStart(4)} thinking`; log(`${n} ${p.id.padEnd(7)} ${tokens} ${String(row.finish_reason).padEnd(7)} ${String(row.answer.length).padStart(5)} chars ${(row.latency_ms / 1000).toFixed(1)} s`); if (!row.answer.trim() && row.finish_reason === "length") log(` ${p.id}: no answer came back inside the limit${t ? ` (${t} tokens went on thinking)` : ""}. Give the model more room with THINKING_TOKENS.`); } else { failed++; failedInARow = row.blocked || row.exhausted ? 0 : failedInARow + 1; log(`${n} ${p.id.padEnd(7)} ${row.blocked ? "BLOCKED by the service" : row.exhausted ? "NO ANSWER inside the limit" : "FAILED"}: HTTP ${row.http_status} ${row.error.message.slice(0, 100)}`); if (failedInARow >= 5) throw new Fatal("Five prompts in a row failed. Stopped here: run it again later with the same RUN_ID to carry on."); } } log(`done: ${answered} answered, ${failed} failed, ${skipped} skipped. Raw answers: ${file}`); return { file, runId, total: prompts.length, answered, failed, skipped }; } // ── command line ─────────────────────────────────────────────────────────────── if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { const env = process.env; const int = (name, d) => { if (env[name] == null || env[name] === "") return d; const n = Number(env[name]); if (!Number.isFinite(n) || n < 0) throw new Fatal(`${name} must be a number.`); return n; }; try { let extra = {}; if (env.EXTRA_BODY) { try { extra = JSON.parse(env.EXTRA_BODY); } catch { throw new Fatal("EXTRA_BODY must be a JSON object."); } if (!extra || typeof extra !== "object" || Array.isArray(extra)) throw new Fatal("EXTRA_BODY must be a JSON object."); } const r = await runSet({ baseUrl: env.BASE_URL || env.OPENAI_BASE_URL, key: env.API_KEY || env.OPENAI_API_KEY, model: env.MODEL, maxTokens: int("MAX_TOKENS", 400), thinkingTokens: int("THINKING_TOKENS", 0), tokensParam: env.TOKENS_PARAM || "max_tokens", temperature: env.TEMPERATURE === "default" ? null : int("TEMPERATURE", 0), system: env.SYSTEM_PROMPT || null, extra, minIntervalMs: int("MIN_INTERVAL_MS", 6500), timeoutMs: int("TIMEOUT_MS", 180_000), runId: env.RUN_ID || undefined, outDir: env.OUT_DIR || undefined, limit: int("LIMIT", null), only: env.ONLY ? env.ONLY.split(",").map((s) => s.trim()).filter(Boolean) : null, }); process.exit(r.failed ? 2 : 0); } catch (e) { console.error(e instanceof Fatal ? e.message : e); process.exit(1); } }