Cloudflare Workers

Cloudflare Workers with an OpenAI-compatible uncensored API

Call Abliterator from a Cloudflare Worker: store the key with wrangler secret, stream tokens through a TransformStream, and log usage after the response with waitUntil.

Reviewed Cloudflare WorkersTypeScript

Quick answer

Save the key with wrangler secret put ABL_API_KEY, then create new OpenAI({ baseURL: "https://abliterator.ai/v1", apiKey: env.ABL_API_KEY }) inside the fetch handler. Workers have no process.env by default; the key arrives on env.

A Worker is a fetch handler, and the official openai package runs in it unchanged because it is built on fetch. Secrets reach the handler on env, as described in Cloudflare's Workers secrets docs. The examples were type-checked with tsc --strict against @cloudflare/workers-types and their handlers called with test requests against a stand-in server.

Setup

npm create cloudflare@latest abl-worker -- --type hello-world --lang ts
cd abl-worker
npm install openai
npx wrangler secret put ABL_API_KEY

For wrangler dev, put the key in .dev.vars (ABL_API_KEY=sk-abl-v1-...) and keep that file out of git.

A JSON endpoint

src/index.ts:

import OpenAI from "openai";

interface Env {
  ABL_API_KEY: string;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    if (request.method !== "POST") return new Response("POST {\"url\": ...}", { status: 405 });
    const { url } = (await request.json()) as { url: string };

    const abliterator = new OpenAI({ baseURL: "https://abliterator.ai/v1", apiKey: env.ABL_API_KEY });
    const r = await abliterator.chat.completions.create({
      model: "deepseek-v4.1-flash-abliterated",
      messages: [
        { role: "system", content: "You assess URLs for a phishing-report triage queue. Reply with verdict and reasons." },
        { role: "user", content: url },
      ],
      max_tokens: 300,
    });
    return Response.json({ verdict: r.choices[0].message.content });
  },
} satisfies ExportedHandler<Env>;

Create the client inside fetch, where the env parameter exists. Creating one per request is cheap; the SDK holds no connection state worth sharing in a Worker.

Stream tokens through a TransformStream

Return the readable side immediately and write to the other side as chunks arrive. ctx.waitUntil keeps the Worker alive until the stream finishes:

import OpenAI from "openai";

interface Env {
  ABL_API_KEY: string;
}

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    const { messages } = (await request.json()) as { messages: OpenAI.ChatCompletionMessageParam[] };
    const abliterator = new OpenAI({ baseURL: "https://abliterator.ai/v1", apiKey: env.ABL_API_KEY });
    const stream = await abliterator.chat.completions.create({ model: "kimi-k3.1-pro-abliterated", messages, stream: true });

    const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>();
    const writer = writable.getWriter();
    const encoder = new TextEncoder();

    ctx.waitUntil(
      (async () => {
        let usage: unknown = null;
        try {
          for await (const chunk of stream) {
            const text = chunk.choices[0]?.delta?.content;
            if (text) await writer.write(encoder.encode(`data: ${JSON.stringify(text)}\n\n`));
            if (chunk.usage) usage = chunk.usage;
          }
          await writer.write(encoder.encode("data: [DONE]\n\n"));
        } finally {
          await writer.close();
          console.log(JSON.stringify({ event: "abl_usage", usage }));
        }
      })(),
    );

    return new Response(readable, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } });
  },
} satisfies ExportedHandler<Env>;

The console.log line lands in Workers Logs, a cheap way to track tokens and the usage.cost Abliterator reports per request. Swap it for a write to KV, D1 or Analytics Engine if you need queries.

Troubleshooting

  • Missing credentials from the SDK. The secret is not bound. Run npx wrangler secret put ABL_API_KEY for the deployed Worker, or add it to .dev.vars for wrangler dev.
  • ReferenceError: env is not defined. The client was created at module scope, outside the handler that receives env. Move it inside fetch.
  • Usage logs never appear. Work that runs after the last byte is sent, like the log line in finally, needs ctx.waitUntil; otherwise the runtime can stop the invocation first.
  • Many users at once hit 429. Each open stream counts against your plan's concurrent-request limit, and Workers scale fast. Queue or reject above that level (/docs/rate-limits).
  • Responses API helpers. abliterator.responses.create is not available; use chat.completions.

Frequently asked questions

Does the openai package need nodejs_compat on Workers?

No. The SDK only needs fetch and web streams, which Workers provide. Enable nodejs_compat only if other dependencies need Node built-ins.

Do long generations hit the Worker CPU limit?

Waiting on Abliterator's response is I/O, not CPU time, so a long stream uses little CPU. Keep per-chunk work small; parsing and re-encoding every chunk is what consumes CPU.

Can I put Cloudflare AI Gateway in front of Abliterator?

This page does not cover it. The Worker calls Abliterator directly, which keeps one hop between your users and the model.