Open History to see the last commit
1import { arrayBufferToBase64 } from '@tanstack/ai-utils'
2import { CLOUDFLARE_API_BASE, gatewayHeaders, isBindingConfig } from './config'
3import type { CloudflareConfig } from './config'
4
5export type RunInputs = Record<string, unknown>
6
7export interface RunBinary {
8 /** Input field that carries the bytes on the binding path. */
9 field: string
10 body: Uint8Array | ArrayBuffer | Blob
11 contentType: string
12}
13
14/**
15 * Runs a Workers AI model with its native task inputs (embeddings, image,
16 * speech, transcription) through the binding or the REST `/ai/run` endpoint.
17 *
18 * Returns the model's decoded output: an object for JSON tasks, or bytes
19 * (`Uint8Array` / `ReadableStream`) for binary media outputs.
20 */
21export async function runModel(
22 config: CloudflareConfig,
23 model: string,
24 inputs: RunInputs,
25 options?: { signal?: AbortSignal; binary?: RunBinary },
26): Promise<unknown> {
27 if (isBindingConfig(config)) {
28 const run = config.binding.run.bind(config.binding) as (
29 model: string,
30 inputs: RunInputs,
31 options?: Record<string, unknown>,
32 ) => Promise<unknown>
33 // The binding serializes inputs as JSON; binary bodies must travel as a
34 // ReadableStream, which it forwards as the raw request body.
35 const bindingInputs = options?.binary
36 ? {
37 ...inputs,
38 [options.binary.field]: {
39 body: new Response(options.binary.body as BodyInit).body,
40 contentType: options.binary.contentType,
41 },
42 }
43 : inputs
44 return await run(
45 model,
46 bindingInputs,
47 config.gateway ? { gateway: config.gateway } : undefined,
48 )
49 }
50
51 const url = new URL(
52 `${CLOUDFLARE_API_BASE}/accounts/${config.accountId}/ai/run/${model}`,
53 )
54 const headers: Record<string, string> = {
55 Authorization: `Bearer ${config.apiKey}`,
56 ...gatewayHeaders(config.gateway),
57 }
58 let body: BodyInit
59 if (options?.binary) {
60 // Binary tasks take the bytes as the body and the other inputs as query.
61 for (const [key, value] of Object.entries(inputs)) {
62 if (value !== undefined) url.searchParams.set(key, String(value))
63 }
64 headers['Content-Type'] = options.binary.contentType
65 body = options.binary.body as BodyInit
66 } else {
67 headers['Content-Type'] = 'application/json'
68 body = JSON.stringify(inputs)
69 }
70 const fetchImpl = config.fetch ?? fetch
71 const response = await fetchImpl(url, {
72 method: 'POST',
73 headers,
74 body,
75 signal: options?.signal,
76 })
77 if (!response.ok) {
78 throw new Error(
79 `Workers AI request for ${model} failed (${response.status}): ${await response.text()}`,
80 )
81 }
82 if (response.headers.get('content-type')?.includes('application/json')) {
83 const json = (await response.json()) as {
84 success?: boolean
85 result?: unknown
86 errors?: Array<{ message?: string }>
87 }
88 if (json.success === false) {
89 throw new Error(
90 `Workers AI request for ${model} failed: ${json.errors?.map((e) => e.message).join('; ')}`,
91 )
92 }
93 return 'result' in json ? json.result : json
94 }
95 return new Uint8Array(await response.arrayBuffer())
96}
97
98/** Base64-encodes a binary model output, whatever shape it arrived in. */
99export async function outputToBase64(output: unknown): Promise<string> {
100 if (typeof output === 'string') return output
101 let bytes: Uint8Array
102 if (output instanceof Uint8Array) {
103 bytes = output
104 } else if (output instanceof ArrayBuffer) {
105 bytes = new Uint8Array(output)
106 } else if (output instanceof ReadableStream) {
107 bytes = new Uint8Array(await new Response(output).arrayBuffer())
108 } else {
109 throw new Error(
110 `Unexpected Workers AI output type: ${Object.prototype.toString.call(output)}`,
111 )
112 }
113 const copy = new Uint8Array(bytes.byteLength)
114 copy.set(bytes)
115 return arrayBufferToBase64(copy.buffer)
116}