Open History to see the last commit
1import type { Ai } from '@cloudflare/workers-types'
2import type {
3 CloudflareBindingConfig,
4 CloudflareGatewayOptions,
5 FetchLike,
6} from './config'
7
8/**
9 * Workers AI streams end with a usage-only trailer (`{"response":"","usage":
10 * {...}}`) that has no `choices` field. The OpenAI Chat Completions stream
11 * reader indexes `chunk.choices[0]` on every event, so give such events an
12 * empty `choices` array (OpenAI's own usage-only trailer shape) and keep the
13 * usage totals they carry. SSE allows `data:` without the space, and CR, LF
14 * or CRLF line ends.
15 */
16export function normalizeSseResponse(response: Response): Response {
17 const contentType = response.headers.get('content-type') ?? ''
18 if (
19 !response.body ||
20 !contentType.toLowerCase().includes('text/event-stream')
21 ) {
22 return response
23 }
24 let buffer = ''
25 const fixLine = (line: string): string => {
26 if (!line.startsWith('data:')) return line
27 const data = line.slice(line.startsWith('data: ') ? 6 : 5)
28 if (data === '[DONE]') return line
29 try {
30 const event = JSON.parse(data) as Record<string, unknown>
31 if (event && typeof event === 'object' && !('choices' in event)) {
32 return `data: ${JSON.stringify({ ...event, choices: [] })}`
33 }
34 } catch {
35 // Not JSON: forward untouched.
36 }
37 return line
38 }
39 const body = response.body
40 .pipeThrough(new TextDecoderStream())
41 .pipeThrough(
42 new TransformStream<string, string>({
43 transform(chunk, controller) {
44 buffer += chunk
45 // ponytail: a CRLF split across two chunks adds one blank line.
46 // That only ends the current event at its last line.
47 const lines = buffer.split(/\r\n|\r|\n/)
48 buffer = lines.pop() ?? ''
49 for (const line of lines) controller.enqueue(`${fixLine(line)}\n`)
50 },
51 flush(controller) {
52 if (buffer) controller.enqueue(fixLine(buffer))
53 },
54 }),
55 )
56 .pipeThrough(new TextEncoderStream())
57 return new Response(body, {
58 status: response.status,
59 statusText: response.statusText,
60 headers: response.headers,
61 })
62}
63
64/**
65 * Cloudflare error bodies look like `{ name, message, internalCode }` or
66 * `{ errors: [{ code, message }] }`. The OpenAI SDK only reads
67 * `body.error.message`, so rewrap them or every failure reads as
68 * "status code (no body)".
69 */
70export async function normalizeErrorResponse(
71 response: Response,
72): Promise<Response> {
73 const text = await response.text()
74 let body = text
75 try {
76 const json = JSON.parse(text) as {
77 error?: unknown
78 errors?: Array<{ code?: number; message?: string }>
79 message?: string
80 name?: string
81 internalCode?: number
82 }
83 if (json && typeof json === 'object' && !('error' in json)) {
84 const first = json.errors?.[0]
85 body = JSON.stringify({
86 error: {
87 message: json.message ?? first?.message ?? text,
88 type: json.name ?? 'cloudflare_error',
89 code: json.internalCode ?? first?.code ?? null,
90 },
91 })
92 }
93 } catch {
94 // Not JSON: forward the text as-is.
95 }
96 return new Response(body, {
97 status: response.status,
98 statusText: response.statusText,
99 headers: response.headers,
100 })
101}
102
103/** Applies the error and SSE normalizations a raw Cloudflare response needs. */
104export async function normalizeResponse(response: Response): Promise<Response> {
105 return response.ok
106 ? normalizeSseResponse(response)
107 : await normalizeErrorResponse(response)
108}
109
110/**
111 * Makes `env.AI` look like an OpenAI-compatible HTTP endpoint to the OpenAI
112 * SDK: the JSON request body becomes `binding.run(model, inputs)` and the
113 * raw inference `Response` (OpenAI-format JSON or SSE) is handed back.
114 *
115 * The SDK's own request headers (auth, user agent, `x-stainless-*`) are
116 * dropped; only the configured `defaultHeaders` reach Workers AI.
117 */
118export function createBindingFetch({
119 binding,
120 gateway,
121 defaultHeaders,
122}: CloudflareBindingConfig): FetchLike {
123 // `Ai` is typed against the bundled model catalog; the adapter accepts any
124 // model id, so widen the binding to the open catalog shape for this call.
125 const run = binding.run.bind(binding) as (
126 model: string,
127 inputs: Record<string, unknown>,
128 options: Record<string, unknown>,
129 ) => Promise<unknown>
130 return async (_input, init) => {
131 const { model, ...inputs } = JSON.parse(
132 typeof init?.body === 'string' ? init.body : '{}',
133 ) as { model: string } & Record<string, unknown>
134 const response = (await run(model, inputs, {
135 returnRawResponse: true,
136 ...(gateway && { gateway }),
137 ...(defaultHeaders && { extraHeaders: defaultHeaders }),
138 })) as Response
139 return await normalizeResponse(response)
140 }
141}
142
143/** Options of {@link cloudflareBindingFetch}. */
144export interface CloudflareBindingFetchOptions {
145 /** The Workers AI binding, `env.AI`. */
146 binding: Ai
147 /**
148 * The AI Gateway vendor of the model. `'anthropic'` carries Anthropic
149 * Messages requests (`createAnthropicChat`), and `'openai'` carries OpenAI
150 * Responses requests (`createOpenaiChat`).
151 */
152 vendor: 'anthropic' | 'openai'
153 /** AI Gateway options, passed to `env.AI.run`. */
154 gateway?: CloudflareGatewayOptions
155}
156
157// The SDK's transport and auth headers. The binding authenticates by itself.
158const SDK_HEADERS = new Set([
159 'x-api-key',
160 'authorization',
161 'anthropic-version',
162 'user-agent',
163 'content-type',
164 'accept',
165 'content-length',
166 'idempotency-key',
167 'openai-organization',
168 'openai-project',
169 'anthropic-dangerous-direct-browser-access',
170])
171
172function forwardedHeaders(headers: HeadersInit | undefined) {
173 const forwarded: Record<string, string> = {}
174 for (const [name, value] of new Headers(headers)) {
175 if (!SDK_HEADERS.has(name) && !name.startsWith('x-stainless-')) {
176 forwarded[name] = value
177 }
178 }
179 return forwarded
180}
181
182/**
183 * A `fetch` that sends the requests of the Anthropic or OpenAI SDK through the
184 * Workers AI binding, to the AI Gateway `anthropic/...` or `openai/...` models.
185 * Pass it as `fetch` to `createAnthropicChat` or `createOpenaiChat`. The
186 * binding authenticates, so the key argument can be any placeholder.
187 *
188 * The request body goes to `env.AI.run('<vendor>/<model>', body)`. Headers
189 * such as `anthropic-beta` go along as `extraHeaders`.
190 *
191 * @example
192 * ```ts
193 * const adapter = createAnthropicChat('claude-opus-5-5', 'cloudflare-binding', {
194 * fetch: cloudflareBindingFetch({ binding: env.AI, vendor: 'anthropic' }),
195 * })
196 * ```
197 */
198export function cloudflareBindingFetch(
199 options: CloudflareBindingFetchOptions,
200): FetchLike {
201 const { binding, vendor, gateway } = options
202 // `Ai` is typed against the bundled catalog; gateway ids are outside it.
203 // With `returnRawResponse`, the binding returns the raw `Response`.
204 const run = binding.run.bind(binding) as (
205 model: string,
206 inputs: Record<string, unknown>,
207 options: Record<string, unknown>,
208 ) => Promise<Response>
209 const prefix = `${vendor}/`
210 return async (_input, init) => {
211 if (typeof init?.body !== 'string') {
212 throw new Error('cloudflareBindingFetch needs a JSON string body.')
213 }
214 const { model, ...body }: { model?: string } & Record<string, unknown> =
215 JSON.parse(init.body)
216 const id = model ?? ''
217 const extraHeaders = forwardedHeaders(init.headers)
218 const pending = run(id.startsWith(prefix) ? id : prefix + id, body, {
219 returnRawResponse: true,
220 ...(gateway && { gateway }),
221 ...(Object.keys(extraHeaders).length > 0 && { extraHeaders }),
222 })
223 // `env.AI.run` takes no signal, so an abort rejects the wait instead.
224 const { signal } = init
225 signal?.throwIfAborted()
226 const response = await (signal
227 ? Promise.race([
228 pending,
229 new Promise<never>((_, reject) =>
230 signal.addEventListener('abort', () => reject(signal.reason), {
231 once: true,
232 }),
233 ),
234 ])
235 : pending)
236 return response.ok ? response : await normalizeErrorResponse(response)
237 }
238}
239
240/** Wraps a REST fetch so responses get the same error and trailer fixes. */
241export function createRestFetch(baseFetch: FetchLike | undefined): FetchLike {
242 const fetchImpl = baseFetch ?? fetch
243 return async (input, init) =>
244 await normalizeResponse(await fetchImpl(input, init))
245}