Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

fetch.ts

131 lines4.4 KB

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 })
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 })
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)
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 }
125​
126/** Wraps a REST fetch so responses get the same error and trailer fixes. */
127export function createRestFetch(baseFetch: FetchLike | undefined): FetchLike {
128 const fetchImpl = baseFetch ?? fetch
129 return async (input, init) =>
130 await normalizeResponse(await fetchImpl(input, init))