import {z} from 'zod' export type EncodingFormat = 'float' | 'base64'; export type InputType = string | Array; export type Input = InputType | Array; export type OpenAICompatRequest = {encoding_format?: EncodingFormat | undefined, input: Input, model?: (string | null) | undefined, user?: (string | null) | undefined}; export type CreateApiV1EmbeddingsArgs = {body: OpenAICompatRequest}; export type CreateApiV1EmbeddingsOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const embedding = z.union([z.array(z.number()), z.string()]); export const openAICompatEmbedding = z.object({embedding: embedding, index: z.number().int().gte(0), object: z.string()}); export const openAICompatUsage = z.object({prompt_tokens: z.number().int().gte(0), total_tokens: z.number().int().gte(0)}); export const openAICompatResponse = z.object({data: z.array(openAICompatEmbedding), model: z.string(), object: z.string(), usage: openAICompatUsage}); 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 }; /** * OpenAI compatible route. Returns a 424 status code if the model is not an embedding model. * * POST /v1/embeddings */ export const createApiV1Embeddings = async (args: CreateApiV1EmbeddingsArgs, options: CreateApiV1EmbeddingsOptions) => { const {baseUrl, 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/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(openAICompatResponse, await res.json()) };