import {z} from 'zod' export type CacheControl = {type?: 'ephemeral' | undefined, ttl?: string | undefined}; export type CreateApiV1ResponsesCompactArgs = {body: {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}>) | undefined, instructions?: string | undefined, previous_response_id?: string | undefined, prompt_cache_key?: string | undefined, prompt_cache_retention?: string | undefined, service_tier?: string | undefined, fallbacks?: Array | undefined}}; export type CreateApiV1ResponsesCompactOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const cacheControl = z.object({type: z.literal("ephemeral").optional(), ttl: z.string().optional()}); export const bifrostCost = z.object({input_tokens_cost: z.number().optional(), output_tokens_cost: z.number().optional(), reasoning_tokens_cost: z.number().optional(), citation_tokens_cost: z.number().optional(), search_queries_cost: z.number().optional(), request_cost: z.number().optional(), total_cost: z.number().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 bifrostCacheDebug = z.object({cache_hit: z.boolean().optional(), cache_id: z.string().optional(), hit_type: z.string().optional(), requested_provider: z.string().optional(), requested_model: z.string().optional(), provider_used: z.string().optional(), model_used: z.string().optional(), input_tokens: z.number().int().optional(), threshold: z.number().optional(), similarity: z.number().optional()}); export const bifrostResponseExtraFields = z.object({request_type: z.string().optional(), provider: modelProvider.optional(), model_requested: z.string().optional(), model_deployment: z.string().optional(), latency: z.number().int().optional(), chunk_index: z.number().int().optional(), raw_request: z.object({}).optional(), raw_response: z.object({}).optional(), cache_debug: bifrostCacheDebug.optional()}); export const createApiV1ResponsesCompactResponse = z.object({id: z.string().optional(), object: z.string().optional(), model: z.string().optional(), created_at: z.number().int().optional(), output: z.array(z.object({id: z.string().optional(), type: z.enum(["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"]).optional(), status: z.enum(["in_progress", "completed", "incomplete", "interpreting", "failed"]).optional(), role: z.enum(["assistant", "user", "system", "developer"]).optional(), content: z.union([z.string(), z.array(z.object({type: z.enum(["input_text", "input_image", "input_file", "input_audio", "output_text", "refusal", "reasoning_text"]), file_id: z.string().optional(), text: z.string().optional(), signature: z.string().optional(), image_url: z.string().optional(), detail: z.string().optional(), file_data: z.string().optional(), file_url: z.string().optional(), filename: z.string().optional(), file_type: z.string().optional(), input_audio: z.object({format: z.enum(["mp3", "wav"]), data: z.string()}).optional(), annotations: z.array(z.object({type: z.enum(["file_citation", "url_citation", "container_file_citation", "file_path"]).optional(), index: z.number().int().optional(), file_id: z.string().optional(), text: z.string().optional(), start_index: z.number().int().optional(), end_index: z.number().int().optional(), filename: z.string().optional(), title: z.string().optional(), url: z.string().optional(), container_id: z.string().optional()})).optional(), logprobs: z.array(z.object({bytes: z.array(z.number().int()).optional(), logprob: z.number().optional(), token: z.string().optional(), top_logprobs: z.array(z.object({bytes: z.array(z.number().int()).optional(), logprob: z.number().optional(), token: z.string().optional()})).optional()})).optional(), refusal: z.string().optional(), cache_control: cacheControl.optional()}))]).optional(), call_id: z.string().optional(), name: z.string().optional(), arguments: z.string().optional(), output: z.union([z.string(), z.array(z.object({type: z.enum(["input_text", "input_image", "input_file", "input_audio", "output_text", "refusal", "reasoning_text"]), file_id: z.string().optional(), text: z.string().optional(), signature: z.string().optional(), image_url: z.string().optional(), detail: z.string().optional(), file_data: z.string().optional(), file_url: z.string().optional(), filename: z.string().optional(), file_type: z.string().optional(), input_audio: z.object({format: z.enum(["mp3", "wav"]), data: z.string()}).optional(), annotations: z.array(z.object({type: z.enum(["file_citation", "url_citation", "container_file_citation", "file_path"]).optional(), index: z.number().int().optional(), file_id: z.string().optional(), text: z.string().optional(), start_index: z.number().int().optional(), end_index: z.number().int().optional(), filename: z.string().optional(), title: z.string().optional(), url: z.string().optional(), container_id: z.string().optional()})).optional(), logprobs: z.array(z.object({bytes: z.array(z.number().int()).optional(), logprob: z.number().optional(), token: z.string().optional(), top_logprobs: z.array(z.object({bytes: z.array(z.number().int()).optional(), logprob: z.number().optional(), token: z.string().optional()})).optional()})).optional(), refusal: z.string().optional(), cache_control: cacheControl.optional()})), z.object({type: z.literal("computer_screenshot").optional(), file_id: z.string().optional(), image_url: z.string().optional()})]).optional(), action: z.object({}).optional(), error: z.string().optional(), queries: z.array(z.string()).optional(), results: z.array(z.object({})).optional(), summary: z.array(z.object({type: z.literal("summary_text"), text: z.string()})).optional(), encrypted_content: z.string().optional()})).optional(), usage: z.object({input_tokens: z.number().int().optional(), input_tokens_details: z.object({text_tokens: z.number().int().optional(), audio_tokens: z.number().int().optional(), image_tokens: z.number().int().optional(), cached_read_tokens: z.number().int().optional(), cached_write_tokens: z.number().int().optional()}).optional(), output_tokens: z.number().int().optional(), output_tokens_details: z.object({text_tokens: z.number().int().optional(), accepted_prediction_tokens: z.number().int().optional(), audio_tokens: z.number().int().optional(), reasoning_tokens: z.number().int().optional(), rejected_prediction_tokens: z.number().int().optional(), citation_tokens: z.number().int().optional(), num_search_queries: z.number().int().optional()}).optional(), total_tokens: z.number().int().optional(), cost: bifrostCost.optional()}).optional(), extra_fields: bifrostResponseExtraFields.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 }; /** * Compact context * * POST /v1/responses/compact * * Also accepts auth: BasicAuth, VirtualKeyAuth, ApiKeyAuth */ export const createApiV1ResponsesCompact = async (args: CreateApiV1ResponsesCompactArgs, options?: CreateApiV1ResponsesCompactOptions) => { 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 (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/responses/compact${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(createApiV1ResponsesCompactResponse, await res.json()) };