import {z} from 'zod' export type CacheControl = {type?: 'ephemeral' | undefined, ttl?: string | undefined}; export type CountTokensRequest = {model: string, messages: 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, 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, instructions?: string | undefined, text?: string | undefined}; export type CreateApiV1ResponsesInputTokensArgs = {body: CountTokensRequest}; export type CreateApiV1ResponsesInputTokensOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; 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 countTokensResponse = z.object({object: z.string().optional(), model: z.string().optional(), 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(), tokens: z.array(z.number().int()).optional(), token_strings: z.array(z.string()).optional(), output_tokens: z.number().int().optional(), total_tokens: z.number().int().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 }; /** * Count tokens * * POST /v1/responses/input_tokens * * Also accepts auth: BasicAuth, VirtualKeyAuth, ApiKeyAuth */ export const createApiV1ResponsesInputTokens = async (args: CreateApiV1ResponsesInputTokensArgs, options?: CreateApiV1ResponsesInputTokensOptions) => { 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/input_tokens${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(countTokensResponse, await res.json()) };