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