@devvibex/aiflow 1.1.0 → 1.4.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.
- package/README.md +93 -0
- package/package.json +10 -2
- package/src/index.d.ts +254 -1
- package/src/index.js +482 -10
package/README.md
CHANGED
|
@@ -77,6 +77,7 @@ console.log(emb.data[0].embedding.length);
|
|
|
77
77
|
| `defaultVideoModel` | `string` | from `GET /config` | Override. |
|
|
78
78
|
| `defaultAudioModel` | `string` | from `GET /config` | Override (music / Lyria). |
|
|
79
79
|
| `defaultSfxModel` | `string` | from `GET /config` | Override (sound effects / ElevenLabs). |
|
|
80
|
+
| `endUserId` | `string` | `null` | Current end-user id; scopes the knowledge base (`x-end-user-id`). Set/clear later with `setEndUser`. |
|
|
80
81
|
| `timeout` | `number` | `60000` | Per-request timeout (ms). |
|
|
81
82
|
| `maxRetries` | `number` | `2` | Retries on 429 / 5xx / network errors. |
|
|
82
83
|
| `fetch` | `typeof fetch` | `globalThis.fetch` | Custom fetch (Node <18, testing). |
|
|
@@ -151,6 +152,98 @@ repeated UI sounds client-side rather than calling per interaction.
|
|
|
151
152
|
|
|
152
153
|
Returns `{ data: [{ embedding: number[], index }], usage: { creditsUsed } }`.
|
|
153
154
|
|
|
155
|
+
### `aiflow.setEndUser(endUserId)` + `aiflow.knowledge.*` — per-user knowledge base (RAG)
|
|
156
|
+
|
|
157
|
+
Let your app's **end users** upload their own documents; AIFlow vectorizes them
|
|
158
|
+
transparently and **automatically grounds that user's chat answers** in the
|
|
159
|
+
relevant passages. Knowledge is scoped **per end user** — a user only ever
|
|
160
|
+
retrieves their own uploads. You don't implement retrieval/embeddings yourself.
|
|
161
|
+
|
|
162
|
+
```js
|
|
163
|
+
// 1. After your app authenticates a user, identify them (sent as x-end-user-id
|
|
164
|
+
// on every knowledge AND chat call). Pass null on logout.
|
|
165
|
+
aiflow.setEndUser(currentUser.id);
|
|
166
|
+
|
|
167
|
+
// 2. Upload a document the user picked (pdf, docx, txt, csv, md, xlsx, pptx).
|
|
168
|
+
const source = await aiflow.knowledge.ingest(file); // a File/Blob
|
|
169
|
+
// → { id, name, status: 'processing', ... } — vectorizes in the background.
|
|
170
|
+
|
|
171
|
+
// 3. Show the user their library (poll while any is 'processing').
|
|
172
|
+
const mine = await aiflow.knowledge.listMine();
|
|
173
|
+
// → [{ id, name, status: 'ready'|'processing'|'error', chunk_count, error_message? }]
|
|
174
|
+
|
|
175
|
+
// 4. Let them remove one.
|
|
176
|
+
await aiflow.knowledge.deleteMine(source.id); // → { success: true }
|
|
177
|
+
|
|
178
|
+
// 5. Just chat — passages from the user's READY docs are injected automatically.
|
|
179
|
+
const res = await aiflow.chat({ messages: [{ role: 'user', content: '...' }] });
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
> `setEndUser` is **required** before `knowledge.ingest` (uploads are rejected
|
|
183
|
+
> without an end-user id), and chat only grounds in personal docs when it's set.
|
|
184
|
+
> Ingestion is billed to the app owner. Don't tell users their files are
|
|
185
|
+
> "vectorized" — from their view they uploaded a file the assistant can now use.
|
|
186
|
+
|
|
187
|
+
### `aiflow.connectLiveTranslate({ targetLang, sourceLang?, mode?, voice?, echoTargetLanguage?, ...handlers })`
|
|
188
|
+
|
|
189
|
+
Real-time **speech translation** over WebSocket (**Gemini 3.5 Live Translate**,
|
|
190
|
+
routed through the gateway — no Google key in the browser). Stream microphone
|
|
191
|
+
audio in and receive spoken translation + source/target transcripts back, live.
|
|
192
|
+
|
|
193
|
+
> Requires the optional peer dependency `socket.io-client`:
|
|
194
|
+
> `npm i socket.io-client`
|
|
195
|
+
|
|
196
|
+
**Audio-only input** — the translate model does not accept text input. Audio
|
|
197
|
+
formats are fixed by the model: **input** = 16 kHz, 16-bit, mono PCM;
|
|
198
|
+
**output** (`onAudio`) = 24 kHz PCM. The source language is **auto-detected**
|
|
199
|
+
(`sourceLang` is just an optional hint). Mic capture and playback stay in your
|
|
200
|
+
app — the session is transport-only.
|
|
201
|
+
|
|
202
|
+
```js
|
|
203
|
+
const session = await aiflow.connectLiveTranslate({
|
|
204
|
+
targetLang: 'ko', // required — translate INTO this language
|
|
205
|
+
// sourceLang is optional (auto-detected)
|
|
206
|
+
mode: 'speech', // 'speech' (default) → render audio + transcripts; 'text' → transcripts only
|
|
207
|
+
onTranscript: ({ role, text }) => {
|
|
208
|
+
// role: 'input' = what you said, 'output' = the translation
|
|
209
|
+
console.log(role, text);
|
|
210
|
+
},
|
|
211
|
+
onAudio: ({ chunk }) => {
|
|
212
|
+
// base64 24 kHz PCM — decode + queue into a Web Audio buffer to play
|
|
213
|
+
playPcm(chunk);
|
|
214
|
+
},
|
|
215
|
+
onTurnComplete: ({ interrupted }) => {
|
|
216
|
+
if (interrupted) stopPlayback(); // user barged in — drop stale audio
|
|
217
|
+
},
|
|
218
|
+
onError: ({ code, message }) => console.warn(code, message),
|
|
219
|
+
onClosed: ({ reason, usage }) => console.log('closed', reason, usage),
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
// Pump 16 kHz mono PCM frames from the mic (base64 string, ArrayBuffer, or typed array)
|
|
223
|
+
micProcessor.onaudioframe = (pcm) => session.sendAudio(pcm);
|
|
224
|
+
|
|
225
|
+
// When the mic turns off / you're done
|
|
226
|
+
session.audioEnd();
|
|
227
|
+
session.stop();
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
**Modes.** `mode: 'speech'` (default) renders spoken translated audio **and** the
|
|
231
|
+
source/translated transcripts. `mode: 'text'` renders transcripts only
|
|
232
|
+
(captions/subtitles). The model always streams audio + transcripts; the mode is
|
|
233
|
+
a client-side hint for what to render. `echoTargetLanguage` (default `true`)
|
|
234
|
+
controls whether audio is still spoken when the input is already in the target
|
|
235
|
+
language.
|
|
236
|
+
|
|
237
|
+
**Session API:** `start(params?)`, `sendAudio(chunk)`, `audioEnd()`, `stop()`,
|
|
238
|
+
`close()`, and `on(event, cb)` where `event` is one of
|
|
239
|
+
`ready | transcript | audio | turn_complete | error | closed`. (`sendText` exists
|
|
240
|
+
but the translate model rejects text input.)
|
|
241
|
+
|
|
242
|
+
**Billing.** Metered against the project owner's credits per token (audio tokens
|
|
243
|
+
cost more than text), settled periodically and on close. If the balance runs
|
|
244
|
+
out mid-session you'll get `onError({ code: 'INSUFFICIENT_CREDITS' })` and the
|
|
245
|
+
session closes.
|
|
246
|
+
|
|
154
247
|
## Error handling
|
|
155
248
|
|
|
156
249
|
All failures throw `AIFlowError` with `.status`, `.code`, and `.requestId`.
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@devvibex/aiflow",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "First-party LLM gateway SDK for apps generated on the VibeX platform — chat, streaming, image, video, music (Lyria), sound effects (ElevenLabs) and
|
|
3
|
+
"version": "1.4.0",
|
|
4
|
+
"description": "First-party LLM gateway SDK for apps generated on the VibeX platform — chat, streaming, image, video, music (Lyria), sound effects (ElevenLabs), embeddings and real-time speech translation (Gemini Live) without shipping any third-party API key.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
7
7
|
"llm",
|
|
@@ -35,6 +35,14 @@
|
|
|
35
35
|
"engines": {
|
|
36
36
|
"node": ">=18"
|
|
37
37
|
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"socket.io-client": "^4.0.0"
|
|
40
|
+
},
|
|
41
|
+
"peerDependenciesMeta": {
|
|
42
|
+
"socket.io-client": {
|
|
43
|
+
"optional": true
|
|
44
|
+
}
|
|
45
|
+
},
|
|
38
46
|
"sideEffects": false,
|
|
39
47
|
"license": "MIT",
|
|
40
48
|
"repository": {
|
package/src/index.d.ts
CHANGED
|
@@ -162,18 +162,75 @@ export interface ImageBatchResponse {
|
|
|
162
162
|
|
|
163
163
|
export interface VideoRequest {
|
|
164
164
|
prompt: string;
|
|
165
|
+
/**
|
|
166
|
+
* Video model. Defaults to the app's configured default. Veo models
|
|
167
|
+
* (`veo-*`) run on Google Vertex; Seedance/Dreamina
|
|
168
|
+
* (`dreamina-seedance-*`) run on BytePlus Ark.
|
|
169
|
+
*/
|
|
165
170
|
model?: string;
|
|
166
|
-
|
|
171
|
+
/**
|
|
172
|
+
* Output aspect ratio. Veo supports 16:9 / 9:16 / 1:1; Seedance also
|
|
173
|
+
* accepts 4:3 / 3:4 / 21:9 (the server maps unsupported ratios to 16:9).
|
|
174
|
+
*/
|
|
175
|
+
aspectRatio?: '16:9' | '9:16' | '1:1' | '4:3' | '3:4' | '21:9' | string;
|
|
176
|
+
/**
|
|
177
|
+
* Output resolution (Seedance/Dreamina only): '480p' | '720p' | '1080p'.
|
|
178
|
+
* Lower resolution generates faster. Defaults to the app's server-side
|
|
179
|
+
* default (720p) when omitted. Ignored by Veo.
|
|
180
|
+
*/
|
|
181
|
+
resolution?: '480p' | '720p' | '1080p' | string;
|
|
182
|
+
/**
|
|
183
|
+
* Clip length in seconds. Seedance 2.0 supports an integer 4–15 (clamped to
|
|
184
|
+
* that range, default 5). Ignored by Veo, which uses a fixed length per mode.
|
|
185
|
+
*/
|
|
186
|
+
duration?: number;
|
|
187
|
+
/** Burn the provider watermark into the output (Seedance only). */
|
|
188
|
+
watermark?: boolean;
|
|
167
189
|
image?: string;
|
|
168
190
|
video?: string;
|
|
169
191
|
signal?: AbortSignal;
|
|
192
|
+
/**
|
|
193
|
+
* Overall wait budget across all status polls (ms). Defaults to 600000
|
|
194
|
+
* (10 min). `generateVideo` submits a job and polls under the hood — no
|
|
195
|
+
* single request is held open this long.
|
|
196
|
+
*/
|
|
197
|
+
timeout?: number;
|
|
198
|
+
/** Interval between status polls (ms). Defaults to 3000. */
|
|
199
|
+
pollIntervalMs?: number;
|
|
170
200
|
}
|
|
171
201
|
|
|
172
202
|
export interface VideoResponse {
|
|
173
203
|
videoUrl: string;
|
|
204
|
+
thumbnailUrl?: string;
|
|
205
|
+
prompt?: string;
|
|
174
206
|
usage: { creditsUsed: number };
|
|
175
207
|
}
|
|
176
208
|
|
|
209
|
+
export type VideoJobStatus =
|
|
210
|
+
| 'queued'
|
|
211
|
+
| 'processing'
|
|
212
|
+
| 'succeeded'
|
|
213
|
+
| 'failed';
|
|
214
|
+
|
|
215
|
+
/** Acknowledgement returned by {@link AIFlowClient.submitVideoJob}. */
|
|
216
|
+
export interface VideoJobSubmitResponse {
|
|
217
|
+
jobId: string;
|
|
218
|
+
status: 'queued';
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Status returned by {@link AIFlowClient.getVideoJob}. */
|
|
222
|
+
export interface VideoJobStatusResponse {
|
|
223
|
+
jobId: string;
|
|
224
|
+
status: VideoJobStatus;
|
|
225
|
+
/** Present once status === 'succeeded'. */
|
|
226
|
+
videoUrl?: string;
|
|
227
|
+
thumbnailUrl?: string;
|
|
228
|
+
prompt?: string;
|
|
229
|
+
usage?: { creditsUsed: number };
|
|
230
|
+
/** Present once status === 'failed'. */
|
|
231
|
+
error?: string;
|
|
232
|
+
}
|
|
233
|
+
|
|
177
234
|
// ─── Audio (music — Lyria) ──────────────────────────────────────────────────
|
|
178
235
|
|
|
179
236
|
export interface AudioRequest {
|
|
@@ -208,6 +265,13 @@ export interface SfxRequest {
|
|
|
208
265
|
model?: string;
|
|
209
266
|
/** Clip length in seconds (0.5–30). Omit to let the model auto-decide. */
|
|
210
267
|
durationSeconds?: number;
|
|
268
|
+
/**
|
|
269
|
+
* How strictly the output follows the prompt (0–1). Higher = more literal
|
|
270
|
+
* and less variable; lower = more creative/ambient. Omit to use the strict
|
|
271
|
+
* SFX default (0.7) — keeps a concrete prompt (e.g. "clapping") from
|
|
272
|
+
* drifting into a musical/ambient soundscape.
|
|
273
|
+
*/
|
|
274
|
+
promptInfluence?: number;
|
|
211
275
|
signal?: AbortSignal;
|
|
212
276
|
/** Per-call timeout (ms). Defaults to 120000 (2 min). */
|
|
213
277
|
timeout?: number;
|
|
@@ -263,6 +327,158 @@ export interface EmbedResponse {
|
|
|
263
327
|
usage: { creditsUsed: number };
|
|
264
328
|
}
|
|
265
329
|
|
|
330
|
+
// ─── Knowledge base (per-user RAG) ───────────────────────────────────────────
|
|
331
|
+
|
|
332
|
+
export type KnowledgeStatus = 'processing' | 'ready' | 'error';
|
|
333
|
+
|
|
334
|
+
export interface KnowledgeSource {
|
|
335
|
+
id: string;
|
|
336
|
+
name: string;
|
|
337
|
+
status: KnowledgeStatus;
|
|
338
|
+
chunk_count?: number;
|
|
339
|
+
char_count?: number;
|
|
340
|
+
mime_type?: string;
|
|
341
|
+
size_bytes?: number;
|
|
342
|
+
/** Present when `status === 'error'`. */
|
|
343
|
+
error_message?: string;
|
|
344
|
+
source_type?: string;
|
|
345
|
+
created_at?: string;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export interface KnowledgeIngestOptions {
|
|
349
|
+
signal?: AbortSignal;
|
|
350
|
+
/** Per-call timeout (ms). Defaults to 180000 (3 min). */
|
|
351
|
+
timeout?: number;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
export interface KnowledgeRequestOptions {
|
|
355
|
+
signal?: AbortSignal;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Per-user knowledge base (RAG). Documents are uploaded by the app's END USERS,
|
|
360
|
+
* vectorized transparently and scoped to the current end user (set via
|
|
361
|
+
* `setEndUser`). Relevant passages are injected into that user's chat answers
|
|
362
|
+
* automatically — you only upload / list / delete here.
|
|
363
|
+
*/
|
|
364
|
+
export interface KnowledgeNamespace {
|
|
365
|
+
/** Upload a File/Blob (pdf, docx, txt, csv, md, xlsx, pptx) to vectorize. */
|
|
366
|
+
ingest(
|
|
367
|
+
file: Blob | File,
|
|
368
|
+
options?: KnowledgeIngestOptions,
|
|
369
|
+
): Promise<KnowledgeSource>;
|
|
370
|
+
/** List the current end user's own knowledge sources. */
|
|
371
|
+
listMine(options?: KnowledgeRequestOptions): Promise<KnowledgeSource[]>;
|
|
372
|
+
/** Delete one of the current end user's own sources by id. */
|
|
373
|
+
deleteMine(
|
|
374
|
+
id: string,
|
|
375
|
+
options?: KnowledgeRequestOptions,
|
|
376
|
+
): Promise<{ success: boolean }>;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// ─── Live translation ──────────────────────────────────────────────────────
|
|
380
|
+
|
|
381
|
+
export type LiveTranslateMode = 'speech' | 'text';
|
|
382
|
+
|
|
383
|
+
export interface LiveUsage {
|
|
384
|
+
inputTokens: number;
|
|
385
|
+
outputTokens: number;
|
|
386
|
+
audioInputTokens: number;
|
|
387
|
+
audioOutputTokens: number;
|
|
388
|
+
creditsUsed: number;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
export interface LiveReadyPayload {
|
|
392
|
+
sessionId: string;
|
|
393
|
+
model: string;
|
|
394
|
+
mode: LiveTranslateMode;
|
|
395
|
+
sourceLang: string;
|
|
396
|
+
targetLang: string;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
export interface LiveTranscript {
|
|
400
|
+
/** 'input' = recognized source speech; 'output' = translated text. */
|
|
401
|
+
role: 'input' | 'output';
|
|
402
|
+
text: string;
|
|
403
|
+
isFinal: boolean;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
export interface LiveAudioOut {
|
|
407
|
+
/** Base64-encoded PCM audio (24 kHz) of the spoken translation. */
|
|
408
|
+
chunk: string;
|
|
409
|
+
mimeType: string;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
export interface LiveTurnComplete {
|
|
413
|
+
interrupted: boolean;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
export interface LiveError {
|
|
417
|
+
code: string;
|
|
418
|
+
message: string;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
export interface LiveClosed {
|
|
422
|
+
reason: string;
|
|
423
|
+
usage: LiveUsage | null;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
export interface LiveTranslateOptions {
|
|
427
|
+
/** Target language to translate into (e.g. "ko" / "Korean"). Required. */
|
|
428
|
+
targetLang: string;
|
|
429
|
+
/** Source language hint. Optional — Gemini Live Translate auto-detects it. */
|
|
430
|
+
sourceLang?: string;
|
|
431
|
+
/** 'speech' (render audio + transcripts, default) or 'text' (transcripts only). */
|
|
432
|
+
mode?: LiveTranslateMode;
|
|
433
|
+
/** Prebuilt voice name for the spoken translation. */
|
|
434
|
+
voice?: string;
|
|
435
|
+
/** Speak audio even when the input is already in the target language (default true). */
|
|
436
|
+
echoTargetLanguage?: boolean;
|
|
437
|
+
/** Override the WebSocket origin (defaults to the `baseUrl` origin). */
|
|
438
|
+
wsUrl?: string;
|
|
439
|
+
/** Emit `translate:start` automatically on connect. Default true. */
|
|
440
|
+
autoStart?: boolean;
|
|
441
|
+
onReady?: (payload: LiveReadyPayload) => void;
|
|
442
|
+
onTranscript?: (payload: LiveTranscript) => void;
|
|
443
|
+
onAudio?: (payload: LiveAudioOut) => void;
|
|
444
|
+
onTurnComplete?: (payload: LiveTurnComplete) => void;
|
|
445
|
+
onError?: (payload: LiveError) => void;
|
|
446
|
+
onClosed?: (payload: LiveClosed) => void;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
export type LiveTranslateEvent =
|
|
450
|
+
| 'ready'
|
|
451
|
+
| 'transcript'
|
|
452
|
+
| 'audio'
|
|
453
|
+
| 'turn_complete'
|
|
454
|
+
| 'error'
|
|
455
|
+
| 'closed';
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* A real-time translation session. Transport-only — mic capture and audio
|
|
459
|
+
* playback stay in your app. Audio in: 16 kHz, 16-bit, mono PCM. Audio out
|
|
460
|
+
* (`onAudio`): 24 kHz PCM.
|
|
461
|
+
*/
|
|
462
|
+
export class LiveTranslateSession {
|
|
463
|
+
readonly params: LiveTranslateOptions;
|
|
464
|
+
ready: boolean;
|
|
465
|
+
closed: boolean;
|
|
466
|
+
/** (Re)start a translation turn with the configured (or given) params. */
|
|
467
|
+
start(params?: Partial<LiveTranslateOptions>): void;
|
|
468
|
+
/** Push a realtime audio chunk (base64 string, ArrayBuffer, or typed array). */
|
|
469
|
+
sendAudio(chunk: string | ArrayBuffer | ArrayBufferView): void;
|
|
470
|
+
/** Push text to translate (alternative to audio). */
|
|
471
|
+
sendText(text: string): void;
|
|
472
|
+
/** Signal the audio input stream ended (mic off). */
|
|
473
|
+
audioEnd(): void;
|
|
474
|
+
/** Stop the session (settles billing and closes upstream). */
|
|
475
|
+
stop(): void;
|
|
476
|
+
/** Tear down the socket immediately. */
|
|
477
|
+
close(): void;
|
|
478
|
+
/** Subscribe to an event; returns an unsubscribe function. */
|
|
479
|
+
on(event: LiveTranslateEvent, cb: (payload: any) => void): () => void;
|
|
480
|
+
}
|
|
481
|
+
|
|
266
482
|
export interface AIFlowClientOptions {
|
|
267
483
|
appId: string;
|
|
268
484
|
baseUrl: string;
|
|
@@ -273,6 +489,11 @@ export interface AIFlowClientOptions {
|
|
|
273
489
|
defaultVideoModel?: string | null;
|
|
274
490
|
defaultAudioModel?: string | null;
|
|
275
491
|
defaultSfxModel?: string | null;
|
|
492
|
+
/**
|
|
493
|
+
* Current end-user id (the app's logged-in user). Scopes the per-user
|
|
494
|
+
* knowledge base; sent as `x-end-user-id`. Set/clear later with `setEndUser`.
|
|
495
|
+
*/
|
|
496
|
+
endUserId?: string | null;
|
|
276
497
|
timeout?: number;
|
|
277
498
|
maxRetries?: number;
|
|
278
499
|
fetch?: typeof fetch;
|
|
@@ -313,9 +534,21 @@ export class AIFlowClient {
|
|
|
313
534
|
readonly baseUrl: string;
|
|
314
535
|
readonly timeout: number;
|
|
315
536
|
readonly maxRetries: number;
|
|
537
|
+
/** Current end-user id (or null). Set via `setEndUser`. */
|
|
538
|
+
endUserId: string | null;
|
|
539
|
+
/** Per-user knowledge base — upload / list / delete the current user's docs. */
|
|
540
|
+
readonly knowledge: KnowledgeNamespace;
|
|
316
541
|
|
|
317
542
|
constructor(options: AIFlowClientOptions);
|
|
318
543
|
|
|
544
|
+
/**
|
|
545
|
+
* Set (or clear with `null`) the current end user. Call after your app
|
|
546
|
+
* authenticates a user — every subsequent knowledge AND chat call then
|
|
547
|
+
* carries `x-end-user-id`, so the user's own uploaded documents ground their
|
|
548
|
+
* answers. Returns `this` for chaining.
|
|
549
|
+
*/
|
|
550
|
+
setEndUser(endUserId: string | null): this;
|
|
551
|
+
|
|
319
552
|
/**
|
|
320
553
|
* Fetch (and cache) the server-side AIFlow config. Pass `{ refresh: true }`
|
|
321
554
|
* to force a reload.
|
|
@@ -325,11 +558,31 @@ export class AIFlowClient {
|
|
|
325
558
|
chatStream(request: ChatRequest): AsyncGenerator<ChatStreamChunk, void, void>;
|
|
326
559
|
generateImage(request: ImageRequest): Promise<ImageResponse>;
|
|
327
560
|
generateImageBatch(request: ImageBatchRequest): Promise<ImageBatchResponse>;
|
|
561
|
+
/**
|
|
562
|
+
* Generate a video. Submits an async job and polls to completion under the
|
|
563
|
+
* hood (no long-held socket), returning the final result. Use
|
|
564
|
+
* {@link submitVideoJob} + {@link getVideoJob} for manual polling.
|
|
565
|
+
*/
|
|
328
566
|
generateVideo(request: VideoRequest): Promise<VideoResponse>;
|
|
567
|
+
/** Submit an async video job; returns a job id immediately. */
|
|
568
|
+
submitVideoJob(request: VideoRequest): Promise<VideoJobSubmitResponse>;
|
|
569
|
+
/** Poll the status/result of an async video job. */
|
|
570
|
+
getVideoJob(
|
|
571
|
+
jobId: string,
|
|
572
|
+
options?: { signal?: AbortSignal; timeout?: number },
|
|
573
|
+
): Promise<VideoJobStatusResponse>;
|
|
329
574
|
generateAudio(request: AudioRequest): Promise<AudioResponse>;
|
|
330
575
|
generateSfx(request: SfxRequest): Promise<SfxResponse>;
|
|
331
576
|
embed(request: EmbedRequest): Promise<EmbedResponse>;
|
|
332
577
|
vision(request: VisionRequest): Promise<VisionResponse>;
|
|
578
|
+
/**
|
|
579
|
+
* Open a real-time speech-translation session over WebSocket (Gemini Live
|
|
580
|
+
* via the gateway). Requires the optional peer dependency
|
|
581
|
+
* `socket.io-client`. Resolves once connected.
|
|
582
|
+
*/
|
|
583
|
+
connectLiveTranslate(
|
|
584
|
+
options: LiveTranslateOptions,
|
|
585
|
+
): Promise<LiveTranslateSession>;
|
|
333
586
|
}
|
|
334
587
|
|
|
335
588
|
export default AIFlowClient;
|
package/src/index.js
CHANGED
|
@@ -28,6 +28,7 @@ export class AIFlowClient {
|
|
|
28
28
|
* @param {string} options.baseUrl VibeX gateway base URL (e.g. "https://api.vibe-x.io/aiflow").
|
|
29
29
|
* @param {string} [options.defaultModel]
|
|
30
30
|
* @param {string} [options.defaultImageModel]
|
|
31
|
+
* @param {string} [options.endUserId] Current end-user id (the app's logged-in user). Scopes the per-user knowledge base; sent as `x-end-user-id`. Set/clear later with `setEndUser()`.
|
|
31
32
|
* @param {number} [options.timeout] Per-request timeout (ms). Default 60000.
|
|
32
33
|
* @param {number} [options.maxRetries] Retries on 429/5xx / network errors. Default 2.
|
|
33
34
|
* @param {typeof fetch} [options.fetch] Custom fetch implementation.
|
|
@@ -41,6 +42,7 @@ export class AIFlowClient {
|
|
|
41
42
|
defaultVideoModel = null,
|
|
42
43
|
defaultAudioModel = null,
|
|
43
44
|
defaultSfxModel = null,
|
|
45
|
+
endUserId = null,
|
|
44
46
|
timeout = DEFAULT_TIMEOUT_MS,
|
|
45
47
|
maxRetries = DEFAULT_MAX_RETRIES,
|
|
46
48
|
fetch: customFetch,
|
|
@@ -50,6 +52,9 @@ export class AIFlowClient {
|
|
|
50
52
|
|
|
51
53
|
this.appId = appId;
|
|
52
54
|
this.baseUrl = String(baseUrl).replace(/\/+$/, '');
|
|
55
|
+
// Current end user (the app's logged-in user). Scopes the knowledge base
|
|
56
|
+
// so each user only ever sees/retrieves their own uploaded documents.
|
|
57
|
+
this.endUserId = endUserId ? String(endUserId) : null;
|
|
53
58
|
// Caller-provided overrides — win over server-fetched config.
|
|
54
59
|
this._userDefaults = {
|
|
55
60
|
chat: defaultModel,
|
|
@@ -75,6 +80,33 @@ export class AIFlowClient {
|
|
|
75
80
|
// getConfig() / chat() / generateImage() / embed().
|
|
76
81
|
this._config = null;
|
|
77
82
|
this._configPromise = null;
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Per-user knowledge base (RAG). The data is uploaded by the app's END
|
|
86
|
+
* USERS through the app itself, vectorized transparently and scoped to
|
|
87
|
+
* the current end user (set via `setEndUser()`). Retrieval into chat is
|
|
88
|
+
* automatic server-side — you only upload / list / delete here.
|
|
89
|
+
*/
|
|
90
|
+
this.knowledge = {
|
|
91
|
+
/** Upload a File/Blob to vectorize into the current user's knowledge. */
|
|
92
|
+
ingest: (file, opts) => this._knowledgeIngest(file, opts),
|
|
93
|
+
/** List the current user's own knowledge sources. */
|
|
94
|
+
listMine: (opts) => this._knowledgeList(opts),
|
|
95
|
+
/** Delete one of the current user's own knowledge sources by id. */
|
|
96
|
+
deleteMine: (id, opts) => this._knowledgeDelete(id, opts),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Set (or clear) the current end user. Call after your app authenticates a
|
|
102
|
+
* user — every subsequent knowledge AND chat call carries `x-end-user-id`,
|
|
103
|
+
* so the user's own uploaded documents ground their answers. Pass `null` on
|
|
104
|
+
* logout. Returns `this` for chaining.
|
|
105
|
+
* @param {string|null} endUserId
|
|
106
|
+
*/
|
|
107
|
+
setEndUser(endUserId) {
|
|
108
|
+
this.endUserId = endUserId ? String(endUserId) : null;
|
|
109
|
+
return this;
|
|
78
110
|
}
|
|
79
111
|
|
|
80
112
|
/**
|
|
@@ -335,15 +367,48 @@ export class AIFlowClient {
|
|
|
335
367
|
|
|
336
368
|
/**
|
|
337
369
|
* Generate a video from a text prompt.
|
|
338
|
-
*
|
|
370
|
+
*
|
|
371
|
+
* Implemented as SUBMIT + POLL: it submits an async job and polls the
|
|
372
|
+
* gateway for the result, so no single HTTP request is held open for the
|
|
373
|
+
* full (~minutes-long) generation. This avoids the upstream proxy timeout
|
|
374
|
+
* that long synchronous video calls used to hit. The return shape is
|
|
375
|
+
* unchanged from earlier SDK versions, so existing code keeps working.
|
|
376
|
+
*
|
|
377
|
+
* For finer control (e.g. your own polling UI) use {@link submitVideoJob}
|
|
378
|
+
* + {@link getVideoJob} directly.
|
|
379
|
+
*
|
|
380
|
+
* @returns {Promise<{videoUrl:string, thumbnailUrl?:string, prompt?:string, usage:{creditsUsed:number}}>}
|
|
381
|
+
*/
|
|
382
|
+
async generateVideo(opts = {}) {
|
|
383
|
+
if (!opts.prompt || typeof opts.prompt !== 'string') {
|
|
384
|
+
throw new AIFlowError('prompt is required');
|
|
385
|
+
}
|
|
386
|
+
const { jobId } = await this.submitVideoJob(opts);
|
|
387
|
+
return this._pollVideoJob(jobId, {
|
|
388
|
+
signal: opts.signal,
|
|
389
|
+
// Overall wait budget across all polls (default 10 min). Each
|
|
390
|
+
// individual poll is a short request, so the socket is never held.
|
|
391
|
+
timeout: opts.timeout ?? 600_000,
|
|
392
|
+
pollIntervalMs: opts.pollIntervalMs,
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Submit an async video-generation job. Returns immediately with a job id;
|
|
398
|
+
* the heavy generation runs in the background on the gateway.
|
|
399
|
+
* @returns {Promise<{jobId:string, status:'queued'}>}
|
|
339
400
|
*/
|
|
340
|
-
async
|
|
401
|
+
async submitVideoJob({
|
|
341
402
|
prompt,
|
|
342
403
|
model,
|
|
343
404
|
aspectRatio = '16:9',
|
|
405
|
+
resolution,
|
|
406
|
+
duration,
|
|
407
|
+
watermark,
|
|
344
408
|
image,
|
|
345
409
|
video,
|
|
346
410
|
signal,
|
|
411
|
+
timeout,
|
|
347
412
|
} = {}) {
|
|
348
413
|
if (!prompt || typeof prompt !== 'string') {
|
|
349
414
|
throw new AIFlowError('prompt is required');
|
|
@@ -351,19 +416,79 @@ export class AIFlowClient {
|
|
|
351
416
|
const resolvedModel =
|
|
352
417
|
model || (await this._resolveDefaultModel('video'));
|
|
353
418
|
const res = await this._request(
|
|
354
|
-
'/video',
|
|
419
|
+
'/video/jobs',
|
|
355
420
|
{
|
|
356
421
|
model: resolvedModel,
|
|
357
422
|
prompt,
|
|
358
423
|
aspectRatio,
|
|
424
|
+
resolution,
|
|
425
|
+
duration,
|
|
426
|
+
watermark,
|
|
359
427
|
image,
|
|
360
428
|
video,
|
|
361
429
|
},
|
|
362
|
-
|
|
430
|
+
// Submit returns fast; the default client timeout is plenty even
|
|
431
|
+
// when an image-to-video request uploads a base64 first frame.
|
|
432
|
+
{ signal, timeout: timeout ?? DEFAULT_TIMEOUT_MS },
|
|
433
|
+
);
|
|
434
|
+
return await res.json();
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Fetch the current status of an async video job.
|
|
439
|
+
* @returns {Promise<{jobId:string, status:'queued'|'processing'|'succeeded'|'failed', videoUrl?:string, thumbnailUrl?:string, prompt?:string, usage?:{creditsUsed:number}, error?:string}>}
|
|
440
|
+
*/
|
|
441
|
+
async getVideoJob(jobId, { signal, timeout } = {}) {
|
|
442
|
+
if (!jobId || typeof jobId !== 'string') {
|
|
443
|
+
throw new AIFlowError('jobId is required');
|
|
444
|
+
}
|
|
445
|
+
const res = await this._get(
|
|
446
|
+
`/video/jobs/${encodeURIComponent(jobId)}`,
|
|
447
|
+
{ signal, timeout: timeout ?? DEFAULT_TIMEOUT_MS },
|
|
363
448
|
);
|
|
364
449
|
return await res.json();
|
|
365
450
|
}
|
|
366
451
|
|
|
452
|
+
/** Poll a video job to completion and normalise the success payload. */
|
|
453
|
+
async _pollVideoJob(
|
|
454
|
+
jobId,
|
|
455
|
+
{ signal, timeout = 600_000, pollIntervalMs = 3_000 } = {},
|
|
456
|
+
) {
|
|
457
|
+
const deadline = Date.now() + timeout;
|
|
458
|
+
// eslint-disable-next-line no-constant-condition
|
|
459
|
+
while (true) {
|
|
460
|
+
if (signal?.aborted) {
|
|
461
|
+
throw new AIFlowError('Video generation aborted', {
|
|
462
|
+
code: 'aborted',
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
const job = await this.getVideoJob(jobId, { signal });
|
|
466
|
+
if (job.status === 'succeeded') {
|
|
467
|
+
return {
|
|
468
|
+
videoUrl: job.videoUrl,
|
|
469
|
+
thumbnailUrl: job.thumbnailUrl,
|
|
470
|
+
prompt: job.prompt,
|
|
471
|
+
usage: job.usage || { creditsUsed: 0 },
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
if (job.status === 'failed') {
|
|
475
|
+
throw new AIFlowError(
|
|
476
|
+
job.error || 'Video generation failed',
|
|
477
|
+
{ code: 'video_failed' },
|
|
478
|
+
);
|
|
479
|
+
}
|
|
480
|
+
if (Date.now() >= deadline) {
|
|
481
|
+
throw new AIFlowError(
|
|
482
|
+
`Video generation timed out after ${Math.round(
|
|
483
|
+
timeout / 1000,
|
|
484
|
+
)}s`,
|
|
485
|
+
{ code: 'timeout' },
|
|
486
|
+
);
|
|
487
|
+
}
|
|
488
|
+
await sleep(pollIntervalMs);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
367
492
|
/**
|
|
368
493
|
* Generate music / background audio from a text prompt (Lyria).
|
|
369
494
|
* @returns {Promise<{audioUrl:string, model:string, durationSeconds:number|null, prompt?:string, usage:{creditsUsed:number}}>}
|
|
@@ -404,6 +529,7 @@ export class AIFlowClient {
|
|
|
404
529
|
prompt,
|
|
405
530
|
model,
|
|
406
531
|
durationSeconds,
|
|
532
|
+
promptInfluence,
|
|
407
533
|
signal,
|
|
408
534
|
timeout,
|
|
409
535
|
} = {}) {
|
|
@@ -417,6 +543,7 @@ export class AIFlowClient {
|
|
|
417
543
|
model: resolvedModel,
|
|
418
544
|
prompt,
|
|
419
545
|
durationSeconds,
|
|
546
|
+
promptInfluence,
|
|
420
547
|
},
|
|
421
548
|
{ signal, timeout: timeout ?? 120_000 },
|
|
422
549
|
);
|
|
@@ -468,17 +595,130 @@ export class AIFlowClient {
|
|
|
468
595
|
return await res.json();
|
|
469
596
|
}
|
|
470
597
|
|
|
598
|
+
/**
|
|
599
|
+
* Open a real-time speech-translation session over WebSocket (Gemini Live
|
|
600
|
+
* via the platform gateway — no Google key in the browser). Stream 16 kHz
|
|
601
|
+
* 16-bit mono PCM audio in; receive translated audio (24 kHz PCM) and
|
|
602
|
+
* source/target transcripts back.
|
|
603
|
+
*
|
|
604
|
+
* Requires the optional peer dependency `socket.io-client`.
|
|
605
|
+
*
|
|
606
|
+
* Input is AUDIO ONLY — text input is not supported by the translate model.
|
|
607
|
+
*
|
|
608
|
+
* @param {object} opts
|
|
609
|
+
* @param {string} opts.targetLang Target language to translate into (e.g. "ko" / "Korean"). Required.
|
|
610
|
+
* @param {string} [opts.sourceLang] Source language hint. Optional — the model auto-detects.
|
|
611
|
+
* @param {'speech'|'text'} [opts.mode] 'speech' (render audio + transcripts, default) or 'text' (transcripts only).
|
|
612
|
+
* @param {string} [opts.voice] Prebuilt voice for the spoken translation.
|
|
613
|
+
* @param {boolean} [opts.echoTargetLanguage] Speak audio even when input is already in the target language (default true).
|
|
614
|
+
* @param {string} [opts.wsUrl] Override the ws origin (defaults to baseUrl's origin).
|
|
615
|
+
* @param {boolean} [opts.autoStart] Send `translate:start` automatically on connect (default true).
|
|
616
|
+
* @param {(p:object)=>void} [opts.onReady]
|
|
617
|
+
* @param {(p:{role:'input'|'output',text:string,isFinal:boolean})=>void} [opts.onTranscript]
|
|
618
|
+
* @param {(p:{chunk:string,mimeType:string})=>void} [opts.onAudio]
|
|
619
|
+
* @param {(p:{interrupted:boolean})=>void} [opts.onTurnComplete]
|
|
620
|
+
* @param {(p:{code:string,message:string})=>void} [opts.onError]
|
|
621
|
+
* @param {(p:{reason:string,usage:object})=>void} [opts.onClosed]
|
|
622
|
+
* @returns {Promise<LiveTranslateSession>} Resolves once connected.
|
|
623
|
+
*/
|
|
624
|
+
async connectLiveTranslate({
|
|
625
|
+
targetLang,
|
|
626
|
+
sourceLang,
|
|
627
|
+
mode,
|
|
628
|
+
voice,
|
|
629
|
+
echoTargetLanguage,
|
|
630
|
+
wsUrl,
|
|
631
|
+
autoStart = true,
|
|
632
|
+
onReady,
|
|
633
|
+
onTranscript,
|
|
634
|
+
onAudio,
|
|
635
|
+
onTurnComplete,
|
|
636
|
+
onError,
|
|
637
|
+
onClosed,
|
|
638
|
+
} = {}) {
|
|
639
|
+
if (!targetLang) {
|
|
640
|
+
throw new AIFlowError(
|
|
641
|
+
'connectLiveTranslate requires targetLang',
|
|
642
|
+
);
|
|
643
|
+
}
|
|
644
|
+
const io = await loadSocketIoClient();
|
|
645
|
+
let origin = wsUrl;
|
|
646
|
+
if (!origin) {
|
|
647
|
+
try {
|
|
648
|
+
origin = new URL(this.baseUrl).origin;
|
|
649
|
+
} catch {
|
|
650
|
+
throw new AIFlowError(
|
|
651
|
+
'Could not derive the WebSocket origin from baseUrl — pass opts.wsUrl.',
|
|
652
|
+
);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
const session = new LiveTranslateSession({
|
|
656
|
+
io,
|
|
657
|
+
origin,
|
|
658
|
+
appId: this.appId,
|
|
659
|
+
params: { targetLang, sourceLang, mode, voice, echoTargetLanguage },
|
|
660
|
+
autoStart,
|
|
661
|
+
handlers: {
|
|
662
|
+
onReady,
|
|
663
|
+
onTranscript,
|
|
664
|
+
onAudio,
|
|
665
|
+
onTurnComplete,
|
|
666
|
+
onError,
|
|
667
|
+
onClosed,
|
|
668
|
+
},
|
|
669
|
+
});
|
|
670
|
+
await session._connect();
|
|
671
|
+
return session;
|
|
672
|
+
}
|
|
673
|
+
|
|
471
674
|
// ────────────────────────────────────────────────────────────────────────
|
|
472
675
|
// Internals
|
|
473
676
|
// ────────────────────────────────────────────────────────────────────────
|
|
474
677
|
|
|
678
|
+
/**
|
|
679
|
+
* Auth/identity headers attached to every gateway call: the public app id
|
|
680
|
+
* and (when set) the current end-user id that scopes the knowledge base.
|
|
681
|
+
*/
|
|
682
|
+
_authHeaders() {
|
|
683
|
+
const h = { 'x-app-id': this.appId };
|
|
684
|
+
if (this.endUserId) h['x-end-user-id'] = this.endUserId;
|
|
685
|
+
return h;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/** POST a JSON body to the gateway. */
|
|
475
689
|
async _request(path, body, { signal, stream = false, timeout } = {}) {
|
|
476
|
-
const url = `${this.baseUrl}${path}`;
|
|
477
690
|
const headers = {
|
|
478
691
|
'Content-Type': 'application/json',
|
|
479
|
-
|
|
692
|
+
...this._authHeaders(),
|
|
480
693
|
Accept: stream ? 'text/event-stream' : 'application/json',
|
|
481
694
|
};
|
|
695
|
+
return this._fetchWithRetry(
|
|
696
|
+
`${this.baseUrl}${path}`,
|
|
697
|
+
{ method: 'POST', headers, body: JSON.stringify(body) },
|
|
698
|
+
{ signal, timeout },
|
|
699
|
+
);
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/** GET from the gateway (used by short status polls). */
|
|
703
|
+
async _get(path, { signal, timeout } = {}) {
|
|
704
|
+
return this._fetchWithRetry(
|
|
705
|
+
`${this.baseUrl}${path}`,
|
|
706
|
+
{
|
|
707
|
+
method: 'GET',
|
|
708
|
+
headers: {
|
|
709
|
+
...this._authHeaders(),
|
|
710
|
+
Accept: 'application/json',
|
|
711
|
+
},
|
|
712
|
+
},
|
|
713
|
+
{ signal, timeout },
|
|
714
|
+
);
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/**
|
|
718
|
+
* Send a request with timeout + retry (429/5xx + network errors). `init`
|
|
719
|
+
* carries method/headers/body; the abort signal is composed per attempt.
|
|
720
|
+
*/
|
|
721
|
+
async _fetchWithRetry(url, init, { signal, timeout } = {}) {
|
|
482
722
|
// Per-call timeout override — image/video calls run far longer than the
|
|
483
723
|
// 60s client default, so they pass a larger value here.
|
|
484
724
|
const effectiveTimeout = timeout ?? this.timeout;
|
|
@@ -495,9 +735,7 @@ export class AIFlowClient {
|
|
|
495
735
|
let res;
|
|
496
736
|
try {
|
|
497
737
|
res = await this._fetch(url, {
|
|
498
|
-
|
|
499
|
-
headers,
|
|
500
|
-
body: JSON.stringify(body),
|
|
738
|
+
...init,
|
|
501
739
|
signal: composedSignal,
|
|
502
740
|
});
|
|
503
741
|
} catch (err) {
|
|
@@ -509,7 +747,7 @@ export class AIFlowClient {
|
|
|
509
747
|
continue;
|
|
510
748
|
}
|
|
511
749
|
throw new AIFlowError(
|
|
512
|
-
`Network error calling ${
|
|
750
|
+
`Network error calling ${url}: ${err?.message || err}`,
|
|
513
751
|
{ cause: err },
|
|
514
752
|
);
|
|
515
753
|
}
|
|
@@ -539,6 +777,240 @@ export class AIFlowClient {
|
|
|
539
777
|
return res;
|
|
540
778
|
}
|
|
541
779
|
}
|
|
780
|
+
|
|
781
|
+
// ────────────────────────────────────────────────────────────────────────
|
|
782
|
+
// Knowledge base (per-user RAG) internals
|
|
783
|
+
// ────────────────────────────────────────────────────────────────────────
|
|
784
|
+
|
|
785
|
+
async _knowledgeIngest(file, { signal, timeout } = {}) {
|
|
786
|
+
if (!file) {
|
|
787
|
+
throw new AIFlowError('a File/Blob is required to ingest knowledge');
|
|
788
|
+
}
|
|
789
|
+
if (!this.endUserId) {
|
|
790
|
+
throw new AIFlowError(
|
|
791
|
+
'setEndUser(id) must be called before uploading knowledge',
|
|
792
|
+
);
|
|
793
|
+
}
|
|
794
|
+
if (typeof FormData === 'undefined') {
|
|
795
|
+
throw new AIFlowError(
|
|
796
|
+
'FormData is not available in this environment — knowledge upload needs a browser or Node 18+ with global FormData.',
|
|
797
|
+
);
|
|
798
|
+
}
|
|
799
|
+
const form = new FormData();
|
|
800
|
+
// Field name is irrelevant — the gateway accepts any (multer().any()).
|
|
801
|
+
form.append('file', file, file.name || 'document');
|
|
802
|
+
// NO Content-Type header — fetch sets the multipart boundary itself.
|
|
803
|
+
const res = await this._fetchWithRetry(
|
|
804
|
+
`${this.baseUrl}/knowledge/ingest`,
|
|
805
|
+
{ method: 'POST', headers: this._authHeaders(), body: form },
|
|
806
|
+
// Extracting + embedding a large doc can run long; the server does it
|
|
807
|
+
// in the background but the upload itself may still take a while.
|
|
808
|
+
{ signal, timeout: timeout ?? 180_000 },
|
|
809
|
+
);
|
|
810
|
+
return await res.json();
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
async _knowledgeList({ signal } = {}) {
|
|
814
|
+
const res = await this._fetchWithRetry(
|
|
815
|
+
`${this.baseUrl}/knowledge/sources`,
|
|
816
|
+
{
|
|
817
|
+
method: 'GET',
|
|
818
|
+
headers: { Accept: 'application/json', ...this._authHeaders() },
|
|
819
|
+
},
|
|
820
|
+
{ signal },
|
|
821
|
+
);
|
|
822
|
+
return await res.json();
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
async _knowledgeDelete(id, { signal } = {}) {
|
|
826
|
+
if (!id) throw new AIFlowError('a source id is required');
|
|
827
|
+
const res = await this._fetchWithRetry(
|
|
828
|
+
`${this.baseUrl}/knowledge/sources/${encodeURIComponent(id)}`,
|
|
829
|
+
{
|
|
830
|
+
method: 'DELETE',
|
|
831
|
+
headers: { Accept: 'application/json', ...this._authHeaders() },
|
|
832
|
+
},
|
|
833
|
+
{ signal },
|
|
834
|
+
);
|
|
835
|
+
return await res.json();
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
840
|
+
// Live translation
|
|
841
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
842
|
+
|
|
843
|
+
/**
|
|
844
|
+
* A real-time translation session. Created via
|
|
845
|
+
* `AIFlowClient.connectLiveTranslate(...)`. Transport-only: mic capture and
|
|
846
|
+
* audio playback stay in your app. Audio in must be 16 kHz, 16-bit, mono PCM;
|
|
847
|
+
* audio out (`onAudio`) is 24 kHz PCM.
|
|
848
|
+
*/
|
|
849
|
+
export class LiveTranslateSession {
|
|
850
|
+
constructor({ io, origin, appId, params, autoStart, handlers }) {
|
|
851
|
+
this._io = io;
|
|
852
|
+
this._origin = String(origin).replace(/\/+$/, '');
|
|
853
|
+
this._appId = appId;
|
|
854
|
+
this.params = params;
|
|
855
|
+
this._autoStart = autoStart;
|
|
856
|
+
this._handlers = handlers || {};
|
|
857
|
+
this._listeners = new Map();
|
|
858
|
+
this.socket = null;
|
|
859
|
+
this.ready = false;
|
|
860
|
+
this.closed = false;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
async _connect() {
|
|
864
|
+
this.socket = this._io(`${this._origin}/aiflow-live`, {
|
|
865
|
+
path: '/ws',
|
|
866
|
+
transports: ['websocket'],
|
|
867
|
+
auth: { appId: this._appId },
|
|
868
|
+
});
|
|
869
|
+
|
|
870
|
+
const fwd = (event, cb) =>
|
|
871
|
+
this.socket.on(event, (payload) => {
|
|
872
|
+
cb?.(payload);
|
|
873
|
+
this._emit(event, payload);
|
|
874
|
+
});
|
|
875
|
+
|
|
876
|
+
this.socket.on('translate:ready', (p) => {
|
|
877
|
+
this.ready = true;
|
|
878
|
+
this._handlers.onReady?.(p);
|
|
879
|
+
this._emit('ready', p);
|
|
880
|
+
});
|
|
881
|
+
fwd('translate:transcript', this._handlers.onTranscript);
|
|
882
|
+
fwd('translate:audio', this._handlers.onAudio);
|
|
883
|
+
fwd('translate:turn_complete', this._handlers.onTurnComplete);
|
|
884
|
+
fwd('translate:error', this._handlers.onError);
|
|
885
|
+
this.socket.on('translate:closed', (p) => {
|
|
886
|
+
this.closed = true;
|
|
887
|
+
this._handlers.onClosed?.(p);
|
|
888
|
+
this._emit('closed', p);
|
|
889
|
+
});
|
|
890
|
+
|
|
891
|
+
await new Promise((resolve, reject) => {
|
|
892
|
+
const timer = setTimeout(
|
|
893
|
+
() =>
|
|
894
|
+
reject(
|
|
895
|
+
new AIFlowError('AIFlow Live connection timed out'),
|
|
896
|
+
),
|
|
897
|
+
15_000,
|
|
898
|
+
);
|
|
899
|
+
this.socket.once('connect', () => {
|
|
900
|
+
clearTimeout(timer);
|
|
901
|
+
resolve();
|
|
902
|
+
});
|
|
903
|
+
this.socket.once('connect_error', (err) => {
|
|
904
|
+
clearTimeout(timer);
|
|
905
|
+
reject(
|
|
906
|
+
new AIFlowError(
|
|
907
|
+
`AIFlow Live connection failed: ${err?.message || err}`,
|
|
908
|
+
{ cause: err },
|
|
909
|
+
),
|
|
910
|
+
);
|
|
911
|
+
});
|
|
912
|
+
});
|
|
913
|
+
|
|
914
|
+
if (this._autoStart) this.start();
|
|
915
|
+
return this;
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
/** (Re)start the translation turn with the configured params. */
|
|
919
|
+
start(params) {
|
|
920
|
+
this.socket?.emit('translate:start', params || this.params);
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
/**
|
|
924
|
+
* Push a realtime audio chunk. Accepts a base64 string, an ArrayBuffer, or
|
|
925
|
+
* a typed array of 16 kHz 16-bit mono PCM.
|
|
926
|
+
*/
|
|
927
|
+
sendAudio(chunk) {
|
|
928
|
+
this.socket?.emit('translate:audio', { chunk: toBase64(chunk) });
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
/** Push text to translate (alternative to audio). */
|
|
932
|
+
sendText(text) {
|
|
933
|
+
this.socket?.emit('translate:text', { text });
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/** Signal that the audio input stream ended (mic off). */
|
|
937
|
+
audioEnd() {
|
|
938
|
+
this.socket?.emit('translate:audio_end');
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
/** Stop the session (settles billing and closes upstream). */
|
|
942
|
+
stop() {
|
|
943
|
+
this.socket?.emit('translate:stop');
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
/** Tear down the socket immediately. */
|
|
947
|
+
close() {
|
|
948
|
+
try {
|
|
949
|
+
this.socket?.close();
|
|
950
|
+
} catch {
|
|
951
|
+
/* noop */
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
/** Subscribe to an event ('ready'|'transcript'|'audio'|'turn_complete'|'error'|'closed' or the raw `translate:*`). */
|
|
956
|
+
on(event, cb) {
|
|
957
|
+
const key = event.startsWith('translate:')
|
|
958
|
+
? event.slice('translate:'.length)
|
|
959
|
+
: event;
|
|
960
|
+
if (!this._listeners.has(key)) this._listeners.set(key, new Set());
|
|
961
|
+
this._listeners.get(key).add(cb);
|
|
962
|
+
return () => this._listeners.get(key)?.delete(cb);
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
_emit(event, payload) {
|
|
966
|
+
const key = event.startsWith('translate:')
|
|
967
|
+
? event.slice('translate:'.length)
|
|
968
|
+
: event;
|
|
969
|
+
const set = this._listeners.get(key);
|
|
970
|
+
if (set) for (const cb of set) cb(payload);
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
async function loadSocketIoClient() {
|
|
975
|
+
try {
|
|
976
|
+
const mod = await import('socket.io-client');
|
|
977
|
+
return mod.io || mod.default?.io || mod.default;
|
|
978
|
+
} catch (err) {
|
|
979
|
+
throw new AIFlowError(
|
|
980
|
+
'socket.io-client is required for live translation — install it: npm i socket.io-client',
|
|
981
|
+
{ cause: err },
|
|
982
|
+
);
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
function toBase64(chunk) {
|
|
987
|
+
if (typeof chunk === 'string') return chunk; // assume already base64
|
|
988
|
+
let bytes;
|
|
989
|
+
if (chunk instanceof Uint8Array) bytes = chunk;
|
|
990
|
+
else if (chunk instanceof ArrayBuffer) bytes = new Uint8Array(chunk);
|
|
991
|
+
else if (ArrayBuffer.isView(chunk))
|
|
992
|
+
bytes = new Uint8Array(
|
|
993
|
+
chunk.buffer,
|
|
994
|
+
chunk.byteOffset,
|
|
995
|
+
chunk.byteLength,
|
|
996
|
+
);
|
|
997
|
+
else
|
|
998
|
+
throw new AIFlowError(
|
|
999
|
+
'sendAudio expects a base64 string, ArrayBuffer, or typed array',
|
|
1000
|
+
);
|
|
1001
|
+
|
|
1002
|
+
if (typeof btoa === 'function') {
|
|
1003
|
+
let bin = '';
|
|
1004
|
+
const CHUNK = 0x8000;
|
|
1005
|
+
for (let i = 0; i < bytes.length; i += CHUNK) {
|
|
1006
|
+
bin += String.fromCharCode.apply(
|
|
1007
|
+
null,
|
|
1008
|
+
bytes.subarray(i, i + CHUNK),
|
|
1009
|
+
);
|
|
1010
|
+
}
|
|
1011
|
+
return btoa(bin);
|
|
1012
|
+
}
|
|
1013
|
+
return Buffer.from(bytes).toString('base64');
|
|
542
1014
|
}
|
|
543
1015
|
|
|
544
1016
|
// ────────────────────────────────────────────────────────────────────────────
|