An LLM adapter pattern for Cloudflare Workers
By Flavio
Tagged: JavaScript
Swap LLM providers with a small adapter pattern. One complete() interface, fetch-based OpenAI calls on Workers, env var switching, graceful degradation.
If every route in your app imports a vendor SDK directly, switching from OpenAI to Groq, OpenRouter, or a local dev bridge turns into a messy refactor across the whole codebase.
I ran into this on one of my Cloudflare Workers apps, where heavy SDKs often don’t run inside workerd. I ended up putting a tiny adapter in front of the LLM calls instead.
One interface
Start by defining only the methods your app needs. In my case, that came down to a two-method interface:
/** @typedef {object} LlmAdapter
* @property {(input: RationaleInput) => Promise<Rationale>} generateRationale
* @property {(prompt: string) => Promise<string>} completeText
*/
Every provider implements that same shape. The route handlers call adapter.completeText(prompt) and parse the JSON string that comes back, without ever importing openai or @cursor/sdk directly.
Fetch-based OpenAI adapter
The OpenAI SDK works fine in Node, but on Cloudflare Workers it’s much cleaner to call the API directly with fetch:
function openAiAdapter({ apiKey, model, baseUrl }) {
async function completeText(prompt) {
const res = await fetch(`${baseUrl}/chat/completions`, {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model,
messages: [{ role: 'user', content: prompt }],
temperature: 0.7,
}),
})
if (!res.ok) throw new Error(`LLM failed (${res.status})`)
const data = await res.json()
const text = data.choices?.[0]?.message?.content
if (!text) throw new Error('Empty LLM response')
return text
}
return {
async generateRationale(input) {
const prompt = buildPrompt(input)
return parseRationaleResponse(await completeText(prompt))
},
completeText,
}
}
Because the request and response JSON format is standard across OpenAI-compatible endpoints, you can point baseUrl at OpenRouter, Groq, Cloudflare AI Gateway, or Vercel AI Gateway without changing the rest of the adapter.
Swap providers with an env var
Next, put provider selection in a single helper so the rest of the app doesn’t care where completions come from:
function getAdapter(env) {
if (env.LLM_PROVIDER === 'openai' && env.OPENAI_API_KEY) {
return openAiAdapter({
apiKey: env.OPENAI_API_KEY,
model: env.OPENAI_MODEL || 'gpt-4o-mini',
baseUrl: env.OPENAI_BASE_URL || 'https://api.openai.com/v1',
})
}
if (env.LLM_PROVIDER === 'cursor' && env.CURSOR_API_KEY) {
return cursorAdapter(env.CURSOR_API_KEY, env.CURSOR_BRIDGE_URL)
}
return null
}
In production, the app uses LLM_PROVIDER=openai. Locally with astro dev, you can set LLM_PROVIDER=cursor and POST to a Node middleware that runs the Cursor SDK, since that SDK can’t execute inside workerd even during dev.
Degrade gracefully
An LLM call shouldn’t take down a page when no provider is configured. When getAdapter() returns null, the route can hide the AI feature instead of crashing:
const adapter = getAdapter(env)
if (!adapter) return null
try {
return await adapter.generateRationale(input)
} catch (err) {
console.error('LLM rationale failed:', err)
return null
}
In my Workers app, a rules engine computes recommended stacks and prices for a report page, and a separate prefill feature reads repository manifests from a GitHub URL. When getAdapter() returns null, the report page still shows those stacks and costs while omitting the LLM-written prose block, and the GitHub URL prefill keeps working from manifest scanning alone.
That separation also keeps bad model output from breaking billing logic, because the rules engine handles providers and prices while the LLM only writes prose on top of numbers you already computed. You can also cache successful responses in KV keyed by a hash of the input so repeat views skip the network call.
Parse defensively
Even when you ask for JSON, models often wrap their replies in markdown code fences. Strip the fences first, extract the outermost {...} block, validate the result with Zod, and retry once if validation fails.
Keep the prompt builders and parsers in the same module as the adapters so the interface stays thin and the vendor-specific details live in one file. In my setup, buildPrompt() and buildExtractionPrompt() sit right next to openAiAdapter(), while routes only import getAdapter and the parse helpers and never touch vendor URLs.
Why not the SDK everywhere
If you’re building a Node app, installing @anthropic-ai/sdk or openai and calling it a day makes plenty of sense. If you do use @anthropic-ai/sdk, check what changed before you upgrade it, because a major bump can change the API version your app sends.
Cloudflare Workers give you fetch, crypto, and TextEncoder, rather than the full Node API surface vendor packages expect. A twenty-line fetch wrapper avoids those runtime gaps, only needs to be tested once, and behaves the same in wrangler dev, production, and any OpenAI-compatible host.
Want me to talk about your product? You can sponsor this site.
Related posts about js: