@effect-uai/google 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/Gemini.d.mts +6 -5
  2. package/dist/Gemini.d.mts.map +1 -1
  3. package/dist/Gemini.mjs +42 -22
  4. package/dist/Gemini.mjs.map +1 -1
  5. package/dist/GeminiEmbedding.d.mts.map +1 -1
  6. package/dist/GeminiEmbedding.mjs +2 -2
  7. package/dist/GeminiEmbedding.mjs.map +1 -1
  8. package/dist/GeminiSynthesizer.d.mts +38 -0
  9. package/dist/GeminiSynthesizer.d.mts.map +1 -0
  10. package/dist/GeminiSynthesizer.mjs +95 -0
  11. package/dist/GeminiSynthesizer.mjs.map +1 -0
  12. package/dist/GeminiSynthesizer.test.d.mts +1 -0
  13. package/dist/GeminiSynthesizer.test.mjs +84 -0
  14. package/dist/GeminiSynthesizer.test.mjs.map +1 -0
  15. package/dist/GeminiTranscriber.d.mts +42 -0
  16. package/dist/GeminiTranscriber.d.mts.map +1 -0
  17. package/dist/GeminiTranscriber.mjs +80 -0
  18. package/dist/GeminiTranscriber.mjs.map +1 -0
  19. package/dist/GeminiTranscriber.test.d.mts +1 -0
  20. package/dist/GeminiTranscriber.test.mjs +125 -0
  21. package/dist/GeminiTranscriber.test.mjs.map +1 -0
  22. package/dist/LyriaGenerator.d.mts +57 -0
  23. package/dist/LyriaGenerator.d.mts.map +1 -0
  24. package/dist/LyriaGenerator.mjs +202 -0
  25. package/dist/LyriaGenerator.mjs.map +1 -0
  26. package/dist/LyriaGenerator.test.d.mts +1 -0
  27. package/dist/LyriaGenerator.test.mjs +138 -0
  28. package/dist/LyriaGenerator.test.mjs.map +1 -0
  29. package/dist/{chunk-CfYAbeIz.mjs → chunk-uyGKjUfl.mjs} +2 -1
  30. package/dist/codec.d.mts +51 -6
  31. package/dist/codec.d.mts.map +1 -1
  32. package/dist/codec.mjs +151 -27
  33. package/dist/codec.mjs.map +1 -1
  34. package/dist/dist-DMsg8YLb.mjs +13782 -0
  35. package/dist/dist-DMsg8YLb.mjs.map +1 -0
  36. package/dist/geminiSpeechCodec.d.mts +37 -0
  37. package/dist/geminiSpeechCodec.d.mts.map +1 -0
  38. package/dist/geminiSpeechCodec.mjs +110 -0
  39. package/dist/geminiSpeechCodec.mjs.map +1 -0
  40. package/dist/geminiSpeechCodec.test.d.mts +1 -0
  41. package/dist/geminiSpeechCodec.test.mjs +78 -0
  42. package/dist/geminiSpeechCodec.test.mjs.map +1 -0
  43. package/dist/index.d.mts +5 -2
  44. package/dist/index.mjs +4 -1
  45. package/dist/magic-string.es-CaWgF-3p.mjs +1013 -0
  46. package/dist/magic-string.es-CaWgF-3p.mjs.map +1 -0
  47. package/dist/models.d.mts +35 -1
  48. package/dist/models.d.mts.map +1 -1
  49. package/package.json +14 -2
  50. package/src/Gemini.ts +53 -18
  51. package/src/GeminiEmbedding.ts +23 -5
  52. package/src/GeminiSynthesizer.test.ts +93 -0
  53. package/src/GeminiSynthesizer.ts +214 -0
  54. package/src/GeminiTranscriber.test.ts +136 -0
  55. package/src/GeminiTranscriber.ts +204 -0
  56. package/src/LyriaGenerator.test.ts +162 -0
  57. package/src/LyriaGenerator.ts +390 -0
  58. package/src/codec.ts +312 -36
  59. package/src/geminiSpeechCodec.test.ts +56 -0
  60. package/src/geminiSpeechCodec.ts +137 -0
  61. package/src/index.ts +3 -0
  62. package/src/models.ts +84 -0
