import {z} from 'zod' export type SpeechRequest = {model: string, input: string, fallbacks?: Array | undefined, stream_format?: 'sse' | undefined, voice: string | Array<{speaker: string, voice: string}>, instructions?: string | undefined, response_format?: ('mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm') | undefined, speed?: number | undefined, language_code?: string | undefined, pronunciation_dictionary_locators?: (Array<{pronunciation_dictionary_id: string, version_id?: string | undefined}>) | undefined, enable_logging?: boolean | undefined, optimize_streaming_latency?: boolean | undefined, with_timestamps?: boolean | undefined}; export type CreateApiV1AudioSpeechArgs = {body: SpeechRequest}; export type CreateApiV1AudioSpeechOptions = {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 speechResponse = z.object({audio: z.string().optional(), usage: z.object({input_tokens: z.number().int().optional(), output_tokens: z.number().int().optional(), total_tokens: z.number().int().optional()}).optional(), alignment: z.object({char_start_times_ms: z.array(z.number()).optional(), char_end_times_ms: z.array(z.number()).optional(), characters: z.array(z.string()).optional()}).optional(), normalized_alignment: z.object({char_start_times_ms: z.array(z.number()).optional(), char_end_times_ms: z.array(z.number()).optional(), characters: z.array(z.string()).optional()}).optional(), audio_base64: z.string().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 }; /** * Create speech * * POST /v1/audio/speech * * Also accepts auth: BasicAuth, VirtualKeyAuth, ApiKeyAuth */ export const createApiV1AudioSpeech = async (args: CreateApiV1AudioSpeechArgs, options?: CreateApiV1AudioSpeechOptions) => { 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/audio/speech${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(speechResponse, await res.json()) };