import {z} from 'zod' export type CacheControl = {type?: 'ephemeral' | undefined, ttl?: string | undefined}; export type ChatMessage = {role: 'assistant' | 'user' | 'system' | 'tool' | 'developer', name?: string | undefined, content?: (string | Array<{type: 'text' | 'image_url' | 'input_audio' | 'file' | 'refusal', text?: string | undefined, refusal?: string | undefined, image_url?: ({url: string, detail?: ('low' | 'high' | 'auto') | undefined}) | undefined, input_audio?: ({data: string, format?: string | undefined}) | undefined, file?: ({file_data?: string | undefined, file_id?: string | undefined, filename?: string | undefined, file_type?: string | undefined}) | undefined, cache_control?: CacheControl | undefined}>) | undefined, tool_call_id?: string | undefined, refusal?: string | undefined, audio?: ({id?: string | undefined, data?: string | undefined, expires_at?: number | undefined, transcript?: string | undefined}) | undefined, reasoning?: string | undefined, reasoning_details?: (Array<{id?: string | undefined, index?: number | undefined, type?: ('reasoning.summary' | 'reasoning.encrypted' | 'reasoning.text') | undefined, summary?: string | undefined, text?: string | undefined, signature?: string | undefined, data?: string | undefined}>) | undefined, annotations?: (Array<{type?: string | undefined, url_citation?: ({start_index?: number | undefined, end_index?: number | undefined, title?: string | undefined, url?: string | undefined, sources?: Record | undefined, type?: string | undefined}) | undefined}>) | undefined, tool_calls?: (Array<{index?: number | undefined, type?: string | undefined, id?: string | undefined, function: {name?: string | undefined, arguments?: string | undefined}}>) | undefined}; export type ChatCompletionRequest = {model: string, messages: Array, fallbacks?: Array | undefined, stream?: boolean | undefined, frequency_penalty?: number | undefined, logit_bias?: {[key: string]: number} | undefined, logprobs?: boolean | undefined, max_completion_tokens?: number | undefined, metadata?: {[key: string]: unknown} | undefined, modalities?: Array | undefined, parallel_tool_calls?: boolean | undefined, presence_penalty?: number | undefined, prompt_cache_key?: string | undefined, reasoning?: ({effort?: ('none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh') | undefined, max_tokens?: number | undefined}) | undefined, response_format?: Record | undefined, safety_identifier?: string | undefined, service_tier?: string | undefined, stream_options?: ({include_obfuscation?: boolean | undefined, include_usage?: boolean | undefined}) | undefined, store?: boolean | undefined, temperature?: number | undefined, tool_choice?: ('none' | 'auto' | 'required' | {type: 'none' | 'any' | 'required' | 'function' | 'allowed_tools' | 'custom', function?: {name: string} | undefined, allowed_tools?: ({mode?: ('auto' | 'required') | undefined, tools?: (Array<{type: string, function?: {name: string} | undefined}>) | undefined}) | undefined}) | undefined, tools?: (Array<{type: 'function' | 'custom', function?: ({name: string, description?: string | undefined, parameters?: ({type?: string | undefined, description?: string | undefined, required?: Array | undefined, properties?: {[key: string]: unknown} | undefined, enum?: Array | undefined, additionalProperties?: boolean | undefined}) | undefined, strict?: boolean | undefined}) | undefined, custom?: ({format?: ({type: string, grammar?: ({definition: string, syntax: 'lark' | 'regex'}) | undefined}) | undefined}) | undefined, cache_control?: CacheControl | undefined}>) | undefined, seed?: number | undefined, top_p?: number | undefined, top_logprobs?: number | undefined, stop?: (string | Array) | undefined, prediction?: ({type?: string | undefined, content?: (string | Array<{[key: string]: unknown}>) | undefined}) | undefined, prompt_cache_retention?: ('in_memory' | '24h') | undefined, web_search_options?: ({search_context_size?: ('low' | 'medium' | 'high') | undefined, user_location?: ({type?: string | undefined, approximate?: ({city?: string | undefined, country?: string | undefined, region?: string | undefined, timezone?: string | undefined}) | undefined}) | undefined}) | undefined, truncation?: string | undefined, user?: string | undefined, verbosity?: ('low' | 'medium' | 'high') | undefined}; export type CreateApiV1AsyncChatCompletionsArgs = {'x-bf-async-job-result-ttl'?: number | undefined, 'x-bf-async-webhook'?: string | undefined, body: ChatCompletionRequest}; export type CreateApiV1AsyncChatCompletionsOptions = {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 chat completion * * POST /v1/async/chat/completions * * Also accepts auth: BasicAuth, VirtualKeyAuth, ApiKeyAuth */ export const createApiV1AsyncChatCompletions = async (args: CreateApiV1AsyncChatCompletionsArgs, options?: CreateApiV1AsyncChatCompletionsOptions) => { 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/chat/completions${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()) };