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 const { gateway, defaultHeaders } = config
45 return await run(
46 model,
47 bindingInputs,
48 gateway || defaultHeaders
49 ? {
50 ...(gateway && { gateway }),
51 ...(defaultHeaders && { extraHeaders: defaultHeaders }),
52 }
53 : undefined,
54 )
55 }
56
57 const url = new URL(
58 `${CLOUDFLARE_API_BASE}/accounts/${config.accountId}/ai/run/${model}`,
59 )
60 const headers: Record<string, string> = {
61 Authorization: `Bearer ${config.apiKey}`,
62 ...gatewayHeaders(config.gateway),
63 }
64 let body: BodyInit
65 if (options?.binary) {
66 // Binary tasks take the bytes as the body and the other inputs as query.
67 for (const [key, value] of Object.entries(inputs)) {
68 if (value !== undefined) url.searchParams.set(key, String(value))
69 }
70 headers['Content-Type'] = options.binary.contentType
71 body = options.binary.body as BodyInit
72 } else {
73 headers['Content-Type'] = 'application/json'
74 body = JSON.stringify(inputs)
75 }
76 const fetchImpl = config.fetch ?? fetch
77 const response = await fetchImpl(url, {
78 method: 'POST',
79 headers,
80 body,
81 signal: options?.signal,
82 })
83 if (!response.ok) {
84 throw new Error(
85 `Workers AI request for ${model} failed (${response.status}): ${await response.text()}`,
86 )
87 }
88 if (response.headers.get('content-type')?.includes('application/json')) {
89 const json = (await response.json()) as {
90 success?: boolean
91 result?: unknown
92 errors?: Array<{ message?: string }>
93 }
94 if (json.success === false) {
95 throw new Error(
96 `Workers AI request for ${model} failed: ${json.errors?.map((e) => e.message).join('; ')}`,
97 )
98 }
99 return 'result' in json ? json.result : json
100 }
101 return new Uint8Array(await response.arrayBuffer())
102}
103
104/** Base64-encodes a binary model output, whatever shape it arrived in. */
105export async function outputToBase64(output: unknown): Promise<string> {
106 if (typeof output === 'string') return output
107 let bytes: Uint8Array
108 if (output instanceof Uint8Array) {
109 bytes = output
110 } else if (output instanceof ArrayBuffer) {
111 bytes = new Uint8Array(output)
112 } else if (output instanceof ReadableStream) {
113 bytes = new Uint8Array(await new Response(output).arrayBuffer())
114 } else {
115 throw new Error(
116 `Unexpected Workers AI output type: ${Object.prototype.toString.call(output)}`,
117 )
118 }
119 const copy = new Uint8Array(bytes.byteLength)
120 copy.set(bytes)
121 return arrayBufferToBase64(copy.buffer)
122}