@memberjunction/ai-gemini 6.2.0-edge.3 → 6.2.0-edge.5

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 (46) hide show
  1. package/dist/geminiAvatarVideoBitrate.d.ts +29 -0
  2. package/dist/geminiAvatarVideoBitrate.d.ts.map +1 -0
  3. package/dist/geminiAvatarVideoBitrate.js +58 -0
  4. package/dist/geminiAvatarVideoBitrate.js.map +1 -0
  5. package/dist/geminiBridgedAvatar.d.ts +119 -0
  6. package/dist/geminiBridgedAvatar.d.ts.map +1 -0
  7. package/dist/geminiBridgedAvatar.js +196 -0
  8. package/dist/geminiBridgedAvatar.js.map +1 -0
  9. package/dist/geminiEmbedding.d.ts +11 -0
  10. package/dist/geminiEmbedding.d.ts.map +1 -1
  11. package/dist/geminiEmbedding.js +34 -12
  12. package/dist/geminiEmbedding.js.map +1 -1
  13. package/dist/geminiImage.d.ts +10 -3
  14. package/dist/geminiImage.d.ts.map +1 -1
  15. package/dist/geminiImage.js +84 -14
  16. package/dist/geminiImage.js.map +1 -1
  17. package/dist/geminiLiveProfiles.d.ts +111 -4
  18. package/dist/geminiLiveProfiles.d.ts.map +1 -1
  19. package/dist/geminiLiveProfiles.js +169 -4
  20. package/dist/geminiLiveProfiles.js.map +1 -1
  21. package/dist/geminiLiveRelayPolicy.d.ts +87 -0
  22. package/dist/geminiLiveRelayPolicy.d.ts.map +1 -0
  23. package/dist/geminiLiveRelayPolicy.js +425 -0
  24. package/dist/geminiLiveRelayPolicy.js.map +1 -0
  25. package/dist/geminiLiveSetup.d.ts +79 -0
  26. package/dist/geminiLiveSetup.d.ts.map +1 -0
  27. package/dist/geminiLiveSetup.js +287 -0
  28. package/dist/geminiLiveSetup.js.map +1 -0
  29. package/dist/geminiRealtime.d.ts +171 -12
  30. package/dist/geminiRealtime.d.ts.map +1 -1
  31. package/dist/geminiRealtime.js +957 -141
  32. package/dist/geminiRealtime.js.map +1 -1
  33. package/dist/geminiSampling.d.ts +30 -0
  34. package/dist/geminiSampling.d.ts.map +1 -0
  35. package/dist/geminiSampling.js +44 -0
  36. package/dist/geminiSampling.js.map +1 -0
  37. package/dist/geminiThinking.d.ts +54 -0
  38. package/dist/geminiThinking.d.ts.map +1 -0
  39. package/dist/geminiThinking.js +107 -0
  40. package/dist/geminiThinking.js.map +1 -0
  41. package/dist/index.d.ts +60 -43
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +177 -309
  44. package/dist/index.js.map +1 -1
  45. package/package.json +5 -5
  46. package/readme.md +66 -1
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @fileoverview The video bitrate a Gemini Live avatar session asks Google for (`avatarConfig.videoBitrateBps`), and the
3
+ * deployment setting that changes it.
4
+ *
5
+ * MJ asks for 2 Mbps: Google's sample avatar streams run at about 8.5 Mbps, and MJAPI relays the avatar to the browser.
6
+ * The field is in `@google/genai`'s types but not on Google's pages, so a deployment can change the number, or leave the
7
+ * field out and let Google choose, without a rebuild: `MJ_GEMINI_AVATAR_VIDEO_BITRATE_BPS` (bits per second; `0` leaves
8
+ * the field out). It is read each time a session's connect config is built, so a restart of the server applies it to the
9
+ * browser mint, the relay's setup and server-side (meeting) sessions alike.
10
+ *
11
+ * @module @memberjunction/ai-gemini
12
+ * @author MemberJunction.com
13
+ */
14
+ /** The environment variable that sets the avatar's video bitrate, in bits per second (`0` leaves the field out). */
15
+ export declare const GEMINI_AVATAR_VIDEO_BITRATE_ENV = "MJ_GEMINI_AVATAR_VIDEO_BITRATE_BPS";
16
+ /** The bitrate MJ asks for when the variable is unset or not a whole number: 2 Mbps. */
17
+ export declare const GEMINI_AVATAR_VIDEO_BITRATE_BPS_DEFAULT = 2000000;
18
+ /**
19
+ * The video bitrate for a Gemini Live avatar session's `avatarConfig.videoBitrateBps`, or `null` to leave the field out.
20
+ *
21
+ * - Unset or blank: {@link GEMINI_AVATAR_VIDEO_BITRATE_BPS_DEFAULT}.
22
+ * - `0`: `null`, so Google uses its own bitrate.
23
+ * - A whole number of bits per second: that number.
24
+ * - Anything else: the default, with one log line per such value.
25
+ *
26
+ * @param env The environment to read; the process's by default.
27
+ */
28
+ export declare function ResolveGeminiAvatarVideoBitrateBps(env?: Readonly<Record<string, string | undefined>>): number | null;
29
+ //# sourceMappingURL=geminiAvatarVideoBitrate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"geminiAvatarVideoBitrate.d.ts","sourceRoot":"","sources":["../src/geminiAvatarVideoBitrate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,oHAAoH;AACpH,eAAO,MAAM,+BAA+B,uCAAuC,CAAC;AAEpF,wFAAwF;AACxF,eAAO,MAAM,uCAAuC,UAAY,CAAC;AAQjE;;;;;;;;;GASG;AACH,wBAAgB,kCAAkC,CAAC,GAAG,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAwB,GAAG,MAAM,GAAG,IAAI,CAW1I"}
@@ -0,0 +1,58 @@
1
+ /**
2
+ * @fileoverview The video bitrate a Gemini Live avatar session asks Google for (`avatarConfig.videoBitrateBps`), and the
3
+ * deployment setting that changes it.
4
+ *
5
+ * MJ asks for 2 Mbps: Google's sample avatar streams run at about 8.5 Mbps, and MJAPI relays the avatar to the browser.
6
+ * The field is in `@google/genai`'s types but not on Google's pages, so a deployment can change the number, or leave the
7
+ * field out and let Google choose, without a rebuild: `MJ_GEMINI_AVATAR_VIDEO_BITRATE_BPS` (bits per second; `0` leaves
8
+ * the field out). It is read each time a session's connect config is built, so a restart of the server applies it to the
9
+ * browser mint, the relay's setup and server-side (meeting) sessions alike.
10
+ *
11
+ * @module @memberjunction/ai-gemini
12
+ * @author MemberJunction.com
13
+ */
14
+ /** The environment variable that sets the avatar's video bitrate, in bits per second (`0` leaves the field out). */
15
+ export const GEMINI_AVATAR_VIDEO_BITRATE_ENV = 'MJ_GEMINI_AVATAR_VIDEO_BITRATE_BPS';
16
+ /** The bitrate MJ asks for when the variable is unset or not a whole number: 2 Mbps. */
17
+ export const GEMINI_AVATAR_VIDEO_BITRATE_BPS_DEFAULT = 2_000_000;
18
+ /** The longest part of an unusable value quoted in the log line. */
19
+ const MAX_QUOTED_CHARS = 40;
20
+ /** Unusable values already reported, so each is logged once per process. */
21
+ const reportedValues = new Set();
22
+ /**
23
+ * The video bitrate for a Gemini Live avatar session's `avatarConfig.videoBitrateBps`, or `null` to leave the field out.
24
+ *
25
+ * - Unset or blank: {@link GEMINI_AVATAR_VIDEO_BITRATE_BPS_DEFAULT}.
26
+ * - `0`: `null`, so Google uses its own bitrate.
27
+ * - A whole number of bits per second: that number.
28
+ * - Anything else: the default, with one log line per such value.
29
+ *
30
+ * @param env The environment to read; the process's by default.
31
+ */
32
+ export function ResolveGeminiAvatarVideoBitrateBps(env = processEnvironment()) {
33
+ const raw = env[GEMINI_AVATAR_VIDEO_BITRATE_ENV]?.trim() ?? '';
34
+ if (raw.length === 0) {
35
+ return GEMINI_AVATAR_VIDEO_BITRATE_BPS_DEFAULT;
36
+ }
37
+ const value = /^\d+$/.test(raw) ? Number(raw) : Number.NaN;
38
+ if (Number.isSafeInteger(value)) {
39
+ return value === 0 ? null : value;
40
+ }
41
+ reportUnusable(raw);
42
+ return GEMINI_AVATAR_VIDEO_BITRATE_BPS_DEFAULT;
43
+ }
44
+ /** One log line per unusable value, quoting it shortened and with only printable characters. */
45
+ function reportUnusable(raw) {
46
+ if (reportedValues.has(raw)) {
47
+ return;
48
+ }
49
+ reportedValues.add(raw);
50
+ const shown = raw.replace(/[^\x20-\x7E]/g, '?').slice(0, MAX_QUOTED_CHARS);
51
+ console.warn(`[GeminiRealtime] ${GEMINI_AVATAR_VIDEO_BITRATE_ENV} "${shown}" is not a whole number of bits per second; avatar sessions ask for ` +
52
+ `${GEMINI_AVATAR_VIDEO_BITRATE_BPS_DEFAULT}. Set a number such as 2000000; 0 leaves the field out.`);
53
+ }
54
+ /** The process's environment, or none on a runtime without `process`. */
55
+ function processEnvironment() {
56
+ return typeof process !== 'undefined' && process.env ? process.env : {};
57
+ }
58
+ //# sourceMappingURL=geminiAvatarVideoBitrate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"geminiAvatarVideoBitrate.js","sourceRoot":"","sources":["../src/geminiAvatarVideoBitrate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,oHAAoH;AACpH,MAAM,CAAC,MAAM,+BAA+B,GAAG,oCAAoC,CAAC;AAEpF,wFAAwF;AACxF,MAAM,CAAC,MAAM,uCAAuC,GAAG,SAAS,CAAC;AAEjE,oEAAoE;AACpE,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAE5B,4EAA4E;AAC5E,MAAM,cAAc,GAAG,IAAI,GAAG,EAAU,CAAC;AAEzC;;;;;;;;;GASG;AACH,MAAM,UAAU,kCAAkC,CAAC,MAAoD,kBAAkB,EAAE;IACvH,MAAM,GAAG,GAAG,GAAG,CAAC,+BAA+B,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAC/D,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACnB,OAAO,uCAAuC,CAAC;IACnD,CAAC;IACD,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;IAC3D,IAAI,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC;QAC9B,OAAO,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;IACtC,CAAC;IACD,cAAc,CAAC,GAAG,CAAC,CAAC;IACpB,OAAO,uCAAuC,CAAC;AACnD,CAAC;AAED,gGAAgG;AAChG,SAAS,cAAc,CAAC,GAAW;IAC/B,IAAI,cAAc,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;QAC1B,OAAO;IACX,CAAC;IACD,cAAc,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACxB,MAAM,KAAK,GAAG,GAAG,CAAC,OAAO,CAAC,eAAe,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,gBAAgB,CAAC,CAAC;IAC3E,OAAO,CAAC,IAAI,CACR,oBAAoB,+BAA+B,KAAK,KAAK,sEAAsE;QAC/H,GAAG,uCAAuC,yDAAyD,CAC1G,CAAC;AACN,CAAC;AAED,yEAAyE;AACzE,SAAS,kBAAkB;IACvB,OAAO,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;AAC5E,CAAC"}
@@ -0,0 +1,119 @@
1
+ /**
2
+ * @fileoverview The avatar half of a server-side (bridged) Gemini Live session whose host publishes the avatar into a
3
+ * meeting room: where each model part goes, what each turn boundary does, and how many seconds of avatar video the
4
+ * session generated.
5
+ *
6
+ * - **Parts.** A part that opens with an MP4 box (`ftyp`, `moov`, `moof`, `styp`) is a piece of the avatar's fragmented
7
+ * MP4 whatever MIME type it names, and so is a `video/*` part. Each goes to the host as a `RealtimeVideoFrame` (Core's
8
+ * `Fmp4PieceToVideoFrame`: init or fragment, with its time and key-frame flag) typed `video/mp4`, keeping a `video/mp4`
9
+ * type's codecs, which is what the room's bridge publishes. A `video/*` part that is neither labelled `video/mp4` nor
10
+ * opens with an MP4 box is dropped and reported once per type. A part with no MIME type that is not MP4 is PCM. A PCM
11
+ * part plays as the voice only while the turn has no video yet: the MP4's audio track carries the voice, so later PCM
12
+ * in the turn would play it twice and is dropped (reported once). Any other part is dropped and reported once per
13
+ * type: unknown data never plays.
14
+ * - **Turns.** From `interrupted` until that turn's `turnComplete`, media parts are dropped (Google sends
15
+ * `interrupted` before `turn_complete`; anything in between is stale after the barge-in).
16
+ * - **Answer or idle.** Vertex AI streams the avatar's video between answers too. The model's answer is under way from
17
+ * its first spoken words (the session reports its output transcription with
18
+ * {@link GeminiBridgedAvatarOutput.AnswerStarted}) or a PCM voice part that plays, until its `generationComplete`, the
19
+ * turn's `turnComplete`, a barge-in, a tool call, a resume or the session's close. Before a part of the answer goes to
20
+ * the host, {@link GeminiBridgedAvatarSinks.OnAnswer} says the model is answering, so the session holds its sends; the
21
+ * video outside an answer goes to the host as well (the avatar keeps its face), marked `Idle`, so a room's floor gate
22
+ * doesn't count it as the agent speaking, whatever its audio track holds. An answer's first pieces can come before its
23
+ * first transcribed words; they are marked `Idle` too.
24
+ * - **Usage.** The seconds of avatar video generated in a turn (its video samples' durations, read from the fragments)
25
+ * are reported as deltas at the turn's end: `generationComplete`, `interrupted`, `turnComplete`, a resume, or the
26
+ * session's close. Video after `generationComplete` is forwarded (idle frames, if Google sends any) but not counted;
27
+ * an interrupted turn counts what arrived before the interruption. The count does not follow the answer above: all
28
+ * video from the session's start, a `turnComplete` or a resume until the next `generationComplete` counts, idle or
29
+ * not, while how Google bills avatar video is open (#5312).
30
+ *
31
+ * @module @memberjunction/ai-gemini
32
+ * @author MemberJunction.com
33
+ */
34
+ import { type RealtimeVideoFrame } from '@memberjunction/ai';
35
+ /** Where a bridged avatar session's media and usage go. */
36
+ export interface GeminiBridgedAvatarSinks {
37
+ /** A piece of the avatar's fragmented MP4 as a frame, in the order the model sent it; marked `Idle` outside an answer. */
38
+ OnVideoFrame(frame: RealtimeVideoFrame): void;
39
+ /** PCM voice: a turn's audio before any of its video arrived. */
40
+ OnPcm(pcm: ArrayBuffer): void;
41
+ /** Seconds of avatar video generated since the last report (a delta, never a total). */
42
+ OnVideoSeconds(seconds: number): void;
43
+ /**
44
+ * The model is answering: called before each part of its answer goes to the host (its avatar's video while the answer
45
+ * is under way, or voice that plays). Never called for the video the avatar streams between answers.
46
+ */
47
+ OnAnswer(): void;
48
+ /** One line about a part that was dropped; called once per kind of drop. */
49
+ Report(message: string): void;
50
+ }
51
+ /**
52
+ * Routes a granted bridged avatar session's model parts to the host (avatar pieces) and the session's audio output
53
+ * (PCM before the turn's first video), says which of them are the model's answer, applies each turn boundary, and reports
54
+ * the avatar video seconds generated. The Gemini session creates one when the driver granted an avatar to a host that
55
+ * publishes it into a room.
56
+ */
57
+ export declare class GeminiBridgedAvatarOutput {
58
+ private readonly sinks;
59
+ private readonly reported;
60
+ private turn;
61
+ /** The stream's latest readable init segment: its tracks and timescales let the fragments' durations be read. */
62
+ private init;
63
+ /** Avatar video seconds counted and not yet reported. */
64
+ private pendingVideoSeconds;
65
+ /** Whether the model's answer is under way (see the module's "Answer or idle"): video outside it is idle. */
66
+ private answering;
67
+ /** @param sinks Where the media, the voice, the usage and the drop reports go. */
68
+ constructor(sinks: GeminiBridgedAvatarSinks);
69
+ /**
70
+ * Plays one model part, or drops it.
71
+ *
72
+ * @param mimeType The part's `inlineData.mimeType`, when it names one.
73
+ * @param data The part's bytes.
74
+ */
75
+ Accept(mimeType: string | undefined, data: ArrayBuffer): void;
76
+ /**
77
+ * The model's answer is under way: its output transcription has words. The video that follows is the answer's until
78
+ * its generation completes, the turn completes, a barge-in stops it, or the model calls a tool.
79
+ */
80
+ AnswerStarted(): void;
81
+ /** The model called a tool: its answer stops there, and the video until it speaks again is idle. */
82
+ ToolCalled(): void;
83
+ /**
84
+ * `generationComplete`: the turn's media is all in, and the answer is over. Its avatar seconds are reported; later
85
+ * video is idle and not counted.
86
+ */
87
+ GenerationComplete(): void;
88
+ /** `turnComplete`: reports what is still uncounted, ends the answer and a barge-in's drop window, and starts a new turn. */
89
+ TurnComplete(): void;
90
+ /**
91
+ * `interrupted`: the turn counts what arrived and its answer ends; its late parts are dropped (and not counted) until
92
+ * its `turnComplete`.
93
+ */
94
+ Interrupted(): void;
95
+ /** The session resumed on a new connection, where a turn the drop cut off never completes: the answer ends, a new turn starts. */
96
+ Resumed(): void;
97
+ /** The session is closing: what was generated and not yet reported is reported now, and no answer is under way. */
98
+ Close(): void;
99
+ /**
100
+ * How a part plays. Its bytes decide first: a part that opens with an MP4 box is the avatar's whatever type it names,
101
+ * since Google does not document the type of avatar parts. Then its type: none means PCM; a `video/*` type is the
102
+ * avatar's (a `video/mp4` piece may start inside a box; any other video type that isn't MP4 is then dropped); a PCM
103
+ * type is the voice; anything else never plays.
104
+ */
105
+ private static kindOf;
106
+ /**
107
+ * Makes the piece a frame, counts its video seconds (before the host may take the buffer), then hands it on: saying
108
+ * first that the model is answering when the piece is the answer's, or marking it `Idle` when it isn't. The frame is
109
+ * typed `video/mp4`, keeping the part's own type when it names `video/mp4` with its codecs: the room's bridge
110
+ * publishes a piece as the avatar only when its type is `video/mp4`, and every piece of the stream is. A piece that
111
+ * isn't MP4 is dropped, reported once per type.
112
+ */
113
+ private acceptAvatar;
114
+ /** Plays a PCM part as the voice, unless the turn's video carries it. Voice that plays means the answer is under way. */
115
+ private acceptVoice;
116
+ private reportVideoSeconds;
117
+ private reportOnce;
118
+ }
119
+ //# sourceMappingURL=geminiBridgedAvatar.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"geminiBridgedAvatar.d.ts","sourceRoot":"","sources":["../src/geminiBridgedAvatar.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,EAOH,KAAK,kBAAkB,EAC1B,MAAM,oBAAoB,CAAC;AAE5B,2DAA2D;AAC3D,MAAM,WAAW,wBAAwB;IACrC,0HAA0H;IAC1H,YAAY,CAAC,KAAK,EAAE,kBAAkB,GAAG,IAAI,CAAC;IAC9C,iEAAiE;IACjE,KAAK,CAAC,GAAG,EAAE,WAAW,GAAG,IAAI,CAAC;IAC9B,wFAAwF;IACxF,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACtC;;;OAGG;IACH,QAAQ,IAAI,IAAI,CAAC;IACjB,4EAA4E;IAC5E,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CACjC;AAmBD;;;;;GAKG;AACH,qBAAa,yBAAyB;IAWtB,OAAO,CAAC,QAAQ,CAAC,KAAK;IAVlC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAqB;IAC9C,OAAO,CAAC,IAAI,CAAgC;IAC5C,iHAAiH;IACjH,OAAO,CAAC,IAAI,CAAyB;IACrC,yDAAyD;IACzD,OAAO,CAAC,mBAAmB,CAAK;IAChC,6GAA6G;IAC7G,OAAO,CAAC,SAAS,CAAS;IAE1B,kFAAkF;gBACrD,KAAK,EAAE,wBAAwB;IAE5D;;;;;OAKG;IACI,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,WAAW,GAAG,IAAI;IAcpE;;;OAGG;IACI,aAAa,IAAI,IAAI;IAI5B,oGAAoG;IAC7F,UAAU,IAAI,IAAI;IAIzB;;;OAGG;IACI,kBAAkB,IAAI,IAAI;IAMjC,4HAA4H;IACrH,YAAY,IAAI,IAAI;IAM3B;;;OAGG;IACI,WAAW,IAAI,IAAI;IAM1B,kIAAkI;IAC3H,OAAO,IAAI,IAAI;IAMtB,mHAAmH;IAC5G,KAAK,IAAI,IAAI;IAKpB;;;;;OAKG;IACH,OAAO,CAAC,MAAM,CAAC,MAAM;IAcrB;;;;;;OAMG;IACH,OAAO,CAAC,YAAY;IAqBpB,yHAAyH;IACzH,OAAO,CAAC,WAAW;IAUnB,OAAO,CAAC,kBAAkB;IAS1B,OAAO,CAAC,UAAU;CAMrB"}
@@ -0,0 +1,196 @@
1
+ /**
2
+ * @fileoverview The avatar half of a server-side (bridged) Gemini Live session whose host publishes the avatar into a
3
+ * meeting room: where each model part goes, what each turn boundary does, and how many seconds of avatar video the
4
+ * session generated.
5
+ *
6
+ * - **Parts.** A part that opens with an MP4 box (`ftyp`, `moov`, `moof`, `styp`) is a piece of the avatar's fragmented
7
+ * MP4 whatever MIME type it names, and so is a `video/*` part. Each goes to the host as a `RealtimeVideoFrame` (Core's
8
+ * `Fmp4PieceToVideoFrame`: init or fragment, with its time and key-frame flag) typed `video/mp4`, keeping a `video/mp4`
9
+ * type's codecs, which is what the room's bridge publishes. A `video/*` part that is neither labelled `video/mp4` nor
10
+ * opens with an MP4 box is dropped and reported once per type. A part with no MIME type that is not MP4 is PCM. A PCM
11
+ * part plays as the voice only while the turn has no video yet: the MP4's audio track carries the voice, so later PCM
12
+ * in the turn would play it twice and is dropped (reported once). Any other part is dropped and reported once per
13
+ * type: unknown data never plays.
14
+ * - **Turns.** From `interrupted` until that turn's `turnComplete`, media parts are dropped (Google sends
15
+ * `interrupted` before `turn_complete`; anything in between is stale after the barge-in).
16
+ * - **Answer or idle.** Vertex AI streams the avatar's video between answers too. The model's answer is under way from
17
+ * its first spoken words (the session reports its output transcription with
18
+ * {@link GeminiBridgedAvatarOutput.AnswerStarted}) or a PCM voice part that plays, until its `generationComplete`, the
19
+ * turn's `turnComplete`, a barge-in, a tool call, a resume or the session's close. Before a part of the answer goes to
20
+ * the host, {@link GeminiBridgedAvatarSinks.OnAnswer} says the model is answering, so the session holds its sends; the
21
+ * video outside an answer goes to the host as well (the avatar keeps its face), marked `Idle`, so a room's floor gate
22
+ * doesn't count it as the agent speaking, whatever its audio track holds. An answer's first pieces can come before its
23
+ * first transcribed words; they are marked `Idle` too.
24
+ * - **Usage.** The seconds of avatar video generated in a turn (its video samples' durations, read from the fragments)
25
+ * are reported as deltas at the turn's end: `generationComplete`, `interrupted`, `turnComplete`, a resume, or the
26
+ * session's close. Video after `generationComplete` is forwarded (idle frames, if Google sends any) but not counted;
27
+ * an interrupted turn counts what arrived before the interruption. The count does not follow the answer above: all
28
+ * video from the session's start, a `turnComplete` or a resume until the next `generationComplete` counts, idle or
29
+ * not, while how Google bills avatar video is open (#5312).
30
+ *
31
+ * @module @memberjunction/ai-gemini
32
+ * @author MemberJunction.com
33
+ */
34
+ import { Fmp4PieceToVideoFrame, Fmp4VideoSeconds, IsPcmAudioMimeType, ReadFmp4Init, SniffFmp4Piece, } from '@memberjunction/ai';
35
+ function newTurn() {
36
+ return { HasVideo: false, GenerationEnded: false, Dropping: false };
37
+ }
38
+ /**
39
+ * Routes a granted bridged avatar session's model parts to the host (avatar pieces) and the session's audio output
40
+ * (PCM before the turn's first video), says which of them are the model's answer, applies each turn boundary, and reports
41
+ * the avatar video seconds generated. The Gemini session creates one when the driver granted an avatar to a host that
42
+ * publishes it into a room.
43
+ */
44
+ export class GeminiBridgedAvatarOutput {
45
+ /** @param sinks Where the media, the voice, the usage and the drop reports go. */
46
+ constructor(sinks) {
47
+ this.sinks = sinks;
48
+ this.reported = new Set();
49
+ this.turn = newTurn();
50
+ /** The stream's latest readable init segment: its tracks and timescales let the fragments' durations be read. */
51
+ this.init = null;
52
+ /** Avatar video seconds counted and not yet reported. */
53
+ this.pendingVideoSeconds = 0;
54
+ /** Whether the model's answer is under way (see the module's "Answer or idle"): video outside it is idle. */
55
+ this.answering = false;
56
+ }
57
+ /**
58
+ * Plays one model part, or drops it.
59
+ *
60
+ * @param mimeType The part's `inlineData.mimeType`, when it names one.
61
+ * @param data The part's bytes.
62
+ */
63
+ Accept(mimeType, data) {
64
+ if (this.turn.Dropping) {
65
+ return;
66
+ }
67
+ const kind = GeminiBridgedAvatarOutput.kindOf(mimeType, data);
68
+ if (kind === 'avatar') {
69
+ this.acceptAvatar(mimeType, data);
70
+ }
71
+ else if (kind === 'voice') {
72
+ this.acceptVoice(data);
73
+ }
74
+ else {
75
+ this.reportOnce(`type:${mimeType}`, `[GeminiRealtime] Dropped model output of type ${mimeType}: an avatar session in a meeting plays its MP4 avatar and PCM audio only.`);
76
+ }
77
+ }
78
+ /**
79
+ * The model's answer is under way: its output transcription has words. The video that follows is the answer's until
80
+ * its generation completes, the turn completes, a barge-in stops it, or the model calls a tool.
81
+ */
82
+ AnswerStarted() {
83
+ this.answering = true;
84
+ }
85
+ /** The model called a tool: its answer stops there, and the video until it speaks again is idle. */
86
+ ToolCalled() {
87
+ this.answering = false;
88
+ }
89
+ /**
90
+ * `generationComplete`: the turn's media is all in, and the answer is over. Its avatar seconds are reported; later
91
+ * video is idle and not counted.
92
+ */
93
+ GenerationComplete() {
94
+ this.reportVideoSeconds();
95
+ this.turn.GenerationEnded = true;
96
+ this.answering = false;
97
+ }
98
+ /** `turnComplete`: reports what is still uncounted, ends the answer and a barge-in's drop window, and starts a new turn. */
99
+ TurnComplete() {
100
+ this.reportVideoSeconds();
101
+ this.answering = false;
102
+ this.turn = newTurn();
103
+ }
104
+ /**
105
+ * `interrupted`: the turn counts what arrived and its answer ends; its late parts are dropped (and not counted) until
106
+ * its `turnComplete`.
107
+ */
108
+ Interrupted() {
109
+ this.reportVideoSeconds();
110
+ this.answering = false;
111
+ this.turn.Dropping = true;
112
+ }
113
+ /** The session resumed on a new connection, where a turn the drop cut off never completes: the answer ends, a new turn starts. */
114
+ Resumed() {
115
+ this.reportVideoSeconds();
116
+ this.answering = false;
117
+ this.turn = newTurn();
118
+ }
119
+ /** The session is closing: what was generated and not yet reported is reported now, and no answer is under way. */
120
+ Close() {
121
+ this.reportVideoSeconds();
122
+ this.answering = false;
123
+ }
124
+ /**
125
+ * How a part plays. Its bytes decide first: a part that opens with an MP4 box is the avatar's whatever type it names,
126
+ * since Google does not document the type of avatar parts. Then its type: none means PCM; a `video/*` type is the
127
+ * avatar's (a `video/mp4` piece may start inside a box; any other video type that isn't MP4 is then dropped); a PCM
128
+ * type is the voice; anything else never plays.
129
+ */
130
+ static kindOf(mimeType, data) {
131
+ if (SniffFmp4Piece(data)) {
132
+ return 'avatar';
133
+ }
134
+ const type = mimeType?.trim() ?? '';
135
+ if (type.length === 0) {
136
+ return 'voice';
137
+ }
138
+ if (/^video\//i.test(type)) {
139
+ return 'avatar';
140
+ }
141
+ return IsPcmAudioMimeType(type) ? 'voice' : 'other';
142
+ }
143
+ /**
144
+ * Makes the piece a frame, counts its video seconds (before the host may take the buffer), then hands it on: saying
145
+ * first that the model is answering when the piece is the answer's, or marking it `Idle` when it isn't. The frame is
146
+ * typed `video/mp4`, keeping the part's own type when it names `video/mp4` with its codecs: the room's bridge
147
+ * publishes a piece as the avatar only when its type is `video/mp4`, and every piece of the stream is. A piece that
148
+ * isn't MP4 is dropped, reported once per type.
149
+ */
150
+ acceptAvatar(mimeType, data) {
151
+ const frame = Fmp4PieceToVideoFrame(data, mimeType, this.init);
152
+ if (!frame) {
153
+ const message = `[GeminiRealtime] Dropped model output of type ${mimeType}: it is not fragmented MP4, the only video an avatar plays.`;
154
+ this.reportOnce(`type:${mimeType}`, message);
155
+ return;
156
+ }
157
+ if (frame.Piece === 'init') {
158
+ this.init = ReadFmp4Init(data) ?? this.init;
159
+ }
160
+ else if (!this.turn.GenerationEnded && this.init) {
161
+ this.pendingVideoSeconds += Fmp4VideoSeconds(data, this.init) ?? 0;
162
+ }
163
+ this.turn.HasVideo = true;
164
+ if (!this.answering) {
165
+ this.sinks.OnVideoFrame({ ...frame, Idle: true });
166
+ return;
167
+ }
168
+ this.sinks.OnAnswer();
169
+ this.sinks.OnVideoFrame(frame);
170
+ }
171
+ /** Plays a PCM part as the voice, unless the turn's video carries it. Voice that plays means the answer is under way. */
172
+ acceptVoice(pcm) {
173
+ if (this.turn.HasVideo) {
174
+ this.reportOnce('pcm-with-video', '[GeminiRealtime] Dropped PCM audio in a turn whose avatar video carries the voice.');
175
+ return;
176
+ }
177
+ this.answering = true;
178
+ this.sinks.OnAnswer();
179
+ this.sinks.OnPcm(pcm);
180
+ }
181
+ reportVideoSeconds() {
182
+ if (this.pendingVideoSeconds <= 0) {
183
+ return;
184
+ }
185
+ const seconds = this.pendingVideoSeconds;
186
+ this.pendingVideoSeconds = 0;
187
+ this.sinks.OnVideoSeconds(seconds);
188
+ }
189
+ reportOnce(key, message) {
190
+ if (!this.reported.has(key)) {
191
+ this.reported.add(key);
192
+ this.sinks.Report(message);
193
+ }
194
+ }
195
+ }
196
+ //# sourceMappingURL=geminiBridgedAvatar.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"geminiBridgedAvatar.js","sourceRoot":"","sources":["../src/geminiBridgedAvatar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AAC,CAAC;IACnC,CAAC;IAED,yHAAyH;IACjH,WAAW,CAAC,GAAgB;QAChC,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACrB,IAAI,CAAC,UAAU,CAAC,gBAAgB,EAAE,oFAAoF,CAAC,CAAC;YACxH,OAAO;QACX,CAAC;QACD,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC1B,CAAC;IAEO,kBAAkB;QACtB,IAAI,IAAI,CAAC,mBAAmB,IAAI,CAAC,EAAE,CAAC;YAChC,OAAO;QACX,CAAC;QACD,MAAM,OAAO,GAAG,IAAI,CAAC,mBAAmB,CAAC;QACzC,IAAI,CAAC,mBAAmB,GAAG,CAAC,CAAC;QAC7B,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC;IAEO,UAAU,CAAC,GAAW,EAAE,OAAe;QAC3C,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC;YAC1B,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YACvB,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAC/B,CAAC;IACL,CAAC;CACJ"}
@@ -24,6 +24,9 @@ export declare class GeminiEmbedding extends BaseEmbeddings {
24
24
  * batch pipelines degrade gracefully instead of aborting. A SUCCESSFUL run is then hard-asserted
25
25
  * to be 1:1 with the inputs and throws on mismatch — so the batch-collapse bug can never again
26
26
  * silently return a short/blended array that downstream code mis-pairs by index.
27
+ *
28
+ * Once `params.CancellationToken` fires, no further text is sent, no retry or backoff continues,
29
+ * and this throws a cancellation error rather than returning the empty result.
27
30
  */
28
31
  EmbedTexts(params: EmbedTextsParams): Promise<EmbedTextsResult>;
29
32
  /**
@@ -37,6 +40,8 @@ export declare class GeminiEmbedding extends BaseEmbeddings {
37
40
  * its failure rate otherwise scales with the text count. Retries {@link maxEmbedTextsRetries}
38
41
  * times, then throws; {@link EmbedTexts} catches that to apply the batch-level empty-result
39
42
  * contract, so a batch never ends up with a silently-corrupt (empty or blended) vector for one text.
43
+ * An aborted `signal` ends the retries: the backoff wait rejects as soon as it fires, and a failure
44
+ * caused by an abort is rethrown rather than retried.
40
45
  */
41
46
  private embedSingleText;
42
47
  /**
@@ -48,6 +53,12 @@ export declare class GeminiEmbedding extends BaseEmbeddings {
48
53
  * consistent with the text methods.
49
54
  */
50
55
  EmbedContent(params: EmbedContentParams): Promise<EmbedContentResult>;
56
+ /**
57
+ * The `config` of an `embedContent` request: the output dimension when one was asked for, and the
58
+ * abort signal, which the SDK forwards to its `fetch` so an abort tears the request down. Spread
59
+ * into the request; empty when there is neither.
60
+ */
61
+ private embedConfig;
51
62
  GetEmbeddingModels(): Promise<EmbeddingModelInfo[]>;
52
63
  }
