import {z} from 'zod' export type ModelProvider = '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 type Fallback = {provider: ModelProvider, model: string}; export type CreateApiV1AsyncImagesGenerationsArgs = {'x-bf-async-job-result-ttl'?: number | undefined, 'x-bf-async-webhook'?: string | undefined, body: {model: string, prompt: string, n?: number | undefined, size?: ('256x256' | '512x512' | '1024x1024' | '1792x1024' | '1024x1792' | '1536x1024' | '1024x1536' | 'auto') | undefined, quality?: ('auto' | 'high' | 'medium' | 'low' | 'hd' | 'standard') | undefined, style?: ('natural' | 'vivid') | undefined, response_format?: ('url' | 'b64_json') | undefined, background?: ('transparent' | 'opaque' | 'auto') | undefined, moderation?: ('low' | 'auto') | undefined, partial_images?: number | undefined, output_compression?: number | undefined, output_format?: ('png' | 'webp' | 'jpeg') | undefined, user?: string | undefined, seed?: number | undefined, negative_prompt?: string | undefined, num_inference_steps?: number | undefined, stream?: boolean | undefined, fallbacks?: Array | undefined}}; export type CreateApiV1AsyncImagesGenerationsOptions = {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 image generation * * POST /v1/async/images/generations * * Also accepts auth: BasicAuth, VirtualKeyAuth, ApiKeyAuth */ export const createApiV1AsyncImagesGenerations = async (args: CreateApiV1AsyncImagesGenerationsArgs, options?: CreateApiV1AsyncImagesGenerationsOptions) => { 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/images/generations${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()) };