{"version":3,"file":"OpenAISynthesizer.mjs","names":[],"sources":["../src/OpenAISynthesizer.ts"],"sourcesContent":["import { Context, Effect, Layer, Redacted, Stream } from \"effect\"\nimport { HttpClient, HttpClientRequest } from \"effect/http\"\nimport * as AiError from \"@effect-uai/core/AiError\"\nimport type { AudioBlob, AudioChunk, AudioFormat } from \"@effect-uai/core/Audio\"\nimport * as Capabilities from \"@effect-uai/core/Capabilities\"\nimport {\n  type CommonStreamSynthesizeRequest,\n  type CommonSynthesizeRequest,\n  SpeechSynthesizer,\n  type SpeechSynthesizerService,\n} from \"@effect-uai/core/SpeechSynthesizer\"\nimport {\n  containerToResponseFormat,\n  httpStatusError,\n  type OpenAIResponseFormat,\n  realizedFormat,\n  transportFailure,\n} from \"./codec.js\"\nimport type { OpenAITtsModel, OpenAIVoiceId } from \"./models.js\"\nimport { type OpenAiRegion, resolveHost } from \"./region.js\"\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * OpenAI-typed synthesize request. `model` narrows to `OpenAITtsModel`;\n * `voiceId` narrows to the stock-only `OpenAIVoiceId` union (no\n * `(string & {})` escape — OpenAI has no custom-voice path).\n *\n * `instructions` is honoured only by `gpt-4o-mini-tts`; it's silently\n * ignored on `tts-1` / `tts-1-hd`.\n */\nexport type OpenAISynthesizeRequest = Omit<CommonSynthesizeRequest, \"model\" | \"voiceId\"> & {\n  readonly model: OpenAITtsModel\n  readonly voiceId: OpenAIVoiceId\n  readonly instructions?: string\n}\n\nexport type OpenAISynthesizerService = {\n  readonly synthesize: (\n    request: OpenAISynthesizeRequest,\n  ) => Effect.Effect<AudioBlob, AiError.AiError>\n  readonly streamSynthesis: (\n    request: OpenAISynthesizeRequest,\n  ) => Stream.Stream<AudioChunk, AiError.AiError>\n  readonly streamSynthesisFrom: <E, R>(\n    textIn: Stream.Stream<string, E, R>,\n    request: CommonStreamSynthesizeRequest,\n  ) => Stream.Stream<AudioChunk, AiError.AiError | E, R>\n  readonly synthesizeDialogue: SpeechSynthesizerService[\"synthesizeDialogue\"]\n  readonly streamSynthesizeDialogue: SpeechSynthesizerService[\"streamSynthesizeDialogue\"]\n}\n\nexport class OpenAISynthesizer extends Context.Service<\n  OpenAISynthesizer,\n  OpenAISynthesizerService\n>()(\"@betalyra/effect-uai/providers/openai/OpenAISynthesizer\") {}\n\nexport type Config = {\n  readonly apiKey: Redacted.Redacted\n  readonly baseUrl?: string\n  readonly region?: OpenAiRegion\n}\n\n// ---------------------------------------------------------------------------\n// Codec — request → JSON body\n// ---------------------------------------------------------------------------\n\nconst defaultFormat: AudioFormat = {\n  container: \"mp3\",\n  encoding: \"mp3\",\n  sampleRate: 24000,\n}\n\ntype WireBody = {\n  readonly model: string\n  readonly input: string\n  readonly voice: string\n  readonly response_format: OpenAIResponseFormat\n  readonly speed?: number\n  readonly instructions?: string\n}\n\nconst buildBody = (\n  request: OpenAISynthesizeRequest,\n): Effect.Effect<{ readonly body: WireBody; readonly format: AudioFormat }, AiError.AiError> =>\n  Effect.gen(function* () {\n    // OpenAI TTS has no phoneme field. Pronunciations are load-bearing\n    // (bucket 1), so reject rather than silently mispronounce.\n    if (request.pronunciations !== undefined && request.pronunciations.length > 0) {\n      return yield* Effect.fail(\n        new AiError.Unsupported({\n          provider: \"openai\",\n          capability: \"pronunciations\",\n          reason:\n            \"OpenAI TTS has no phoneme/pronunciation field. Use a provider with a phoneme path (Inworld, Google) for pronunciation overrides.\",\n        }),\n      )\n    }\n    // `/audio/speech` has no language parameter (it auto-detects); bucket 2.\n    yield* Capabilities.warnDroppedWhen(request.languageCode, {\n      provider: \"openai\",\n      capability: \"languageCode\",\n      field: \"languageCode\",\n      reason:\n        \"OpenAI /audio/speech has no language parameter; it auto-detects from the input text.\",\n    })\n    const responseFormat = yield* containerToResponseFormat(\n      (request.outputFormat ?? defaultFormat).container,\n    )\n    return {\n      body: {\n        model: request.model,\n        input: request.text,\n        voice: request.voiceId,\n        response_format: responseFormat,\n        ...(request.speed !== undefined && { speed: request.speed }),\n        ...(request.instructions !== undefined && { instructions: request.instructions }),\n      } satisfies WireBody,\n      format: realizedFormat(responseFormat),\n    }\n  })\n\n// ---------------------------------------------------------------------------\n// HTTP plumbing\n// ---------------------------------------------------------------------------\n\nconst buildHttpRequest = (cfg: Config, body: WireBody) =>\n  HttpClientRequest.post(`${resolveHost(cfg)}/audio/speech`).pipe(\n    HttpClientRequest.bearerToken(cfg.apiKey),\n    HttpClientRequest.bodyJsonUnsafe(body),\n  )\n\nconst synthesizeImpl =\n  (cfg: Config) =>\n  (\n    request: OpenAISynthesizeRequest,\n  ): Effect.Effect<AudioBlob, AiError.AiError, HttpClient.HttpClient> =>\n    Effect.gen(function* () {\n      const client = yield* HttpClient.HttpClient\n      const { body, format } = yield* buildBody(request)\n      const response = yield* client\n        .execute(buildHttpRequest(cfg, body))\n        .pipe(Effect.mapError(transportFailure))\n      if (response.status >= 400) {\n        const text = yield* response.text.pipe(Effect.orElseSucceed(() => \"\"))\n        return yield* Effect.fail(httpStatusError(response.status, text))\n      }\n      const bytes = yield* response.arrayBuffer.pipe(Effect.mapError(transportFailure))\n      return { format, bytes: new Uint8Array(bytes) }\n    })\n\nconst streamSynthesisImpl =\n  (cfg: Config) =>\n  (\n    request: OpenAISynthesizeRequest,\n  ): Stream.Stream<AudioChunk, AiError.AiError, HttpClient.HttpClient> =>\n    Stream.unwrap(\n      Effect.gen(function* () {\n        const client = yield* HttpClient.HttpClient\n        const { body } = yield* buildBody(request)\n        const response = yield* client\n          .execute(buildHttpRequest(cfg, body))\n          .pipe(Effect.mapError(transportFailure))\n        if (response.status >= 400) {\n          const text = yield* response.text.pipe(Effect.orElseSucceed(() => \"\"))\n          return Stream.fail(httpStatusError(response.status, text))\n        }\n        return response.stream.pipe(\n          Stream.mapError(transportFailure),\n          Stream.map((bytes): AudioChunk => ({ bytes })),\n        )\n      }),\n    )\n\n// ---------------------------------------------------------------------------\n// streamSynthesisFrom — Unsupported (OpenAI has no incremental text-in)\n// ---------------------------------------------------------------------------\n\n/**\n * OpenAI has no incremental-text-in TTS endpoint at the wire level.\n * The provider Layer also does NOT register the `TtsIncrementalText`\n * capability marker, so callers using\n * `SpeechSynthesizer.streamSynthesisFrom` against only OpenAI's Layer\n * get a compile-time error before this runtime fallback ever fires.\n */\nconst streamSynthesisFromUnsupported = <E, R>(\n  _textIn: Stream.Stream<string, E, R>,\n  _request: CommonStreamSynthesizeRequest,\n): Stream.Stream<AudioChunk, AiError.AiError | E, R> => {\n  const fail: Stream.Stream<AudioChunk, AiError.AiError | E, R> = Stream.fail(\n    new AiError.Unsupported({\n      provider: \"openai\",\n      capability: \"streamSynthesisFrom\",\n      reason:\n        \"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).\",\n    }),\n  )\n  return fail\n}\n\nconst synthesizeDialogueUnsupported: SpeechSynthesizerService[\"synthesizeDialogue\"] = () =>\n  Effect.fail(\n    new AiError.Unsupported({\n      provider: \"openai\",\n      capability: \"synthesizeDialogue\",\n      reason: \"OpenAI TTS has no multi-speaker endpoint.\",\n    }),\n  )\n\nconst streamSynthesizeDialogueUnsupported: SpeechSynthesizerService[\"streamSynthesizeDialogue\"] =\n  () =>\n    Stream.fail(\n      new AiError.Unsupported({\n        provider: \"openai\",\n        capability: \"streamSynthesizeDialogue\",\n        reason: \"OpenAI TTS has no multi-speaker endpoint.\",\n      }),\n    )\n\n// ---------------------------------------------------------------------------\n// Constructors\n// ---------------------------------------------------------------------------\n\nexport const make = (\n  cfg: Config,\n): Effect.Effect<OpenAISynthesizerService, never, HttpClient.HttpClient> =>\n  Effect.map(HttpClient.HttpClient, (client) => ({\n    synthesize: (request) =>\n      synthesizeImpl(cfg)(request).pipe(Effect.provideService(HttpClient.HttpClient, client)),\n    streamSynthesis: (request) =>\n      streamSynthesisImpl(cfg)(request).pipe(Stream.provideService(HttpClient.HttpClient, client)),\n    streamSynthesisFrom: streamSynthesisFromUnsupported,\n    synthesizeDialogue: synthesizeDialogueUnsupported,\n    streamSynthesizeDialogue: streamSynthesizeDialogueUnsupported,\n  }))\n\n/**\n * Layer that registers both `OpenAISynthesizer` and the generic\n * `SpeechSynthesizer` tag.\n *\n * Does NOT register the `TtsIncrementalText` capability marker —\n * OpenAI has no incremental-text-in TTS at the wire level. Code calling\n * `SpeechSynthesizer.streamSynthesisFrom` will fail to typecheck\n * against this Layer alone, which is the intended UX.\n */\nexport const layer = (\n  cfg: Config,\n): Layer.Layer<OpenAISynthesizer | SpeechSynthesizer, never, HttpClient.HttpClient> =>\n  Layer.merge(\n    Layer.effect(OpenAISynthesizer, make(cfg)),\n    Layer.effect(\n      SpeechSynthesizer,\n      Effect.map(make(cfg), (s): SpeechSynthesizerService => ({\n        synthesize: (req: CommonSynthesizeRequest) => s.synthesize(req as OpenAISynthesizeRequest),\n        streamSynthesis: (req: CommonSynthesizeRequest) =>\n          s.streamSynthesis(req as OpenAISynthesizeRequest),\n        streamSynthesisFrom: s.streamSynthesisFrom,\n        synthesizeDialogue: s.synthesizeDialogue,\n        streamSynthesizeDialogue: s.streamSynthesizeDialogue,\n      })),\n    ),\n  )\n"],"mappings":";;;;;;;;;;;;;;AAsDA,IAAa,oBAAb,cAAuC,QAAQ,QAG7C,CAAC,CAAC,yDAAyD,CAAC,CAAC,CAAC;AAYhE,MAAM,gBAA6B;CACjC,WAAW;CACX,UAAU;CACV,YAAY;AACd;AAWA,MAAM,aACJ,YAEA,OAAO,IAAI,aAAa;CAGtB,IAAI,QAAQ,mBAAmB,KAAA,KAAa,QAAQ,eAAe,SAAS,GAC1E,OAAO,OAAO,OAAO,KACnB,IAAI,QAAQ,YAAY;EACtB,UAAU;EACV,YAAY;EACZ,QACE;CACJ,CAAC,CACH;CAGF,OAAO,aAAa,gBAAgB,QAAQ,cAAc;EACxD,UAAU;EACV,YAAY;EACZ,OAAO;EACP,QACE;CACJ,CAAC;CACD,MAAM,iBAAiB,OAAO,2BAC3B,QAAQ,gBAAgB,cAAA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