import {z} from 'zod' export type CacheControl = {type?: 'ephemeral' | undefined, ttl?: string | undefined}; export type ResponsesRequest = {model: string, input: string | Array<{id?: string | undefined, type?: ('message' | 'file_search_call' | 'computer_call' | 'computer_call_output' | 'web_search_call' | 'web_fetch_call' | 'function_call' | 'function_call_output' | 'code_interpreter_call' | 'local_shell_call' | 'local_shell_call_output' | 'mcp_call' | 'custom_tool_call' | 'custom_tool_call_output' | 'image_generation_call' | 'mcp_list_tools' | 'mcp_approval_request' | 'mcp_approval_responses' | 'reasoning' | 'item_reference' | 'refusal') | undefined, status?: ('in_progress' | 'completed' | 'incomplete' | 'interpreting' | 'failed') | undefined, role?: ('assistant' | 'user' | 'system' | 'developer') | undefined, content?: (string | Array<{type: 'input_text' | 'input_image' | 'input_file' | 'input_audio' | 'output_text' | 'refusal' | 'reasoning_text', file_id?: string | undefined, text?: string | undefined, signature?: string | undefined, image_url?: string | undefined, detail?: string | undefined, file_data?: string | undefined, file_url?: string | undefined, filename?: string | undefined, file_type?: string | undefined, input_audio?: ({format: 'mp3' | 'wav', data: string}) | undefined, annotations?: (Array<{type?: ('file_citation' | 'url_citation' | 'container_file_citation' | 'file_path') | undefined, index?: number | undefined, file_id?: string | undefined, text?: string | undefined, start_index?: number | undefined, end_index?: number | undefined, filename?: string | undefined, title?: string | undefined, url?: string | undefined, container_id?: string | undefined}>) | undefined, logprobs?: (Array<{bytes?: Array | undefined, logprob?: number | undefined, token?: string | undefined, top_logprobs?: (Array<{bytes?: Array | undefined, logprob?: number | undefined, token?: string | undefined}>) | undefined}>) | undefined, refusal?: string | undefined, cache_control?: CacheControl | undefined}>) | undefined, call_id?: string | undefined, name?: string | undefined, arguments?: string | undefined, output?: (string | Array<{type: 'input_text' | 'input_image' | 'input_file' | 'input_audio' | 'output_text' | 'refusal' | 'reasoning_text', file_id?: string | undefined, text?: string | undefined, signature?: string | undefined, image_url?: string | undefined, detail?: string | undefined, file_data?: string | undefined, file_url?: string | undefined, filename?: string | undefined, file_type?: string | undefined, input_audio?: ({format: 'mp3' | 'wav', data: string}) | undefined, annotations?: (Array<{type?: ('file_citation' | 'url_citation' | 'container_file_citation' | 'file_path') | undefined, index?: number | undefined, file_id?: string | undefined, text?: string | undefined, start_index?: number | undefined, end_index?: number | undefined, filename?: string | undefined, title?: string | undefined, url?: string | undefined, container_id?: string | undefined}>) | undefined, logprobs?: (Array<{bytes?: Array | undefined, logprob?: number | undefined, token?: string | undefined, top_logprobs?: (Array<{bytes?: Array | undefined, logprob?: number | undefined, token?: string | undefined}>) | undefined}>) | undefined, refusal?: string | undefined, cache_control?: CacheControl | undefined}> | {type?: 'computer_screenshot' | undefined, file_id?: string | undefined, image_url?: string | undefined}) | undefined, action?: Record | undefined, error?: string | undefined, queries?: Array | undefined, results?: Array> | undefined, summary?: Array<{type: 'summary_text', text: string}> | undefined, encrypted_content?: string | undefined}>, fallbacks?: Array | undefined, stream?: boolean | undefined, background?: boolean | undefined, conversation?: string | undefined, include?: Array | undefined, instructions?: string | undefined, max_output_tokens?: number | undefined, max_tool_calls?: number | undefined, metadata?: {[key: string]: unknown} | undefined, parallel_tool_calls?: boolean | undefined, previous_response_id?: string | undefined, prompt_cache_key?: string | undefined, reasoning?: ({effort?: ('none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh') | undefined, generate_summary?: string | undefined, summary?: ('auto' | 'concise' | 'detailed') | undefined, max_tokens?: number | undefined}) | undefined, safety_identifier?: string | undefined, service_tier?: string | undefined, stream_options?: ({include_obfuscation?: boolean | undefined}) | undefined, store?: boolean | undefined, temperature?: number | undefined, text?: ({format?: ({type: 'text' | 'json_schema' | 'json_object', name?: string | undefined, schema?: Record | undefined, strict?: boolean | undefined}) | undefined, verbosity?: ('low' | 'medium' | 'high') | undefined}) | undefined, top_logprobs?: number | undefined, top_p?: number | undefined, tool_choice?: ('none' | 'auto' | 'required' | {type: 'none' | 'auto' | 'any' | 'required' | 'function' | 'allowed_tools' | 'file_search' | 'web_search_preview' | 'computer_use_preview' | 'code_interpreter' | 'image_generation' | 'mcp' | 'custom', mode?: string | undefined, name?: string | undefined, server_label?: string | undefined, tools?: (Array<{type: 'function' | 'mcp' | 'image_generation', name?: string | undefined, server_label?: string | undefined}>) | undefined}) | undefined, tools?: (Array<{type: 'function' | 'file_search' | 'computer_use_preview' | 'web_search' | 'web_fetch' | 'mcp' | 'code_interpreter' | 'image_generation' | 'local_shell' | 'custom' | 'web_search_preview' | 'memory' | 'tool_search', name?: string | undefined, description?: string | undefined, cache_control?: CacheControl | 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, vector_store_ids?: Array | undefined, filters?: Record | undefined, max_num_results?: number | undefined, ranking_options?: Record | undefined, display_height?: number | undefined, display_width?: number | undefined, environment?: string | undefined, enable_zoom?: boolean | undefined, search_context_size?: string | undefined, user_location?: Record | undefined, server_label?: string | undefined, server_url?: string | undefined, allowed_tools?: Record | undefined, authorization?: string | undefined, connector_id?: string | undefined, headers?: {[key: string]: string} | undefined, require_approval?: Record | undefined, server_description?: string | undefined, container?: Record | undefined, background?: string | undefined, input_fidelity?: string | undefined, input_image_mask?: Record | undefined, moderation?: string | undefined, output_compression?: number | undefined, output_format?: string | undefined, partial_images?: number | undefined, quality?: string | undefined, size?: string | undefined, format?: Record | undefined}>) | undefined, truncation?: string | undefined}; export type CreateApiV1AsyncResponsesArgs = {'x-bf-async-job-result-ttl'?: number | undefined, 'x-bf-async-webhook'?: string | undefined, body: ResponsesRequest}; export type CreateApiV1AsyncResponsesOptions = {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 response * * POST /v1/async/responses * * Also accepts auth: BasicAuth, VirtualKeyAuth, ApiKeyAuth */ export const createApiV1AsyncResponses = async (args: CreateApiV1AsyncResponsesArgs, options?: CreateApiV1AsyncResponsesOptions) => { 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/responses${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()) };