import {z} from 'zod' export type V1AudioConfigAudioEncoding = 'LINEAR16' | 'MP3' | 'OGG_OPUS' | 'ALAW' | 'MULAW' | 'FLAC' | 'PCM' | 'WAV'; export type Ttsv1AudioConfig = {audioEncoding?: V1AudioConfigAudioEncoding | undefined, bitRate?: number | undefined, sampleRateHertz?: number | undefined, speakingRate?: number | undefined}; export type Ttsv1SynthesisContext = {previousRequests?: (Array<{text?: string | undefined}>) | undefined}; export type Ttsv1SynthesizeSpeechStreamRequest = {text: string, voiceId: string, audioConfig?: Ttsv1AudioConfig | undefined, modelId: string, language?: string | undefined, deliveryMode?: ('DELIVERY_MODE_UNSPECIFIED' | 'STABLE' | 'BALANCED' | 'CREATIVE') | undefined, temperature?: number | undefined, timestampType?: ('TIMESTAMP_TYPE_UNSPECIFIED' | 'WORD' | 'CHARACTER') | undefined, applyTextNormalization?: ('APPLY_TEXT_NORMALIZATION_UNSPECIFIED' | 'ON' | 'OFF') | undefined, enhanceGeneration?: boolean | undefined, synthesisContext?: Ttsv1SynthesisContext | undefined}; export type CreateApiTtsV1VoiceStreamArgs = {body: Ttsv1SynthesizeSpeechStreamRequest}; export type CreateApiTtsV1VoiceStreamOptions = {baseUrl?: string | undefined, inworldBasic?: string | undefined, fetch?: typeof fetch | undefined}; export const ttsv1SynthesizeSpeechResponse = z.object({audioContent: z.string().optional(), usage: z.object({processedCharactersCount: z.number().int().optional(), modelId: z.string().optional()}).optional(), timestampInfo: z.object({wordAlignment: z.object({words: z.array(z.string()).optional(), wordStartTimeSeconds: z.array(z.number()).optional(), wordEndTimeSeconds: z.array(z.number()).optional(), phoneticDetails: z.array(z.object({wordIndex: z.number().int().optional(), phones: z.array(z.object({phoneSymbol: z.string().optional(), startTimeSeconds: z.number().optional(), durationSeconds: z.number().optional(), visemeSymbol: z.string().optional()})).optional(), isPartial: z.boolean().optional()})).optional()}).optional(), characterAlignment: z.object({characters: z.array(z.string()).optional(), characterStartTimeSeconds: z.array(z.number()).optional(), characterEndTimeSeconds: z.array(z.number()).optional()}).optional()}).optional()}); export const protobufAny = z.object({"@type": z.string().optional()}).and(z.record(z.string(), z.unknown())); export const rpcStatusStream = z.object({code: z.number().int().optional(), message: z.string().optional(), details: z.array(protobufAny).optional()}); export const createApiTtsV1VoiceStreamResponse = z.object({result: ttsv1SynthesizeSpeechResponse.optional(), error: rpcStatusStream.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 }; /** * Synthesize speech (stream) * * POST /tts/v1/voice:stream */ export const createApiTtsV1VoiceStream = async (args: CreateApiTtsV1VoiceStreamArgs, options?: CreateApiTtsV1VoiceStreamOptions) => { const {baseUrl = "https://api.inworld.ai", fetch: fetchFn = fetch, inworldBasic} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (inworldBasic !== undefined) headers.set("Authorization", inworldBasic) const url = `${baseUrl.replace(/\/+$/, '')}/tts/v1/voice:stream${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(createApiTtsV1VoiceStreamResponse, await res.json()) };