Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kody/clef

Cloudflare Clef decision models via Workers AI (Jev-shaped noul/choice/score API).

FollowFork

Files

request.ts

187 lines · 5.1 KB · TypeScript
/**
 * Escape-hatch raw Cloudflare `/ai/run/@cf/cloudflare/clef(-flash)` call.
 * Prefer `./evaluate` for parsed answers; use this when you need the full envelope.
 *
 * Unlike Jev, Clef uses a **flat** body (`model` + `state` + `questions`) and the
 * model id is also in the URL path.
 *
 * @param input.state - Shared state (string or object) to evaluate.
 * @param input.questions - Named noul / choice / score questions.
 * @param input.accountId - Optional Cloudflare account id override.
 * @param input.gatewayId - Optional AI Gateway id (sent as `cf-aig-gateway-id`).
 * @param input.model - Optional model id (default `@cf/cloudflare/clef-flash`).
 * @returns `{ ok, status, data }` — never logs secrets.
 *
 * @example
 * import clefRequest from 'kody:@kody/clef/request'
 *
 * const raw = await clefRequest({
 *   state: 'hello',
 *   questions: {
 *     greeting: { type: 'noul', instructions: 'Is this a greeting?' },
 *   },
 * })
 */

import { credential } from 'kody:runtime'
import {
	missingSetup,
	resolveClefConfig,
} from './resolve.ts'
import { ClefRequestInputSchema, formatSchemaError, parse } from './schema.ts'
import type { ClefRequestInput, ClefRequestResult } from './types.ts'

function stringify(value: unknown) {
	try {
		return JSON.stringify(value)
	} catch {
		return String(value)
	}
}

/**
 * Escape-hatch raw Cloudflare `/ai/run/@cf/cloudflare/clef(-flash)` call.
 * Prefer `./evaluate` for parsed answers; use this when you need the full envelope.
 *
 * @param input.state - Shared state (string or object) to evaluate.
 * @param input.questions - Named noul / choice / score questions.
 * @param input.accountId - Optional Cloudflare account id override.
 * @param input.gatewayId - Optional AI Gateway id (sent as `cf-aig-gateway-id`).
 * @param input.model - Optional model id (default `@cf/cloudflare/clef-flash`).
 * @returns `{ ok, status, data }` — never logs secrets.
 *
 * @example
 * import clefRequest from 'kody:@kody/clef/request'
 *
 * const raw = await clefRequest({
 *   state: 'hello',
 *   questions: {
 *     greeting: { type: 'noul', instructions: 'Is this a greeting?' },
 *   },
 * })
 */
export default async function clefRequest(
	input: ClefRequestInput,
): Promise<ClefRequestResult> {
	let parsed: ClefRequestInput
	try {
		parsed = parse(ClefRequestInputSchema, input ?? {}) as ClefRequestInput
	} catch (error) {
		return {
			ok: false,
			status: 0,
			data: null,
			error: formatSchemaError(error),
		}
	}

	if (parsed.state === undefined || parsed.state === null) {
		return { ok: false, status: 0, data: null, error: 'state is required' }
	}
	if (!parsed.questions || typeof parsed.questions !== 'object') {
		return {
			ok: false,
			status: 0,
			data: null,
			error: 'questions must be a non-empty object',
		}
	}

	const config = await resolveClefConfig({
		accountId: parsed.accountId,
		gatewayId: parsed.gatewayId,
		model: parsed.model,
	})

	if (!config.accountId) {
		return {
			ok: false,
			status: 0,
			data: null,
			error: 'cloudflareAccountId is not set',
			setup: missingSetup(''),
		}
	}

	const url =
		'https://api.cloudflare.com/client/v4/accounts/' +
		config.accountId +
		'/ai/run/' +
		config.urlModel

	let client: { fetch: typeof fetch }
	try {
		// The scoped client follows the package credential mapping for `cloudflareApiToken`
		// (provider `cloudflare`), so an org-mapped token works where a by-name placeholder would not.
		client = (await credential('cloudflareApiToken')) as { fetch: typeof fetch }
	} catch (error) {
		return {
			ok: false,
			status: 0,
			data: null,
			error:
				'credential cloudflareApiToken unavailable: ' +
				(error instanceof Error ? error.message : String(error)),
			setup: missingSetup(''),
		}
	}

	const headers: Record<string, string> = {
		'Content-Type': 'application/json',
		'cf-aig-gateway-id': config.gatewayId,
		// The body carries caller text; never fill secret placeholders there.
		'x-kody-secret-resolution': 'headers-only',
		...(parsed.headers && typeof parsed.headers === 'object'
			? (parsed.headers as Record<string, string>)
			: {}),
	}

	// Flat Clef body (NOT Jev's `{ model, input: { state, questions } }`).
	const body = {
		model: config.bodyModel,
		state: parsed.state,
		questions: parsed.questions,
	}

	try {
		const response = await client.fetch(url, {
			method: 'POST',
			headers,
			body: JSON.stringify(body),
		})
		const text = await response.text()
		let data: unknown = text
		try {
			data = text ? JSON.parse(text) : null
		} catch {
			data = text
		}
		if (!response.ok) {
			return {
				ok: false,
				status: response.status,
				data,
				error:
					'Cloudflare /ai/run failed: HTTP ' +
					response.status +
					' ' +
					(typeof data === 'string'
						? data.slice(0, 500)
						: stringify(data).slice(0, 500)),
				setup:
					response.status === 401 || response.status === 403
						? missingSetup(config.accountId)
						: undefined,
			}
		}
		return { ok: true, status: response.status, data }
	} catch (error) {
		return {
			ok: false,
			status: 0,
			data: null,
			error: error instanceof Error ? error.message : String(error),
			setup: missingSetup(config.accountId),
		}
	}
}