import {z} from 'zod' export type EmbeddingRequest = {model: string, input: string | Array | Array | Array>, fallbacks?: Array | undefined, encoding_format?: ('float' | 'base64') | undefined, dimensions?: number | undefined}; export type CreateApiV1AsyncEmbeddingsArgs = {'x-bf-async-job-result-ttl'?: number | undefined, 'x-bf-async-webhook'?: string | undefined, body: EmbeddingRequest}; export type CreateApiV1AsyncEmbeddingsOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const asyncJobStatus = z.enum(["pending", "processing", "completed", "failed"]); export const errorField = z.object({type: z.string().optional(), code: z.string().optional(), message: z.string().optional(), param: z.string().optional(), event_id: z.string().optional()}); export const modelProvider = z.enum(["openai", "azure", "anthropic", "bedrock", "cohere", "vertex", "vllm", "mistral", "ollama", "groq", "sgl", "parasail", "perplexity", "replicate", "cerebras", "deepseek", "gemini", "openrouter", "elevenlabs", "huggingface", "nebius", "xai", "runway", "fireworks"]); export const bifrostErrorExtraFields = z.object({provider: modelProvider.optional(), model_requested: z.string().optional(), request_type: z.string().optional()}); export const bifrostError = z.object({event_id: z.string().optional(), type: z.string().optional(), is_bifrost_error: z.boolean().optional(), status_code: z.number().int().optional(), error: errorField.optional(), extra_fields: bifrostErrorExtraFields.optional()}); export const asyncJobResponse = z.object({id: z.string(), status: asyncJobStatus, expires_at: z.string().optional(), created_at: z.string(), completed_at: z.string().optional(), status_code: z.number().int().optional(), result: z.unknown(), error: bifrostError.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 }; /** * Create async embedding * * POST /v1/async/embeddings * * Also accepts auth: BasicAuth, VirtualKeyAuth, ApiKeyAuth */ export const createApiV1AsyncEmbeddings = async (args: CreateApiV1AsyncEmbeddingsArgs, options?: CreateApiV1AsyncEmbeddingsOptions) => { const {baseUrl = "http://localhost:8080", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['x-bf-async-job-result-ttl'] != null) headers.set("x-bf-async-job-result-ttl", String(args['x-bf-async-job-result-ttl'])) if (args['x-bf-async-webhook'] != null) headers.set("x-bf-async-webhook", String(args['x-bf-async-webhook'])) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/async/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(asyncJobResponse, await res.json()) };