import {z} from 'zod' export type ConfidentialComputeRequest = {ciphertext: string, client_dh_public_key: string, model_name: string, node_dh_public_key: string, nonce: string, num_compute_units?: (number | null) | undefined, plaintext_body_hash: string, salt: string, stack_small_id: number, stream?: (boolean | null) | undefined}; export type CreateApiV1ConfidentialEmbeddingsArgs = {body: ConfidentialComputeRequest}; export type CreateApiV1ConfidentialEmbeddingsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const promptTokensDetails = z.object({cached_tokens: z.number().int()}); export const completionUsage = z.object({completion_tokens: z.number().int(), prompt_tokens: z.number().int(), prompt_tokens_details: promptTokensDetails.nullable().optional(), total_tokens: z.number().int()}); export const confidentialComputeResponse = z.object({ciphertext: z.string(), nonce: z.string(), response_hash: z.string().nullable().optional(), signature: z.string().nullable().optional(), usage: completionUsage.nullable().optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Handler for confidential embeddings requests * * POST /v1/confidential/embeddings */ export const createApiV1ConfidentialEmbeddings = async (args: CreateApiV1ConfidentialEmbeddingsArgs, options?: CreateApiV1ConfidentialEmbeddingsOptions) => { const {baseUrl = "http://localhost:8080", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/v1/confidential/embeddings${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(confidentialComputeResponse, await res.json()) };