@@ -0,0 +1,162 @@
1
+ import { Effect, Layer, Redacted, Stream } from "effect"
2
+ import { FetchHttpClient } from "effect/unstable/http"
3
+ import { describe, expect, expectTypeOf, it } from "vitest"
4
+ import type * as AiError from "@effect-uai/core/AiError"
5
+ import * as MusicGenerator from "@effect-uai/core/MusicGenerator"
6
+ import { promptsInput } from "@effect-uai/core/Music"
7
+ import * as LyriaGenerator from "./LyriaGenerator.js"
8
+
9
+ const cfg: LyriaGenerator.Config = { apiKey: Redacted.make("test-key") }
10
+ // FetchHttpClient is required for `make`, but these tests only exercise the
11
+ // compile-time gating and runtime Unsupported branches — no real HTTP is made.
12
+ const live = Layer.provide(LyriaGenerator.layer(cfg), FetchHttpClient.layer)
13
+
14
+ describe("buildPrompt", () => {
15
+ it("returns a plain string when prompts is a string", () => {
16
+ const out = LyriaGenerator.buildPrompt({
17
+ model: "lyria-3-clip-preview",
18
+ prompts: "upbeat indie pop",
19
+ })
20
+ expect(out).toBe("upbeat indie pop")
21
+ })
22
+
23
+ it("joins weighted prompts with weight annotations", () => {
24
+ const out = LyriaGenerator.buildPrompt({
25
+ model: "lyria-3-clip-preview",
26
+ prompts: [
27
+ { text: "minimal techno", weight: 1.0 },
28
+ { text: "1980s synthwave", weight: 0.3 },
29
+ ],
30
+ })
31
+ expect(out).toContain("minimal techno")
32
+ expect(out).toContain("1980s synthwave (weight 0.3)")
33
+ })
34
+
35
+ it("omits the weight annotation for weight === 1", () => {
36
+ const out = LyriaGenerator.buildPrompt({
37
+ model: "lyria-3-clip-preview",
38
+ prompts: [{ text: "ambient", weight: 1 }],
39
+ })
40
+ expect(out).toBe("ambient")
41
+ })
42
+
43
+ it("splices in bpm, scale, duration, and instrumental hints", () => {
44
+ const out = LyriaGenerator.buildPrompt({
45
+ model: "lyria-3-clip-preview",
46
+ prompts: "house",
47
+ bpm: 124,
48
+ scale: "C_MAJOR",
49
+ durationSeconds: 30,
50
+ instrumental: true,
51
+ })
52
+ expect(out).toContain("Instrumental only")
53
+ expect(out).toContain("BPM: 124")
54
+ expect(out).toContain("Key/scale: C_MAJOR")
55
+ expect(out).toContain("Target duration: 30s")
56
+ })
57
+
58
+ it("appends a lyrics block when lyrics is set and instrumental is not true", () => {
59
+ const out = LyriaGenerator.buildPrompt({
60
+ model: "lyria-3-clip-preview",
61
+ prompts: "indie rock",
62
+ lyrics: "[Verse]\nhello world",
63
+ })
64
+ expect(out).toContain("Lyrics:")
65
+ expect(out).toContain("[Verse]")
66
+ })
67
+
68
+ it("drops the lyrics block when instrumental is true", () => {
69
+ const out = LyriaGenerator.buildPrompt({
70
+ model: "lyria-3-clip-preview",
71
+ prompts: "indie rock",
72
+ lyrics: "[Verse]\nhello world",
73
+ instrumental: true,
74
+ })
75
+ expect(out).not.toContain("Lyrics:")
76
+ })
77
+ })
78
+
79
+ describe("containerToMimeType", () => {
80
+ it("maps mp3 and wav", async () => {
81
+ expect(await Effect.runPromise(LyriaGenerator.containerToMimeType("mp3"))).toBe("audio/mp3")
82
+ expect(await Effect.runPromise(LyriaGenerator.containerToMimeType("wav"))).toBe("audio/wav")
83
+ })
84
+
85
+ it("fails Unsupported for ogg / opus / flac / aac / webm / raw", async () => {
86
+ const exit = await Effect.runPromiseExit(LyriaGenerator.containerToMimeType("ogg"))
87
+ expect(exit._tag).toBe("Failure")
88
+ if (exit._tag === "Failure") {
89
+ expect(JSON.stringify(exit.cause)).toContain("Unsupported")
90
+ expect(JSON.stringify(exit.cause)).toContain("outputFormat")
91
+ }
92
+ })
93
+ })
94
+
95
+ describe("realizedFormat", () => {
96
+ it("reports 44.1 kHz stereo for both mp3 and wav", () => {
97
+ expect(LyriaGenerator.realizedFormat("audio/mp3")).toEqual({
98
+ container: "mp3",
99
+ encoding: "mp3",
100
+ sampleRate: 44100,
101
+ channels: 2,
102
+ })
103
+ expect(LyriaGenerator.realizedFormat("audio/wav")).toEqual({
104
+ container: "wav",
105
+ encoding: "pcm_s16le",
106
+ sampleRate: 44100,
107
+ channels: 2,
108
+ })
109
+ })
110
+ })
111
+
112
+ describe("LyriaGenerator capability guards (runtime)", () => {
113
+ it("streamGenerationFrom returns an Unsupported stream", async () => {
114
+ const program = LyriaGenerator.LyriaGenerator.use((s) =>
115
+ Stream.runDrain(
116
+ s.streamGenerationFrom(Stream.fromIterable([promptsInput([{ text: "x" }])]), {
117
+ model: "lyria-3-clip-preview",
118
+ prompts: "",
119
+ }),
120
+ ),
121
+ )
122
+ const exit = await Effect.runPromiseExit(program.pipe(Effect.provide(live)))
123
+ expect(exit._tag).toBe("Failure")
124
+ if (exit._tag === "Failure") {
125
+ expect(JSON.stringify(exit.cause)).toContain("Unsupported")
126
+ expect(JSON.stringify(exit.cause)).toContain("streamGenerationFrom")
127
+ }
128
+ })
129
+ })
130
+
131
+ describe("LyriaGenerator Layer (compile-time)", () => {
132
+ it("leaves `MusicInteractiveSession` unsatisfied when using `streamGenerationFrom` against this Layer", () => {
133
+ const inputs = Stream.fromIterable([promptsInput([{ text: "techno" }])])
134
+ const audio = inputs.pipe(
135
+ MusicGenerator.streamGenerationFrom({
136
+ model: "lyria-3-clip-preview",
137
+ prompts: "",
138
+ }),
139
+ )
140
+ const provided = Stream.runDrain(audio).pipe(Effect.provide(live))
141
+ expectTypeOf(provided).toEqualTypeOf<
142
+ Effect.Effect<void, AiError.AiError, MusicGenerator.MusicInteractiveSession>
143
+ >()
144
+ })
145
+
146
+ it("sync `generate` and chunked `streamGeneration` require no marker", () => {
147
+ const gen = MusicGenerator.generate({
148
+ model: "lyria-3-clip-preview",
149
+ prompts: "ambient",
150
+ }).pipe(Effect.provide(live))
151
+ expectTypeOf(gen).toEqualTypeOf<
152
+ Effect.Effect<import("@effect-uai/core/Music").MusicResult, AiError.AiError, never>
153
+ >()
154
+ const _stream = Stream.runCollect(
155
+ MusicGenerator.streamGeneration({
156
+ model: "lyria-3-clip-preview",
157
+ prompts: "ambient",
158
+ }),
159
+ ).pipe(Effect.provide(live))
160
+ expect(_stream).toBeDefined()
161
+ })
162
+ })
@@ -0,0 +1,390 @@
1
+ import {
2
+ Array as Arr,
3
+ Context,
4
+ Effect,
5
+ Encoding,
6
+ Layer,
7
+ Match,
8
+ Option,
9
+ Redacted,
10
+ Result,
11
+ Schema,
12
+ Stream,
13
+ } from "effect"
14
+ import { HttpClient, HttpClientRequest } from "effect/unstable/http"
15
+ import * as AiError from "@effect-uai/core/AiError"
16
+ import type { AudioChunk, AudioFormat } from "@effect-uai/core/Audio"
17
+ import type {
18
+ CommonGenerateMusicRequest,
19
+ CommonStreamGenerateMusicRequest,
20
+ MusicResult,
21
+ MusicSessionInput,
22
+ WeightedPrompt,
23
+ } from "@effect-uai/core/Music"
24
+ import { MusicGenerator, type MusicGeneratorService } from "@effect-uai/core/MusicGenerator"
25
+ import type { LyriaModel } from "./models.js"
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // Public types
29
+ // ---------------------------------------------------------------------------
30
+
31
+ /**
32
+ * Lyria-typed generate request. Narrows `model` to `LyriaModel`. The
33
+ * Lyria sync API (`generateContent`) accepts only `audio/mp3` and
34
+ * `audio/wav` output; `bpm`, `scale`, `instrumental` etc. on the
35
+ * `CommonGenerateMusicRequest` are flattened into the prompt text
36
+ * because the public API does not expose them as structured fields.
37
+ */
38
+ export type LyriaGenerateRequest = Omit<CommonGenerateMusicRequest, "model"> & {
39
+ readonly model: LyriaModel
40
+ }
41
+
42
+ export type LyriaGeneratorService = {
43
+ readonly generate: (request: LyriaGenerateRequest) => Effect.Effect<MusicResult, AiError.AiError>
44
+ readonly streamGeneration: (
45
+ request: LyriaGenerateRequest,
46
+ ) => Stream.Stream<AudioChunk, AiError.AiError>
47
+ readonly streamGenerationFrom: <E, R>(
48
+ input: Stream.Stream<MusicSessionInput, E, R>,
49
+ request: CommonStreamGenerateMusicRequest,
50
+ ) => Stream.Stream<AudioChunk, AiError.AiError | E, R>
51
+ }
52
+
53
+ export class LyriaGenerator extends Context.Service<LyriaGenerator, LyriaGeneratorService>()(
54
+ "@betalyra/effect-uai/providers/google/LyriaGenerator",
55
+ ) {}
56
+
57
+ export type Config = {
58
+ readonly apiKey: Redacted.Redacted
59
+ readonly baseUrl?: string
60
+ }
61
+
62
+ // ---------------------------------------------------------------------------
63
+ // Codec — request → prompt text + response_format
64
+ // ---------------------------------------------------------------------------
65
+
66
+ export type LyriaResponseMimeType = "audio/mp3" | "audio/wav"
67
+
68
+ export const containerToMimeType: (
69
+ container: AudioFormat["container"],
70
+ ) => Effect.Effect<LyriaResponseMimeType, AiError.AiError> = Match.type<
71
+ AudioFormat["container"]
72
+ >().pipe(
73
+ Match.when("mp3", () => Effect.succeed<LyriaResponseMimeType>("audio/mp3")),
74
+ Match.when("wav", () => Effect.succeed<LyriaResponseMimeType>("audio/wav")),
75
+ Match.whenOr("ogg", "opus", "flac", "aac", "webm", "raw", (c) =>
76
+ Effect.fail(
77
+ new AiError.Unsupported({
78
+ provider: "lyria",
79
+ capability: "outputFormat",
80
+ reason: `Lyria 3 only produces audio/mp3 or audio/wav; ${c} is not available. Use container: "mp3" or "wav".`,
81
+ }),
82
+ ),
83
+ ),
84
+ Match.exhaustive,
85
+ )
86
+
87
+ /**
88
+ * Is this a Lyria 3 Clip model variant? Clip is fixed at 30 s MP3 — it
89
+ * does not accept a `responseFormat` on `generationConfig` (the live
90
+ * API rejects unknown fields, despite what the docs imply). Pro
91
+ * accepts the documented `responseFormat` knob.
92
+ */
93
+ const isClipModel = (model: string): boolean => model.includes("clip")
94
+
95
+ export const realizedFormat: (mime: LyriaResponseMimeType) => AudioFormat =
96
+ Match.type<LyriaResponseMimeType>().pipe(
97
+ Match.when(
98
+ "audio/mp3",
99
+ (): AudioFormat => ({ container: "mp3", encoding: "mp3", sampleRate: 44100, channels: 2 }),
100
+ ),
101
+ Match.when(
102
+ "audio/wav",
103
+ (): AudioFormat => ({
104
+ container: "wav",
105
+ encoding: "pcm_s16le",
106
+ sampleRate: 44100,
107
+ channels: 2,
108
+ }),
109
+ ),
110
+ Match.exhaustive,
111
+ )
112
+
113
+ /**
114
+ * Collapse `prompts | WeightedPrompt[]` into a single prompt string and
115
+ * splice in non-structural hints (`lyrics`, `bpm`, `scale`,
116
+ * `instrumental`, `durationSeconds`). The Lyria 3 sync API only takes
117
+ * one text part — every condition lives inline.
118
+ */
119
+ export const buildPrompt = (request: CommonGenerateMusicRequest): string => {
120
+ const promptText = Match.value(request.prompts).pipe(
121
+ Match.when(Match.string, (s) => s),
122
+ Match.orElse((ws: ReadonlyArray<WeightedPrompt>) =>
123
+ Arr.map(ws, (w) =>
124
+ w.weight !== undefined && w.weight !== 1 ? `${w.text} (weight ${w.weight})` : w.text,
125
+ ).join(". "),
126
+ ),
127
+ )
128
+ const hints = Arr.getSomes([
129
+ request.instrumental === true ? Option.some("Instrumental only — no vocals.") : Option.none(),
130
+ request.bpm !== undefined ? Option.some(`BPM: ${request.bpm}.`) : Option.none(),
131
+ request.scale !== undefined ? Option.some(`Key/scale: ${request.scale}.`) : Option.none(),
132
+ request.durationSeconds !== undefined
133
+ ? Option.some(`Target duration: ${request.durationSeconds}s.`)
134
+ : Option.none(),
135
+ ])
136
+ const lyricsBlock =
137
+ request.lyrics !== undefined && request.instrumental !== true
138
+ ? `\n\nLyrics:\n${request.lyrics}`
139
+ : ""
140
+ return [promptText, ...hints].join(" ") + lyricsBlock
141
+ }
142
+
143
+ // ---------------------------------------------------------------------------
144
+ // Wire response schema — just enough to find audio + optional lyrics text
145
+ // ---------------------------------------------------------------------------
146
+
147
+ const InlineData = Schema.Struct({
148
+ mimeType: Schema.optional(Schema.String),
149
+ data: Schema.String,
150
+ })
151
+
152
+ const Part = Schema.Struct({
153
+ text: Schema.optional(Schema.String),
154
+ inlineData: Schema.optional(InlineData),
155
+ })
156
+
157
+ const Content = Schema.Struct({
158
+ parts: Schema.optional(Schema.Array(Part)),
159
+ })
160
+
161
+ const Candidate = Schema.Struct({
162
+ content: Schema.optional(Content),
163
+ })
164
+
165
+ const Wire = Schema.Struct({
166
+ candidates: Schema.optional(Schema.Array(Candidate)),
167
+ })
168
+
169
+ const decodeWire = Schema.decodeUnknownEffect(Wire)
170
+
171
+ // ---------------------------------------------------------------------------
172
+ // HTTP plumbing
173
+ // ---------------------------------------------------------------------------
174
+
175
+ const baseUrl = (cfg: Config): string =>
176
+ cfg.baseUrl ?? "https://generativelanguage.googleapis.com/v1beta"
177
+
178
+ const transportFailure = (cause: unknown): AiError.AiError =>
179
+ new AiError.Unavailable({ provider: "lyria", raw: cause })
180
+
181
+ const httpStatusError: (status: number, body: string) => AiError.AiError = (status, body) =>
182
+ Match.value(status).pipe(
183
+ Match.when(
184
+ 429,
185
+ (): AiError.AiError => new AiError.RateLimited({ provider: "lyria", raw: body }),
186
+ ),
187
+ Match.whenOr(
188
+ 408,
189
+ 504,
190
+ (): AiError.AiError => new AiError.Timeout({ provider: "lyria", raw: body }),
191
+ ),
192
+ Match.when(
193
+ 401,
194
+ (): AiError.AiError =>
195
+ new AiError.AuthFailed({ provider: "lyria", subtype: "auth", raw: body }),
196
+ ),
197
+ Match.when(
198
+ 403,
199
+ (): AiError.AiError =>
200
+ new AiError.AuthFailed({ provider: "lyria", subtype: "permission", raw: body }),
201
+ ),
202
+ Match.when(
203
+ 402,
204
+ (): AiError.AiError =>
205
+ new AiError.AuthFailed({ provider: "lyria", subtype: "billing", raw: body }),
206
+ ),
207
+ Match.when(
208
+ (n) => n >= 500,
209
+ (n): AiError.AiError => new AiError.Unavailable({ provider: "lyria", status: n, raw: body }),
210
+ ),
211
+ Match.orElse(
212
+ (): AiError.AiError => new AiError.InvalidRequest({ provider: "lyria", raw: body }),
213
+ ),
214
+ )
215
+
216
+ const decodeBase64ToBytes = (b64: string): Effect.Effect<Uint8Array, AiError.AiError> =>
217
+ Result.match(Encoding.decodeBase64(b64), {
218
+ onSuccess: Effect.succeed,
219
+ onFailure: (cause) =>
220
+ Effect.fail(new AiError.InvalidRequest({ provider: "lyria", param: "audio", raw: cause })),
221
+ })
222
+
223
+ /**
224
+ * Find the first inline-data audio part and the concatenated text parts
225
+ * from a Wire response.
226
+ */
227
+ const extractParts = (
228
+ wire: typeof Wire.Type,
229
+ ): { readonly inline?: typeof InlineData.Type; readonly text?: string } => {
230
+ const allParts = (wire.candidates ?? []).flatMap((c) => c.content?.parts ?? [])
231
+ const inline = allParts.find((p) => p.inlineData !== undefined)?.inlineData
232
+ const textParts = allParts.flatMap((p) => (p.text !== undefined ? [p.text] : []))
233
+ const text = textParts.length === 0 ? undefined : textParts.join("\n")
234
+ return {
235
+ ...(inline !== undefined && { inline }),
236
+ ...(text !== undefined && { text }),
237
+ }
238
+ }
239
+
240
+ // ---------------------------------------------------------------------------
241
+ // Service implementation
242
+ // ---------------------------------------------------------------------------
243
+
244
+ const generateImpl =
245
+ (cfg: Config) =>
246
+ (
247
+ request: LyriaGenerateRequest,
248
+ ): Effect.Effect<MusicResult, AiError.AiError, HttpClient.HttpClient> =>
249
+ Effect.gen(function* () {
250
+ const client = yield* HttpClient.HttpClient
251
+ const requestedContainer = (request.outputFormat?.container ??
252
+ "mp3") satisfies AudioFormat["container"]
253
+ const mimeType = yield* containerToMimeType(requestedContainer)
254
+ // Clip is fixed 30 s mp3 — reject wav up front rather than sending
255
+ // a `responseFormat` that the live API ignores or rejects.
256
+ if (isClipModel(request.model) && mimeType === "audio/wav") {
257
+ return yield* new AiError.Unsupported({
258
+ provider: "lyria",
259
+ capability: "outputFormat",
260
+ reason: `lyria-3-clip-preview is fixed at audio/mp3. Use lyria-3-pro-preview for audio/wav output.`,
261
+ })
262
+ }
263
+ const promptText = buildPrompt(request)
264
+ const body = isClipModel(request.model)
265
+ ? { contents: [{ parts: [{ text: promptText }] }] }
266
+ : {
267
+ contents: [{ parts: [{ text: promptText }] }],
268
+ generationConfig: {
269
+ responseModalities: ["AUDIO", "TEXT"],
270
+ responseFormat: { audio: { mimeType } },
271
+ },
272
+ }
273
+ const httpRequest = HttpClientRequest.post(
274
+ `${baseUrl(cfg)}/models/${request.model}:generateContent`,
275
+ ).pipe(
276
+ HttpClientRequest.setHeader("x-goog-api-key", Redacted.value(cfg.apiKey)),
277
+ HttpClientRequest.bodyJsonUnsafe(body),
278
+ )
279
+ const response = yield* client.execute(httpRequest).pipe(Effect.mapError(transportFailure))
280
+ if (response.status >= 400) {
281
+ const text = yield* response.text.pipe(Effect.orElseSucceed(() => ""))
282
+ return yield* httpStatusError(response.status, text)
283
+ }
284
+ const json = yield* response.json.pipe(Effect.mapError(transportFailure))
285
+ const wire = yield* decodeWire(json).pipe(
286
+ Effect.mapError(
287
+ (cause): AiError.AiError =>
288
+ new AiError.GenerationFailed({ provider: "lyria", raw: cause }),
289
+ ),
290
+ )
291
+ const { inline, text } = extractParts(wire)
292
+ if (inline === undefined) {
293
+ // No audio came back. Most common cause: Lyria filtered the prompt
294
+ // (named-artist references, copyrighted lyrics, etc.). Surface the
295
+ // full response body — text parts, finish reasons, prompt-feedback
296
+ // blocks — so the caller can see why.
297
+ return yield* new AiError.GenerationFailed({
298
+ provider: "lyria",
299
+ raw: {
300
+ message: "Lyria response had no inlineData audio part.",
301
+ hint: "Likely a prompt-filter rejection. Lyria filters references to real artists / copyrighted song lyrics. Rephrase with descriptive style language instead of artist names.",
302
+ textParts: text,
303
+ response: json,
304
+ },
305
+ })
306
+ }
307
+ const bytes = yield* decodeBase64ToBytes(inline.data)
308
+ return {
309
+ format: realizedFormat(mimeType),
310
+ bytes,
311
+ ...(text !== undefined && { lyrics: text }),
312
+ watermark: { kind: "synthid" },
313
+ } satisfies MusicResult
314
+ })
315
+
316
+ const streamGenerationImpl =
317
+ (cfg: Config) =>
318
+ (
319
+ request: LyriaGenerateRequest,
320
+ ): Stream.Stream<AudioChunk, AiError.AiError, HttpClient.HttpClient> =>
321
+ Stream.unwrap(
322
+ Effect.map(generateImpl(cfg)(request), (result) =>
323
+ Stream.succeed<AudioChunk>({ bytes: result.bytes }),
324
+ ),
325
+ )
326
+
327
+ /**
328
+ * Lyria 3 sync has no bidirectional session at the wire level — that's
329
+ * Lyria RealTime (Phase 1b, separate Layer). The provider Layer here
330
+ * also does NOT register `MusicInteractiveSession`, so callers using
331
+ * `MusicGenerator.streamGenerationFrom` against only this Layer get a
332
+ * compile-time error before this runtime fallback ever fires.
333
+ */
334
+ const streamGenerationFromUnsupported = <E, R>(
335
+ _input: Stream.Stream<MusicSessionInput, E, R>,
336
+ _request: CommonStreamGenerateMusicRequest,
337
+ ): Stream.Stream<AudioChunk, AiError.AiError | E, R> => {
338
+ const fail: Stream.Stream<AudioChunk, AiError.AiError | E, R> = Stream.fail(
339
+ new AiError.Unsupported({
340
+ provider: "lyria",
341
+ capability: "streamGenerationFrom",
342
+ reason:
343
+ "Lyria 3 sync does not support bidirectional sessions. Use the Lyria RealTime Layer (WebSocket BidiGenerateMusic) for interactive mid-session prompts.",
344
+ }),
345
+ )
346
+ return fail
347
+ }
348
+
349
+ // ---------------------------------------------------------------------------
350
+ // Constructors
351
+ // ---------------------------------------------------------------------------
352
+
353
+ export const make = (
354
+ cfg: Config,
355
+ ): Effect.Effect<LyriaGeneratorService, never, HttpClient.HttpClient> =>
356
+ Effect.map(HttpClient.HttpClient.asEffect(), (client) => ({
357
+ generate: (request) =>
358
+ generateImpl(cfg)(request).pipe(Effect.provideService(HttpClient.HttpClient, client)),
359
+ streamGeneration: (request) =>
360
+ streamGenerationImpl(cfg)(request).pipe(Stream.provideService(HttpClient.HttpClient, client)),
361
+ streamGenerationFrom: streamGenerationFromUnsupported,
362
+ }))
363
+
364
+ /**
365
+ * Layer that registers both the provider-specific `LyriaGenerator` tag
366
+ * and the generic `MusicGenerator` tag.
367
+ *
368
+ * Does NOT register the `MusicInteractiveSession` capability marker —
369
+ * Lyria 3 sync has no bidirectional session at the wire level. Code
370
+ * calling `MusicGenerator.streamGenerationFrom` will fail to typecheck
371
+ * against this Layer alone, which is the intended UX.
372
+ */
373
+ export const layer = (
374
+ cfg: Config,
375
+ ): Layer.Layer<LyriaGenerator | MusicGenerator, never, HttpClient.HttpClient> =>
376
+ Layer.merge(
377
+ Layer.effect(LyriaGenerator, make(cfg)),
378
+ Layer.effect(
379
+ MusicGenerator,
380
+ Effect.map(
381
+ make(cfg),
382
+ (s): MusicGeneratorService => ({
383
+ generate: (req: CommonGenerateMusicRequest) => s.generate(req as LyriaGenerateRequest),
384
+ streamGeneration: (req: CommonStreamGenerateMusicRequest) =>
385
+ s.streamGeneration(req as LyriaGenerateRequest),
386
+ streamGenerationFrom: s.streamGenerationFrom,
387
+ }),
388
+ ),
389
+ ),
390
+ )