{"version":3,"file":"OpenAITranscriber.mjs","names":[],"sources":["../src/OpenAITranscriber.ts"],"sourcesContent":["import { Context, Duration, Effect, Layer, Redacted, Schema, Stream } from \"effect\"\nimport { HttpClient, HttpClientRequest } from \"effect/http\"\nimport * as AiError from \"@effect-uai/core/AiError\"\nimport * as Capabilities from \"@effect-uai/core/Capabilities\"\nimport type { TranscriptEvent, TranscriptResult, WordTimestamp } from \"@effect-uai/core/Transcript\"\nimport {\n  type CommonStreamTranscribeRequest,\n  type CommonTranscribeRequest,\n  Transcriber,\n  type TranscriberService,\n} from \"@effect-uai/core/Transcriber\"\nimport {\n  audioToBlob,\n  bodyMultipart,\n  defaultFileName,\n  httpStatusError,\n  transportFailure,\n} from \"./codec.js\"\nimport type { OpenAITranscribeModel } from \"./models.js\"\nimport { type OpenAiRegion, resolveHost } from \"./region.js\"\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * OpenAI-typed transcribe request. `model` narrows to the typed\n * `OpenAITranscribeModel` union; `fileName` overrides the multipart\n * upload's `filename` (OpenAI uses the extension to detect format).\n *\n * Field caveats:\n * - `diarization` is narrowed off — OpenAI's transcription endpoint\n *   doesn't offer it. On the generic surface it's GATE-ONLY (lax-silent\n *   absence; no marker shipped).\n * - `wordTimestamps` stays — it works on `whisper-1`. We don't keep a\n *   per-model table (capabilities §2.3): a non-whisper-1 model rejects\n *   `verbose_json` at the wire, surfacing as the generic 400\n *   `AiError.InvalidRequest`. We don't reclassify it to `Unsupported`\n *   (would need fragile body inspection — deliberately skipped).\n */\nexport type OpenAITranscribeRequest = Omit<CommonTranscribeRequest, \"model\" | \"diarization\"> & {\n  readonly model: OpenAITranscribeModel\n  readonly temperature?: number\n  readonly fileName?: string\n}\n\nexport type OpenAITranscriberService = {\n  readonly transcribe: (\n    request: OpenAITranscribeRequest,\n  ) => Effect.Effect<TranscriptResult, AiError.AiError>\n  readonly streamTranscriptionFrom: <E, R>(\n    audioIn: Stream.Stream<Uint8Array, E, R>,\n    request: CommonStreamTranscribeRequest,\n  ) => Stream.Stream<TranscriptEvent, AiError.AiError | E, R>\n}\n\nexport class OpenAITranscriber extends Context.Service<\n  OpenAITranscriber,\n  OpenAITranscriberService\n>()(\"@betalyra/effect-uai/providers/openai/OpenAITranscriber\") {}\n\nexport type Config = {\n  readonly apiKey: Redacted.Redacted\n  readonly baseUrl?: string\n  readonly region?: OpenAiRegion\n}\n\n// ---------------------------------------------------------------------------\n// Codec — request → FormData\n// ---------------------------------------------------------------------------\n\nconst wantsVerboseJson = (request: OpenAITranscribeRequest): boolean =>\n  request.wordTimestamps === true\n\nconst buildFormData = (\n  request: OpenAITranscribeRequest,\n): Effect.Effect<FormData, AiError.AiError> =>\n  Effect.gen(function* () {\n    const blob = yield* audioToBlob(request.audio)\n    const fd = new FormData()\n    fd.set(\"file\", blob, request.fileName ?? defaultFileName(blob.type))\n    fd.set(\"model\", request.model)\n    fd.set(\"response_format\", wantsVerboseJson(request) ? \"verbose_json\" : \"json\")\n    if (wantsVerboseJson(request)) fd.set(\"timestamp_granularities[]\", \"word\")\n    if (request.language !== undefined) fd.set(\"language\", request.language)\n    if (request.prompt !== undefined) fd.set(\"prompt\", request.prompt)\n    // OpenAI has no structured keyterm field — the prose `prompt` is its\n    // only biasing surface. Don't stuff terms into it (prompt-building);\n    // warn instead.\n    yield* Capabilities.warnDroppedWhen(request.biasingTerms, {\n      provider: \"openai\",\n      capability: \"biasing\",\n      field: \"biasingTerms\",\n      reason:\n        \"OpenAI transcription has no keyterm field. Use `prompt` for light vocab hints, or a provider with structured biasing (Deepgram, ElevenLabs, Google).\",\n    })\n    if (request.temperature !== undefined) fd.set(\"temperature\", String(request.temperature))\n    return fd\n  })\n\n// ---------------------------------------------------------------------------\n// Codec — response → TranscriptResult\n// ---------------------------------------------------------------------------\n\nconst WireWord = Schema.Struct({\n  word: Schema.String,\n  start: Schema.Number,\n  end: Schema.Number,\n})\n\nconst WireVerboseResponse = Schema.Struct({\n  text: Schema.String,\n  language: Schema.optional(Schema.String),\n  duration: Schema.optional(Schema.Number),\n  words: Schema.optional(Schema.Array(WireWord)),\n})\n\nconst WireSimpleResponse = Schema.Struct({ text: Schema.String })\n\nconst decodeVerbose = Schema.decodeUnknownEffect(WireVerboseResponse)\nconst decodeSimple = Schema.decodeUnknownEffect(WireSimpleResponse)\n\nconst wireWordToCommon = (w: typeof WireWord.Type): WordTimestamp => ({\n  text: w.word,\n  startSeconds: w.start,\n  endSeconds: w.end,\n})\n\nconst verboseToResult = (\n  raw: unknown,\n  decoded: typeof WireVerboseResponse.Type,\n): TranscriptResult => ({\n  text: decoded.text,\n  ...(decoded.language !== undefined && { languageCode: decoded.language }),\n  ...(decoded.duration !== undefined && { duration: Duration.seconds(decoded.duration) }),\n  ...(decoded.words !== undefined && { words: decoded.words.map(wireWordToCommon) }),\n  raw,\n})\n\nconst decodeResponse = (\n  request: OpenAITranscribeRequest,\n  raw: unknown,\n): Effect.Effect<TranscriptResult, AiError.AiError> =>\n  wantsVerboseJson(request)\n    ? decodeVerbose(raw).pipe(\n        Effect.mapError(transportFailure),\n        Effect.map((decoded) => verboseToResult(raw, decoded)),\n      )\n    : decodeSimple(raw).pipe(\n        Effect.mapError(transportFailure),\n        Effect.map((decoded): TranscriptResult => ({ text: decoded.text, raw })),\n      )\n\n// ---------------------------------------------------------------------------\n// HTTP plumbing\n// ---------------------------------------------------------------------------\n\n/** Exported for reuse by `OpenAIRealtimeTranscriber` (same sync path). */\nexport const transcribeImpl =\n  (cfg: Config) =>\n  (\n    request: OpenAITranscribeRequest,\n  ): Effect.Effect<TranscriptResult, AiError.AiError, HttpClient.HttpClient> =>\n    Effect.gen(function* () {\n      const client = yield* HttpClient.HttpClient\n      const withBody = yield* Effect.flatMap(buildFormData(request), bodyMultipart)\n      const httpRequest = HttpClientRequest.post(`${resolveHost(cfg)}/audio/transcriptions`).pipe(\n        HttpClientRequest.bearerToken(cfg.apiKey),\n        withBody,\n      )\n      const response = yield* client.execute(httpRequest).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 json = yield* response.json.pipe(Effect.mapError(transportFailure))\n      return yield* decodeResponse(request, json)\n    })\n\n// ---------------------------------------------------------------------------\n// Service implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Sync-only Layer's streaming impl. For live transcription, import the\n * `OpenAIRealtimeTranscriber` subpath instead — it registers `SttStreaming`\n * and wires the Realtime WS endpoint. Provided here so the sync Layer can\n * still satisfy the `TranscriberService` shape; the marker absence makes\n * `Transcriber.streamTranscriptionFrom` calls a compile-time error against\n * this Layer alone.\n */\nconst streamUnsupported = <E, R>(\n  _audioIn: Stream.Stream<Uint8Array, E, R>,\n  _request: CommonStreamTranscribeRequest,\n): Stream.Stream<TranscriptEvent, AiError.AiError | E, R> => {\n  const fail: Stream.Stream<TranscriptEvent, AiError.AiError | E, R> = Stream.fail(\n    new AiError.Unsupported({\n      provider: \"openai\",\n      capability: \"streamTranscriptionFrom\",\n      reason:\n        \"OpenAI Realtime WebSocket streaming is not yet wired in this package. Use `transcribe` for sync transcription.\",\n    }),\n  )\n  return fail\n}\n\n// ---------------------------------------------------------------------------\n// Constructors\n// ---------------------------------------------------------------------------\n\nexport const make = (\n  cfg: Config,\n): Effect.Effect<OpenAITranscriberService, never, HttpClient.HttpClient> =>\n  Effect.map(HttpClient.HttpClient, (client) => ({\n    transcribe: (request) =>\n      transcribeImpl(cfg)(request).pipe(Effect.provideService(HttpClient.HttpClient, client)),\n    streamTranscriptionFrom: streamUnsupported,\n  }))\n\n/**\n * Sync-only Layer. Registers `OpenAITranscriber` + the generic `Transcriber`\n * tag. Does **not** register the `SttStreaming` capability marker — for\n * live transcription use `@effect-uai/openai/OpenAIRealtimeTranscriber`,\n * which uses the Realtime WS endpoint and the `ws` peer dep.\n */\nexport const layer = (\n  cfg: Config,\n): Layer.Layer<OpenAITranscriber | Transcriber, never, HttpClient.HttpClient> =>\n  Layer.merge(\n    Layer.effect(OpenAITranscriber, make(cfg)),\n    Layer.effect(\n      Transcriber,\n      Effect.map(make(cfg), (s): TranscriberService => ({\n        transcribe: (req: CommonTranscribeRequest) => s.transcribe(req as OpenAITranscribeRequest),\n        streamTranscriptionFrom: s.streamTranscriptionFrom,\n      })),\n    ),\n  )\n"],"mappings":";;;;;;;;;;;;;;;AAwDA,IAAa,oBAAb,cAAuC,QAAQ,QAG7C,CAAC,CAAC,yDAAyD,CAAC,CAAC,CAAC;AAYhE,MAAM,oBAAoB,YACxB,QAAQ,mBAAmB;AAE7B,MAAM,iBACJ,YAEA,OAAO,IAAI,aAAa;CACtB,MAAM,OAAO,OAAO,YAAY,QAAQ,KAAK;CAC7C,MAAM,KAAK,IAAI,SAAS;CACxB,GAAG,IAAI,QAAQ,MAAM,QAAQ,YAAY,gBAAgB,KAAK,IAAI,CAAC;CACnE,GAAG,IAAI,SAAS,QAAQ,KAAK;CAC7B,GAAG,IAAI,mBAAmB,iBAAiB,OAAO,IAAI,iBAAiB,MAAM;CAC7E,IAAI,iBAAiB,OAAO,GAAG,GAAG,IAAI,6BAA6B,MAAM;CACzE,IAAI,QAAQ,aAAa,KAAA,GAAW,GAAG,IAAI,YAAY,QAAQ,QAAQ;CACvE,IAAI,QAAQ,WAAW,KAAA,GAAW,GAAG,IAAI,UAAU,QAAQ,MAAM;CAIjE,OAAO,aAAa,gBAAgB,QAAQ,cAAc;EACxD,UAAU;EACV,YAAY;EACZ,OAAO;EACP,QACE;CACJ,CAAC;CACD,IAAI,QAAQ,gBAAgB,KAAA,GAAW,GAAG,IAAI,eAAe,OAAO,QAAQ,WAAW,CAAC;CACxF,OAAO;AACT,CAAC;AAMH,MAAM,WAAW,OAAO,OAAO;CAC7B,MAAM,OAAO;CACb,OAAO,OAAO;CACd,KAAK,OAAO;AACd,CAAC;AAED,MAAM,sBAAsB,OAAO,OAAO;CACxC,MAAM,OAAO;CACb,UAA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