53
64
  /** Describes an embedding model returned by {@link GeminiEmbedding.GetEmbeddingModels}. */
@@ -1 +1 @@
1
- {"version":3,"file":"geminiEmbedding.d.ts","sourceRoot":"","sources":["../src/geminiEmbedding.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,cAAc,EACd,eAAe,EACf,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAGhB,kBAAkB,EAClB,kBAAkB,EAClB,gBAAgB,EACnB,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,WAAW,EAAW,MAAM,eAAe,CAAC;AAkCrD,qBACa,eAAgB,SAAQ,cAAc;IAC/C,OAAO,CAAC,OAAO,CAAc;gBAEjB,MAAM,EAAE,MAAM;IAK1B,IAAW,YAAY,IAAI,WAAW,CAErC;IAED,4GAA4G;IAC5G,SAAS,KAAK,oBAAoB,IAAI,MAAM,CAE3C;IAED,gGAAgG;IAChG,SAAS,KAAK,qBAAqB,IAAI,MAAM,CAE5C;IAEe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U,UAAU,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAiC5E;;;OAGG;YACW,sBAAsB;IAgCpC;;;;;;;;OAQG;YACW,eAAe;IA8B7B;;;;;;;OAOG;IACmB,YAAY,CAAC,MAAM,EAAE,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IA8B3F;;;;OAIG;IACH,OAAO,CAAC,WAAW;IAQN,kBAAkB,IAAI,OAAO,CAAC,kBAAkB,EAAE,CAAC;CASnE;AAED,2FAA2F;AAC3F,MAAM,WAAW,kBAAkB;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,MAAM,CAAC;CAC3B"}
@@ -7,7 +7,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __metadata = (this && this.__metadata) || function (k, v) {
8
8
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
9
  };
10
- import { BaseEmbeddings, ModelUsage, ErrorAnalyzer, } from '@memberjunction/ai';
10
+ import { BaseEmbeddings, ModelUsage, ErrorAnalyzer, AbortableDelay, IsRequestAborted, ThrowIfAborted, } from '@memberjunction/ai';
11
11
  import { RegisterClass } from '@memberjunction/global';
12
12
  import { GoogleGenAI } from '@google/genai';
13
13
  import { GeminiLLM } from './index.js';
@@ -36,8 +36,6 @@ const DEFAULT_MODEL = 'gemini-embedding-2';
36
36
  * while keeping throughput reasonable.
37
37
  */
38
38
  const EMBED_TEXTS_MAX_CONCURRENCY = 4;
39
- /** Sleep helper for exponential backoff between per-text embed retries. */
40
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
41
39
  let GeminiEmbedding = class GeminiEmbedding extends BaseEmbeddings {
42
40
  constructor(apiKey) {
43
41
  super(apiKey);
@@ -87,7 +85,7 @@ let GeminiEmbedding = class GeminiEmbedding extends BaseEmbeddings {
87
85
  const response = await this._gemini.models.embedContent({
88
86
  model,
89
87
  contents: params.text,
90
- ...(params.dimensions ? { config: { outputDimensionality: params.dimensions } } : {}),
88
+ ...this.embedConfig(params.dimensions, params.CancellationToken),
91
89
  });
92
90
  return {
93
91
  object: 'object',
@@ -97,6 +95,8 @@ let GeminiEmbedding = class GeminiEmbedding extends BaseEmbeddings {
97
95
  };
98
96
  }
99
97
  catch (error) {
98
+ // An aborted request is reported as cancelled, not as an empty (failed) vector.
99
+ this.ThrowIfRequestAborted(error, params.CancellationToken);
100
100
  console.error('Gemini embedding error:', ErrorAnalyzer.analyzeError(error, 'Gemini'));
101
101
  return { object: 'object', model, ModelUsage: new ModelUsage(0, 0), vector: [] };
102
102
  }
@@ -115,15 +115,20 @@ let GeminiEmbedding = class GeminiEmbedding extends BaseEmbeddings {
115
115
  * batch pipelines degrade gracefully instead of aborting. A SUCCESSFUL run is then hard-asserted
116
116
  * to be 1:1 with the inputs and throws on mismatch — so the batch-collapse bug can never again
117
117
  * silently return a short/blended array that downstream code mis-pairs by index.
118
+ *
119
+ * Once `params.CancellationToken` fires, no further text is sent, no retry or backoff continues,
120
+ * and this throws a cancellation error rather than returning the empty result.
118
121
  */
119
122
  async EmbedTexts(params) {
120
123
  const model = params.model || DEFAULT_MODEL;
121
124
  const texts = params.texts ?? [];
122
125
  let vectors;
123
126
  try {
124
- vectors = await this.embedTextsConcurrently(texts, model, EMBED_TEXTS_MAX_CONCURRENCY, params.dimensions);
127
+ vectors = await this.embedTextsConcurrently(texts, model, EMBED_TEXTS_MAX_CONCURRENCY, params.dimensions, params.CancellationToken);
125
128
  }
126
129
  catch (error) {
130
+ // A cancellation is the caller's decision, not a failed batch: it is thrown, not degraded.
131
+ this.ThrowIfRequestAborted(error, params.CancellationToken);
127
132
  // Preserve the original contract: empty result on failure (no throw), so existing
128
133
  // callers that don't wrap EmbedTexts keep degrading gracefully rather than aborting.
129
134
  console.error('Gemini embedding error:', ErrorAnalyzer.analyzeError(error, 'Gemini'));
@@ -146,7 +151,7 @@ let GeminiEmbedding = class GeminiEmbedding extends BaseEmbeddings {
146
151
  * Embeds each text with its own `embedContent` call while capping the number of concurrent
147
152
  * in-flight requests at `maxConcurrency`. Results are returned in the same order as `texts`.
148
153
  */
149
- async embedTextsConcurrently(texts, model, maxConcurrency, dimensions) {
154
+ async embedTextsConcurrently(texts, model, maxConcurrency, dimensions, signal) {
150
155
  const vectors = new Array(texts.length);
151
156
  let nextIndex = 0;
152
157
  let failed = false;
@@ -157,7 +162,8 @@ let GeminiEmbedding = class GeminiEmbedding extends BaseEmbeddings {
157
162
  // embedContent calls after the batch is already doomed to reject.
158
163
  for (let index = nextIndex++; !failed && index < texts.length; index = nextIndex++) {
159
164
  try {
160
- vectors[index] = await this.embedSingleText(texts[index], model, dimensions);
165
+ ThrowIfAborted(signal, 'Gemini'); // a cancelled batch claims no further texts
166
+ vectors[index] = await this.embedSingleText(texts[index], model, dimensions, signal);
161
167
  }
162
168
  catch (error) {
163
169
  failed = true;
@@ -175,18 +181,21 @@ let GeminiEmbedding = class GeminiEmbedding extends BaseEmbeddings {
175
181
  * its failure rate otherwise scales with the text count. Retries {@link maxEmbedTextsRetries}
176
182
  * times, then throws; {@link EmbedTexts} catches that to apply the batch-level empty-result
177
183
  * contract, so a batch never ends up with a silently-corrupt (empty or blended) vector for one text.
184
+ * An aborted `signal` ends the retries: the backoff wait rejects as soon as it fires, and a failure
185
+ * caused by an abort is rethrown rather than retried.
178
186
  */
179
- async embedSingleText(text, model, dimensions) {
187
+ async embedSingleText(text, model, dimensions, signal) {
180
188
  let lastError;
181
189
  for (let n = 0; n <= this.maxEmbedTextsRetries; n++) {
190
+ ThrowIfAborted(signal, 'Gemini');
182
191
  if (n > 0) {
183
- await sleep(this.embedRetryBaseDelayMs * 2 ** (n - 1));
192
+ await AbortableDelay(this.embedRetryBaseDelayMs * 2 ** (n - 1), signal);
184
193
  }
185
194
  try {
186
195
  const response = await this._gemini.models.embedContent({
187
196
  model,
188
197
  contents: text,
189
- ...(dimensions ? { config: { outputDimensionality: dimensions } } : {}),
198
+ ...this.embedConfig(dimensions, signal),
190
199
  });
191
200
  const vector = response.embeddings?.[0]?.values;
192
201
  if (!vector || vector.length === 0) {
@@ -196,7 +205,7 @@ let GeminiEmbedding = class GeminiEmbedding extends BaseEmbeddings {
196
205
  }
197
206
  catch (error) {
198
207
  lastError = error;
199
- if (n >= this.maxEmbedTextsRetries) {
208
+ if (n >= this.maxEmbedTextsRetries || IsRequestAborted(error, signal)) {
200
209
  throw error; // out of retries — let EmbedTexts apply the empty-batch contract
201
210
  }
202
211
  // else: back off and retry
@@ -222,7 +231,7 @@ let GeminiEmbedding = class GeminiEmbedding extends BaseEmbeddings {
222
231
  const response = await this._gemini.models.embedContent({
223
232
  model,
224
233
  contents,
225
- ...(params.dimensions ? { config: { outputDimensionality: params.dimensions } } : {}),
234
+ ...this.embedConfig(params.dimensions, params.CancellationToken),
226
235
  });
227
236
  return {
228
237
  object: 'object',
@@ -232,6 +241,7 @@ let GeminiEmbedding = class GeminiEmbedding extends BaseEmbeddings {
232
241
  };
233
242
  }
234
243
  catch (error) {
244
+ this.ThrowIfRequestAborted(error, params.CancellationToken);
235
245
  console.error('Gemini embedding (content) error:', ErrorAnalyzer.analyzeError(error, 'Gemini'));
236
246
  // design considerations: propagate error in addition to returning an empty vector or throw error from the get-go
237
247
  return {
@@ -242,6 +252,18 @@ let GeminiEmbedding = class GeminiEmbedding extends BaseEmbeddings {
242
252
  };
243
253
  }
244
254
  }
255
+ /**
256
+ * The `config` of an `embedContent` request: the output dimension when one was asked for, and the
257
+ * abort signal, which the SDK forwards to its `fetch` so an abort tears the request down. Spread
258
+ * into the request; empty when there is neither.
259
+ */
260
+ embedConfig(dimensions, signal) {
261
+ const config = {
262
+ ...(dimensions ? { outputDimensionality: dimensions } : {}),
263
+ ...(signal ? { abortSignal: signal } : {}),
264
+ };
265
+ return Object.keys(config).length > 0 ? { config } : {};
266
+ }
245
267
  async GetEmbeddingModels() {
246
268
  return [
247
269
  {