import { Context, Effect, Layer, Redacted, Stream } from "effect" import { HttpClient, HttpClientRequest } from "effect/http" import * as AiError from "@effect-uai/core/AiError" import type { AudioBlob, AudioChunk, AudioFormat } from "@effect-uai/core/Audio" import * as Capabilities from "@effect-uai/core/Capabilities" import { type CommonStreamSynthesizeRequest, type CommonSynthesizeRequest, SpeechSynthesizer, type SpeechSynthesizerService, } from "@effect-uai/core/SpeechSynthesizer" import { containerToResponseFormat, httpStatusError, type OpenAIResponseFormat, realizedFormat, transportFailure, } from "./codec.js" import type { OpenAITtsModel, OpenAIVoiceId } from "./models.js" import { type OpenAiRegion, resolveHost } from "./region.js" // --------------------------------------------------------------------------- // Public types // --------------------------------------------------------------------------- /** * OpenAI-typed synthesize request. `model` narrows to `OpenAITtsModel`; * `voiceId` narrows to the stock-only `OpenAIVoiceId` union (no * `(string & {})` escape — OpenAI has no custom-voice path). * * `instructions` is honoured only by `gpt-4o-mini-tts`; it's silently * ignored on `tts-1` / `tts-1-hd`. */ export type OpenAISynthesizeRequest = Omit & { readonly model: OpenAITtsModel readonly voiceId: OpenAIVoiceId readonly instructions?: string } export type OpenAISynthesizerService = { readonly synthesize: ( request: OpenAISynthesizeRequest, ) => Effect.Effect readonly streamSynthesis: ( request: OpenAISynthesizeRequest, ) => Stream.Stream readonly streamSynthesisFrom: ( textIn: Stream.Stream, request: CommonStreamSynthesizeRequest, ) => Stream.Stream readonly synthesizeDialogue: SpeechSynthesizerService["synthesizeDialogue"] readonly streamSynthesizeDialogue: SpeechSynthesizerService["streamSynthesizeDialogue"] } export class OpenAISynthesizer extends Context.Service< OpenAISynthesizer, OpenAISynthesizerService >()("@betalyra/effect-uai/providers/openai/OpenAISynthesizer") {} export type Config = { readonly apiKey: Redacted.Redacted readonly baseUrl?: string readonly region?: OpenAiRegion } // --------------------------------------------------------------------------- // Codec — request → JSON body // --------------------------------------------------------------------------- const defaultFormat: AudioFormat = { container: "mp3", encoding: "mp3", sampleRate: 24000, } type WireBody = { readonly model: string readonly input: string readonly voice: string readonly response_format: OpenAIResponseFormat readonly speed?: number readonly instructions?: string } const buildBody = ( request: OpenAISynthesizeRequest, ): Effect.Effect<{ readonly body: WireBody; readonly format: AudioFormat }, AiError.AiError> => Effect.gen(function* () { // OpenAI TTS has no phoneme field. Pronunciations are load-bearing // (bucket 1), so reject rather than silently mispronounce. if (request.pronunciations !== undefined && request.pronunciations.length > 0) { return yield* Effect.fail( new AiError.Unsupported({ provider: "openai", capability: "pronunciations", reason: "OpenAI TTS has no phoneme/pronunciation field. Use a provider with a phoneme path (Inworld, Google) for pronunciation overrides.", }), ) } // `/audio/speech` has no language parameter (it auto-detects); bucket 2. yield* Capabilities.warnDroppedWhen(request.languageCode, { provider: "openai", capability: "languageCode", field: "languageCode", reason: "OpenAI /audio/speech has no language parameter; it auto-detects from the input text.", }) const responseFormat = yield* containerToResponseFormat( (request.outputFormat ?? defaultFormat).container, ) return { body: { model: request.model, input: request.text, voice: request.voiceId, response_format: responseFormat, ...(request.speed !== undefined && { speed: request.speed }), ...(request.instructions !== undefined && { instructions: request.instructions }), } satisfies WireBody, format: realizedFormat(responseFormat), } }) // --------------------------------------------------------------------------- // HTTP plumbing // --------------------------------------------------------------------------- const buildHttpRequest = (cfg: Config, body: WireBody) => HttpClientRequest.post(`${resolveHost(cfg)}/audio/speech`).pipe( HttpClientRequest.bearerToken(cfg.apiKey), HttpClientRequest.bodyJsonUnsafe(body), ) const synthesizeImpl = (cfg: Config) => ( request: OpenAISynthesizeRequest, ): Effect.Effect => Effect.gen(function* () { const client = yield* HttpClient.HttpClient const { body, format } = yield* buildBody(request) const response = yield* client .execute(buildHttpRequest(cfg, body)) .pipe(Effect.mapError(transportFailure)) if (response.status >= 400) { const text = yield* response.text.pipe(Effect.orElseSucceed(() => "")) return yield* Effect.fail(httpStatusError(response.status, text)) } const bytes = yield* response.arrayBuffer.pipe(Effect.mapError(transportFailure)) return { format, bytes: new Uint8Array(bytes) } }) const streamSynthesisImpl = (cfg: Config) => ( request: OpenAISynthesizeRequest, ): Stream.Stream => Stream.unwrap( Effect.gen(function* () { const client = yield* HttpClient.HttpClient const { body } = yield* buildBody(request) const response = yield* client .execute(buildHttpRequest(cfg, body)) .pipe(Effect.mapError(transportFailure)) if (response.status >= 400) { const text = yield* response.text.pipe(Effect.orElseSucceed(() => "")) return Stream.fail(httpStatusError(response.status, text)) } return response.stream.pipe( Stream.mapError(transportFailure), Stream.map((bytes): AudioChunk => ({ bytes })), ) }), ) // --------------------------------------------------------------------------- // streamSynthesisFrom — Unsupported (OpenAI has no incremental text-in) // --------------------------------------------------------------------------- /** * OpenAI has no incremental-text-in TTS endpoint at the wire level. * The provider Layer also does NOT register the `TtsIncrementalText` * capability marker, so callers using * `SpeechSynthesizer.streamSynthesisFrom` against only OpenAI's Layer * get a compile-time error before this runtime fallback ever fires. */ const streamSynthesisFromUnsupported = ( _textIn: Stream.Stream, _request: CommonStreamSynthesizeRequest, ): Stream.Stream => { const fail: Stream.Stream = Stream.fail( new AiError.Unsupported({ provider: "openai", capability: "streamSynthesisFrom", reason: "OpenAI does not offer an incremental-text-in TTS endpoint. Use `synthesize` (full text in, full audio out) or `streamSynthesis` (full text in, chunked audio out).", }), ) return fail } const synthesizeDialogueUnsupported: SpeechSynthesizerService["synthesizeDialogue"] = () => Effect.fail( new AiError.Unsupported({ provider: "openai", capability: "synthesizeDialogue", reason: "OpenAI TTS has no multi-speaker endpoint.", }), ) const streamSynthesizeDialogueUnsupported: SpeechSynthesizerService["streamSynthesizeDialogue"] = () => Stream.fail( new AiError.Unsupported({ provider: "openai", capability: "streamSynthesizeDialogue", reason: "OpenAI TTS has no multi-speaker endpoint.", }), ) // --------------------------------------------------------------------------- // Constructors // --------------------------------------------------------------------------- export const make = ( cfg: Config, ): Effect.Effect => Effect.map(HttpClient.HttpClient, (client) => ({ synthesize: (request) => synthesizeImpl(cfg)(request).pipe(Effect.provideService(HttpClient.HttpClient, client)), streamSynthesis: (request) => streamSynthesisImpl(cfg)(request).pipe(Stream.provideService(HttpClient.HttpClient, client)), streamSynthesisFrom: streamSynthesisFromUnsupported, synthesizeDialogue: synthesizeDialogueUnsupported, streamSynthesizeDialogue: streamSynthesizeDialogueUnsupported, })) /** * Layer that registers both `OpenAISynthesizer` and the generic * `SpeechSynthesizer` tag. * * Does NOT register the `TtsIncrementalText` capability marker — * OpenAI has no incremental-text-in TTS at the wire level. Code calling * `SpeechSynthesizer.streamSynthesisFrom` will fail to typecheck * against this Layer alone, which is the intended UX. */ export const layer = ( cfg: Config, ): Layer.Layer => Layer.merge( Layer.effect(OpenAISynthesizer, make(cfg)), Layer.effect( SpeechSynthesizer, Effect.map(make(cfg), (s): SpeechSynthesizerService => ({ synthesize: (req: CommonSynthesizeRequest) => s.synthesize(req as OpenAISynthesizeRequest), streamSynthesis: (req: CommonSynthesizeRequest) => s.streamSynthesis(req as OpenAISynthesizeRequest), streamSynthesisFrom: s.streamSynthesisFrom, synthesizeDialogue: s.synthesizeDialogue, streamSynthesizeDialogue: s.streamSynthesizeDialogue, })), ), )