@devvibex/aiflow 1.0.9 → 1.3.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 +129 -4
- package/package.json +14 -2
- package/src/index.d.ts +262 -1
- package/src/index.js +444 -7
package/README.md
CHANGED
|
@@ -74,6 +74,10 @@ console.log(emb.data[0].embedding.length);
|
|
|
74
74
|
| `defaultModel` | `string` | from `GET /config` | Override — wins over server config. |
|
|
75
75
|
| `defaultImageModel` | `string` | from `GET /config` | Override. |
|
|
76
76
|
| `defaultEmbedModel` | `string` | from `GET /config` | Override. |
|
|
77
|
+
| `defaultVideoModel` | `string` | from `GET /config` | Override. |
|
|
78
|
+
| `defaultAudioModel` | `string` | from `GET /config` | Override (music / Lyria). |
|
|
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`. |
|
|
77
81
|
| `timeout` | `number` | `60000` | Per-request timeout (ms). |
|
|
78
82
|
| `maxRetries` | `number` | `2` | Retries on 429 / 5xx / network errors. |
|
|
79
83
|
| `fetch` | `typeof fetch` | `globalThis.fetch` | Custom fetch (Node <18, testing). |
|
|
@@ -94,9 +98,18 @@ to invalidate the cache.
|
|
|
94
98
|
chat: string[], // e.g. ["claude-sonnet-4-6", "gpt-4o", ...]
|
|
95
99
|
image: string[],
|
|
96
100
|
embed: string[],
|
|
101
|
+
video: string[],
|
|
102
|
+
audio: string[], // Lyria — e.g. ["lyria-3-clip-preview", ...]
|
|
103
|
+
sfx: string[], // ElevenLabs — e.g. ["eleven_text_to_sound_v2"]
|
|
104
|
+
},
|
|
105
|
+
defaults: { chat: string, image: string, embed: string, video: string, audio: string, sfx: string },
|
|
106
|
+
limits: {
|
|
107
|
+
maxTokens: number,
|
|
108
|
+
maxImageN: number,
|
|
109
|
+
maxEmbedInputs: number,
|
|
110
|
+
minSfxDurationSeconds: number,
|
|
111
|
+
maxSfxDurationSeconds: number,
|
|
97
112
|
},
|
|
98
|
-
defaults: { chat: string, image: string, embed: string },
|
|
99
|
-
limits: { maxTokens: number, maxImageN: number, maxEmbedInputs: number },
|
|
100
113
|
creditValue: number,
|
|
101
114
|
}
|
|
102
115
|
```
|
|
@@ -110,15 +123,127 @@ Returns `Promise<{ id, model, content, usage: { inputTokens, outputTokens, credi
|
|
|
110
123
|
Async iterable of `{ delta: string, done: boolean }` chunks. The final chunk
|
|
111
124
|
has `done: true` and carries the cumulative `usage` object.
|
|
112
125
|
|
|
113
|
-
### `aiflow.generateImage({ prompt, model?, size?, n?, signal? })`
|
|
126
|
+
### `aiflow.generateImage({ prompt, model?, size?, n?, image?, images?, system?, language?, signal? })`
|
|
114
127
|
|
|
115
128
|
Returns `{ images: [{ url?, b64?, mimeType }], usage: { creditsUsed } }`.
|
|
116
|
-
`url` is a short-lived signed URL (~1h).
|
|
129
|
+
`url` is a short-lived signed URL (~1h). Pass `image`/`images` to edit an
|
|
130
|
+
existing image (image-to-image) instead of generating from text.
|
|
131
|
+
|
|
132
|
+
### `aiflow.generateVideo({ prompt, model?, aspectRatio?, image?, video?, signal? })`
|
|
133
|
+
|
|
134
|
+
Returns `{ videoUrl, usage: { creditsUsed } }`. Pass `image` for image-to-video
|
|
135
|
+
or `video` for video-to-video; omit both for pure text-to-video.
|
|
136
|
+
|
|
137
|
+
### `aiflow.generateAudio({ prompt, model?, negativePrompt?, seed?, signal?, timeout? })`
|
|
138
|
+
|
|
139
|
+
Generate music / background audio from a text prompt (Google Vertex AI **Lyria**).
|
|
140
|
+
Returns `{ audioUrl, model, durationSeconds, usage: { creditsUsed } }`. `audioUrl`
|
|
141
|
+
is a hosted mp3/wav on the CDN. `prompt` should be a musical description (mood,
|
|
142
|
+
genre, tempo/BPM, instrumentation). `negativePrompt`/`seed` apply to Lyria 2 only.
|
|
143
|
+
|
|
144
|
+
### `aiflow.generateSfx({ prompt, model?, durationSeconds?, signal?, timeout? })`
|
|
145
|
+
|
|
146
|
+
Generate a one-shot sound effect from a text prompt (**ElevenLabs**). Returns
|
|
147
|
+
`{ audioUrl, model, durationSeconds, usage: { creditsUsed } }`. `durationSeconds`
|
|
148
|
+
is clamped to `0.5–30`; omit it to let the model auto-decide. Cache/replay
|
|
149
|
+
repeated UI sounds client-side rather than calling per interaction.
|
|
117
150
|
|
|
118
151
|
### `aiflow.embed({ input, model?, signal? })`
|
|
119
152
|
|
|
120
153
|
Returns `{ data: [{ embedding: number[], index }], usage: { creditsUsed } }`.
|
|
121
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
|
+
|
|
122
247
|
## Error handling
|
|
123
248
|
|
|
124
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.0
|
|
4
|
-
"description": "First-party LLM gateway SDK for apps generated on the VibeX platform — chat, streaming, image
|
|
3
|
+
"version": "1.3.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",
|
|
@@ -9,6 +9,10 @@
|
|
|
9
9
|
"claude",
|
|
10
10
|
"gpt",
|
|
11
11
|
"gemini",
|
|
12
|
+
"lyria",
|
|
13
|
+
"elevenlabs",
|
|
14
|
+
"music-generation",
|
|
15
|
+
"sound-effects",
|
|
12
16
|
"vibex",
|
|
13
17
|
"aiflow"
|
|
14
18
|
],
|
|
@@ -31,6 +35,14 @@
|
|
|
31
35
|
"engines": {
|
|
32
36
|
"node": ">=18"
|
|
33
37
|
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"socket.io-client": "^4.0.0"
|
|
40
|
+
},
|
|
41
|
+
"peerDependenciesMeta": {
|
|
42
|
+
"socket.io-client": {
|
|
43
|
+
"optional": true
|
|
44
|
+
}
|
|
45
|
+
},
|
|
34
46
|
"sideEffects": false,
|
|
35
47
|
"license": "MIT",
|
|
36
48
|
"repository": {
|
package/src/index.d.ts
CHANGED
|
@@ -162,11 +162,29 @@ 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
|
+
* Clip length in seconds. Seedance 2.0 supports an integer 4–15 (clamped to
|
|
178
|
+
* that range, default 5). Ignored by Veo, which uses a fixed length per mode.
|
|
179
|
+
*/
|
|
180
|
+
duration?: number;
|
|
181
|
+
/** Burn the provider watermark into the output (Seedance only). */
|
|
182
|
+
watermark?: boolean;
|
|
167
183
|
image?: string;
|
|
168
184
|
video?: string;
|
|
169
185
|
signal?: AbortSignal;
|
|
186
|
+
/** Per-request timeout (ms). Defaults to 600000 (10 min). */
|
|
187
|
+
timeout?: number;
|
|
170
188
|
}
|
|
171
189
|
|
|
172
190
|
export interface VideoResponse {
|
|
@@ -174,6 +192,62 @@ export interface VideoResponse {
|
|
|
174
192
|
usage: { creditsUsed: number };
|
|
175
193
|
}
|
|
176
194
|
|
|
195
|
+
// ─── Audio (music — Lyria) ──────────────────────────────────────────────────
|
|
196
|
+
|
|
197
|
+
export interface AudioRequest {
|
|
198
|
+
/** Musical description — mood, genre, tempo (BPM), instrumentation, texture. */
|
|
199
|
+
prompt: string;
|
|
200
|
+
model?: string;
|
|
201
|
+
/** Things to steer away from. Lyria 2 only — ignored by Lyria 3. */
|
|
202
|
+
negativePrompt?: string;
|
|
203
|
+
/** Deterministic seed (Lyria 2 only). */
|
|
204
|
+
seed?: number;
|
|
205
|
+
signal?: AbortSignal;
|
|
206
|
+
/** Per-call timeout (ms). Defaults to 180000 (3 min) — music gen is slow. */
|
|
207
|
+
timeout?: number;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export interface AudioResponse {
|
|
211
|
+
/** Public CDN URL of the generated music clip (mp3/wav). */
|
|
212
|
+
audioUrl: string;
|
|
213
|
+
/** Resolved model id that produced the clip. */
|
|
214
|
+
model: string;
|
|
215
|
+
/** Output duration in seconds, or null if undetermined. */
|
|
216
|
+
durationSeconds: number | null;
|
|
217
|
+
prompt?: string;
|
|
218
|
+
usage: { creditsUsed: number };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// ─── SFX (sound effects — ElevenLabs) ───────────────────────────────────────
|
|
222
|
+
|
|
223
|
+
export interface SfxRequest {
|
|
224
|
+
/** Sound description (the source + its character), e.g. "glass shattering". */
|
|
225
|
+
prompt: string;
|
|
226
|
+
model?: string;
|
|
227
|
+
/** Clip length in seconds (0.5–30). Omit to let the model auto-decide. */
|
|
228
|
+
durationSeconds?: number;
|
|
229
|
+
/**
|
|
230
|
+
* How strictly the output follows the prompt (0–1). Higher = more literal
|
|
231
|
+
* and less variable; lower = more creative/ambient. Omit to use the strict
|
|
232
|
+
* SFX default (0.7) — keeps a concrete prompt (e.g. "clapping") from
|
|
233
|
+
* drifting into a musical/ambient soundscape.
|
|
234
|
+
*/
|
|
235
|
+
promptInfluence?: number;
|
|
236
|
+
signal?: AbortSignal;
|
|
237
|
+
/** Per-call timeout (ms). Defaults to 120000 (2 min). */
|
|
238
|
+
timeout?: number;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export interface SfxResponse {
|
|
242
|
+
/** Public CDN URL of the generated sound effect (mp3). */
|
|
243
|
+
audioUrl: string;
|
|
244
|
+
model: string;
|
|
245
|
+
/** Output duration in seconds, or null if the model auto-decided. */
|
|
246
|
+
durationSeconds: number | null;
|
|
247
|
+
prompt?: string;
|
|
248
|
+
usage: { creditsUsed: number };
|
|
249
|
+
}
|
|
250
|
+
|
|
177
251
|
// ─── Vision ───────────────────────────────────────────────────────────────────
|
|
178
252
|
|
|
179
253
|
export interface VisionRequest {
|
|
@@ -214,6 +288,158 @@ export interface EmbedResponse {
|
|
|
214
288
|
usage: { creditsUsed: number };
|
|
215
289
|
}
|
|
216
290
|
|
|
291
|
+
// ─── Knowledge base (per-user RAG) ───────────────────────────────────────────
|
|
292
|
+
|
|
293
|
+
export type KnowledgeStatus = 'processing' | 'ready' | 'error';
|
|
294
|
+
|
|
295
|
+
export interface KnowledgeSource {
|
|
296
|
+
id: string;
|
|
297
|
+
name: string;
|
|
298
|
+
status: KnowledgeStatus;
|
|
299
|
+
chunk_count?: number;
|
|
300
|
+
char_count?: number;
|
|
301
|
+
mime_type?: string;
|
|
302
|
+
size_bytes?: number;
|
|
303
|
+
/** Present when `status === 'error'`. */
|
|
304
|
+
error_message?: string;
|
|
305
|
+
source_type?: string;
|
|
306
|
+
created_at?: string;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
export interface KnowledgeIngestOptions {
|
|
310
|
+
signal?: AbortSignal;
|
|
311
|
+
/** Per-call timeout (ms). Defaults to 180000 (3 min). */
|
|
312
|
+
timeout?: number;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
export interface KnowledgeRequestOptions {
|
|
316
|
+
signal?: AbortSignal;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Per-user knowledge base (RAG). Documents are uploaded by the app's END USERS,
|
|
321
|
+
* vectorized transparently and scoped to the current end user (set via
|
|
322
|
+
* `setEndUser`). Relevant passages are injected into that user's chat answers
|
|
323
|
+
* automatically — you only upload / list / delete here.
|
|
324
|
+
*/
|
|
325
|
+
export interface KnowledgeNamespace {
|
|
326
|
+
/** Upload a File/Blob (pdf, docx, txt, csv, md, xlsx, pptx) to vectorize. */
|
|
327
|
+
ingest(
|
|
328
|
+
file: Blob | File,
|
|
329
|
+
options?: KnowledgeIngestOptions,
|
|
330
|
+
): Promise<KnowledgeSource>;
|
|
331
|
+
/** List the current end user's own knowledge sources. */
|
|
332
|
+
listMine(options?: KnowledgeRequestOptions): Promise<KnowledgeSource[]>;
|
|
333
|
+
/** Delete one of the current end user's own sources by id. */
|
|
334
|
+
deleteMine(
|
|
335
|
+
id: string,
|
|
336
|
+
options?: KnowledgeRequestOptions,
|
|
337
|
+
): Promise<{ success: boolean }>;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// ─── Live translation ──────────────────────────────────────────────────────
|
|
341
|
+
|
|
342
|
+
export type LiveTranslateMode = 'speech' | 'text';
|
|
343
|
+
|
|
344
|
+
export interface LiveUsage {
|
|
345
|
+
inputTokens: number;
|
|
346
|
+
outputTokens: number;
|
|
347
|
+
audioInputTokens: number;
|
|
348
|
+
audioOutputTokens: number;
|
|
349
|
+
creditsUsed: number;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
export interface LiveReadyPayload {
|
|
353
|
+
sessionId: string;
|
|
354
|
+
model: string;
|
|
355
|
+
mode: LiveTranslateMode;
|
|
356
|
+
sourceLang: string;
|
|
357
|
+
targetLang: string;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
export interface LiveTranscript {
|
|
361
|
+
/** 'input' = recognized source speech; 'output' = translated text. */
|
|
362
|
+
role: 'input' | 'output';
|
|
363
|
+
text: string;
|
|
364
|
+
isFinal: boolean;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
export interface LiveAudioOut {
|
|
368
|
+
/** Base64-encoded PCM audio (24 kHz) of the spoken translation. */
|
|
369
|
+
chunk: string;
|
|
370
|
+
mimeType: string;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
export interface LiveTurnComplete {
|
|
374
|
+
interrupted: boolean;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
export interface LiveError {
|
|
378
|
+
code: string;
|
|
379
|
+
message: string;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
export interface LiveClosed {
|
|
383
|
+
reason: string;
|
|
384
|
+
usage: LiveUsage | null;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
export interface LiveTranslateOptions {
|
|
388
|
+
/** Target language to translate into (e.g. "ko" / "Korean"). Required. */
|
|
389
|
+
targetLang: string;
|
|
390
|
+
/** Source language hint. Optional — Gemini Live Translate auto-detects it. */
|
|
391
|
+
sourceLang?: string;
|
|
392
|
+
/** 'speech' (render audio + transcripts, default) or 'text' (transcripts only). */
|
|
393
|
+
mode?: LiveTranslateMode;
|
|
394
|
+
/** Prebuilt voice name for the spoken translation. */
|
|
395
|
+
voice?: string;
|
|
396
|
+
/** Speak audio even when the input is already in the target language (default true). */
|
|
397
|
+
echoTargetLanguage?: boolean;
|
|
398
|
+
/** Override the WebSocket origin (defaults to the `baseUrl` origin). */
|
|
399
|
+
wsUrl?: string;
|
|
400
|
+
/** Emit `translate:start` automatically on connect. Default true. */
|
|
401
|
+
autoStart?: boolean;
|
|
402
|
+
onReady?: (payload: LiveReadyPayload) => void;
|
|
403
|
+
onTranscript?: (payload: LiveTranscript) => void;
|
|
404
|
+
onAudio?: (payload: LiveAudioOut) => void;
|
|
405
|
+
onTurnComplete?: (payload: LiveTurnComplete) => void;
|
|
406
|
+
onError?: (payload: LiveError) => void;
|
|
407
|
+
onClosed?: (payload: LiveClosed) => void;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
export type LiveTranslateEvent =
|
|
411
|
+
| 'ready'
|
|
412
|
+
| 'transcript'
|
|
413
|
+
| 'audio'
|
|
414
|
+
| 'turn_complete'
|
|
415
|
+
| 'error'
|
|
416
|
+
| 'closed';
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* A real-time translation session. Transport-only — mic capture and audio
|
|
420
|
+
* playback stay in your app. Audio in: 16 kHz, 16-bit, mono PCM. Audio out
|
|
421
|
+
* (`onAudio`): 24 kHz PCM.
|
|
422
|
+
*/
|
|
423
|
+
export class LiveTranslateSession {
|
|
424
|
+
readonly params: LiveTranslateOptions;
|
|
425
|
+
ready: boolean;
|
|
426
|
+
closed: boolean;
|
|
427
|
+
/** (Re)start a translation turn with the configured (or given) params. */
|
|
428
|
+
start(params?: Partial<LiveTranslateOptions>): void;
|
|
429
|
+
/** Push a realtime audio chunk (base64 string, ArrayBuffer, or typed array). */
|
|
430
|
+
sendAudio(chunk: string | ArrayBuffer | ArrayBufferView): void;
|
|
431
|
+
/** Push text to translate (alternative to audio). */
|
|
432
|
+
sendText(text: string): void;
|
|
433
|
+
/** Signal the audio input stream ended (mic off). */
|
|
434
|
+
audioEnd(): void;
|
|
435
|
+
/** Stop the session (settles billing and closes upstream). */
|
|
436
|
+
stop(): void;
|
|
437
|
+
/** Tear down the socket immediately. */
|
|
438
|
+
close(): void;
|
|
439
|
+
/** Subscribe to an event; returns an unsubscribe function. */
|
|
440
|
+
on(event: LiveTranslateEvent, cb: (payload: any) => void): () => void;
|
|
441
|
+
}
|
|
442
|
+
|
|
217
443
|
export interface AIFlowClientOptions {
|
|
218
444
|
appId: string;
|
|
219
445
|
baseUrl: string;
|
|
@@ -222,6 +448,13 @@ export interface AIFlowClientOptions {
|
|
|
222
448
|
defaultImageModel?: string | null;
|
|
223
449
|
defaultEmbedModel?: string | null;
|
|
224
450
|
defaultVideoModel?: string | null;
|
|
451
|
+
defaultAudioModel?: string | null;
|
|
452
|
+
defaultSfxModel?: string | null;
|
|
453
|
+
/**
|
|
454
|
+
* Current end-user id (the app's logged-in user). Scopes the per-user
|
|
455
|
+
* knowledge base; sent as `x-end-user-id`. Set/clear later with `setEndUser`.
|
|
456
|
+
*/
|
|
457
|
+
endUserId?: string | null;
|
|
225
458
|
timeout?: number;
|
|
226
459
|
maxRetries?: number;
|
|
227
460
|
fetch?: typeof fetch;
|
|
@@ -234,17 +467,23 @@ export interface AiflowConfig {
|
|
|
234
467
|
image: string[];
|
|
235
468
|
embed: string[];
|
|
236
469
|
video: string[];
|
|
470
|
+
audio: string[];
|
|
471
|
+
sfx: string[];
|
|
237
472
|
};
|
|
238
473
|
defaults: {
|
|
239
474
|
chat: string;
|
|
240
475
|
image: string;
|
|
241
476
|
embed: string;
|
|
242
477
|
video: string;
|
|
478
|
+
audio: string;
|
|
479
|
+
sfx: string;
|
|
243
480
|
};
|
|
244
481
|
limits: {
|
|
245
482
|
maxTokens: number;
|
|
246
483
|
maxImageN: number;
|
|
247
484
|
maxEmbedInputs: number;
|
|
485
|
+
minSfxDurationSeconds: number;
|
|
486
|
+
maxSfxDurationSeconds: number;
|
|
248
487
|
};
|
|
249
488
|
creditValue: number;
|
|
250
489
|
/** Module-configured default system prompt, or null if none. */
|
|
@@ -256,9 +495,21 @@ export class AIFlowClient {
|
|
|
256
495
|
readonly baseUrl: string;
|
|
257
496
|
readonly timeout: number;
|
|
258
497
|
readonly maxRetries: number;
|
|
498
|
+
/** Current end-user id (or null). Set via `setEndUser`. */
|
|
499
|
+
endUserId: string | null;
|
|
500
|
+
/** Per-user knowledge base — upload / list / delete the current user's docs. */
|
|
501
|
+
readonly knowledge: KnowledgeNamespace;
|
|
259
502
|
|
|
260
503
|
constructor(options: AIFlowClientOptions);
|
|
261
504
|
|
|
505
|
+
/**
|
|
506
|
+
* Set (or clear with `null`) the current end user. Call after your app
|
|
507
|
+
* authenticates a user — every subsequent knowledge AND chat call then
|
|
508
|
+
* carries `x-end-user-id`, so the user's own uploaded documents ground their
|
|
509
|
+
* answers. Returns `this` for chaining.
|
|
510
|
+
*/
|
|
511
|
+
setEndUser(endUserId: string | null): this;
|
|
512
|
+
|
|
262
513
|
/**
|
|
263
514
|
* Fetch (and cache) the server-side AIFlow config. Pass `{ refresh: true }`
|
|
264
515
|
* to force a reload.
|
|
@@ -269,8 +520,18 @@ export class AIFlowClient {
|
|
|
269
520
|
generateImage(request: ImageRequest): Promise<ImageResponse>;
|
|
270
521
|
generateImageBatch(request: ImageBatchRequest): Promise<ImageBatchResponse>;
|
|
271
522
|
generateVideo(request: VideoRequest): Promise<VideoResponse>;
|
|
523
|
+
generateAudio(request: AudioRequest): Promise<AudioResponse>;
|
|
524
|
+
generateSfx(request: SfxRequest): Promise<SfxResponse>;
|
|
272
525
|
embed(request: EmbedRequest): Promise<EmbedResponse>;
|
|
273
526
|
vision(request: VisionRequest): Promise<VisionResponse>;
|
|
527
|
+
/**
|
|
528
|
+
* Open a real-time speech-translation session over WebSocket (Gemini Live
|
|
529
|
+
* via the gateway). Requires the optional peer dependency
|
|
530
|
+
* `socket.io-client`. Resolves once connected.
|
|
531
|
+
*/
|
|
532
|
+
connectLiveTranslate(
|
|
533
|
+
options: LiveTranslateOptions,
|
|
534
|
+
): Promise<LiveTranslateSession>;
|
|
274
535
|
}
|
|
275
536
|
|
|
276
537
|
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.
|
|
@@ -38,6 +39,10 @@ export class AIFlowClient {
|
|
|
38
39
|
defaultModel = null,
|
|
39
40
|
defaultImageModel = null,
|
|
40
41
|
defaultEmbedModel = null,
|
|
42
|
+
defaultVideoModel = null,
|
|
43
|
+
defaultAudioModel = null,
|
|
44
|
+
defaultSfxModel = null,
|
|
45
|
+
endUserId = null,
|
|
41
46
|
timeout = DEFAULT_TIMEOUT_MS,
|
|
42
47
|
maxRetries = DEFAULT_MAX_RETRIES,
|
|
43
48
|
fetch: customFetch,
|
|
@@ -47,11 +52,17 @@ export class AIFlowClient {
|
|
|
47
52
|
|
|
48
53
|
this.appId = appId;
|
|
49
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;
|
|
50
58
|
// Caller-provided overrides — win over server-fetched config.
|
|
51
59
|
this._userDefaults = {
|
|
52
60
|
chat: defaultModel,
|
|
53
61
|
image: defaultImageModel,
|
|
54
62
|
embed: defaultEmbedModel,
|
|
63
|
+
video: defaultVideoModel,
|
|
64
|
+
audio: defaultAudioModel,
|
|
65
|
+
sfx: defaultSfxModel,
|
|
55
66
|
};
|
|
56
67
|
this.timeout = timeout;
|
|
57
68
|
this.maxRetries = maxRetries;
|
|
@@ -69,6 +80,33 @@ export class AIFlowClient {
|
|
|
69
80
|
// getConfig() / chat() / generateImage() / embed().
|
|
70
81
|
this._config = null;
|
|
71
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;
|
|
72
110
|
}
|
|
73
111
|
|
|
74
112
|
/**
|
|
@@ -335,9 +373,12 @@ export class AIFlowClient {
|
|
|
335
373
|
prompt,
|
|
336
374
|
model,
|
|
337
375
|
aspectRatio = '16:9',
|
|
376
|
+
duration,
|
|
377
|
+
watermark,
|
|
338
378
|
image,
|
|
339
379
|
video,
|
|
340
380
|
signal,
|
|
381
|
+
timeout,
|
|
341
382
|
} = {}) {
|
|
342
383
|
if (!prompt || typeof prompt !== 'string') {
|
|
343
384
|
throw new AIFlowError('prompt is required');
|
|
@@ -350,10 +391,76 @@ export class AIFlowClient {
|
|
|
350
391
|
model: resolvedModel,
|
|
351
392
|
prompt,
|
|
352
393
|
aspectRatio,
|
|
394
|
+
duration,
|
|
395
|
+
watermark,
|
|
353
396
|
image,
|
|
354
397
|
video,
|
|
355
398
|
},
|
|
356
|
-
|
|
399
|
+
// Video generation is long-running (the server polls the provider
|
|
400
|
+
// for up to ~10 minutes). Match that ceiling so the socket isn't
|
|
401
|
+
// closed mid-generation.
|
|
402
|
+
{ signal, timeout: timeout ?? 600_000 },
|
|
403
|
+
);
|
|
404
|
+
return await res.json();
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Generate music / background audio from a text prompt (Lyria).
|
|
409
|
+
* @returns {Promise<{audioUrl:string, model:string, durationSeconds:number|null, prompt?:string, usage:{creditsUsed:number}}>}
|
|
410
|
+
*/
|
|
411
|
+
async generateAudio({
|
|
412
|
+
prompt,
|
|
413
|
+
model,
|
|
414
|
+
negativePrompt,
|
|
415
|
+
seed,
|
|
416
|
+
signal,
|
|
417
|
+
timeout,
|
|
418
|
+
} = {}) {
|
|
419
|
+
if (!prompt || typeof prompt !== 'string') {
|
|
420
|
+
throw new AIFlowError('prompt is required');
|
|
421
|
+
}
|
|
422
|
+
const resolvedModel =
|
|
423
|
+
model || (await this._resolveDefaultModel('audio'));
|
|
424
|
+
const res = await this._request(
|
|
425
|
+
'/audio',
|
|
426
|
+
{
|
|
427
|
+
model: resolvedModel,
|
|
428
|
+
prompt,
|
|
429
|
+
negativePrompt,
|
|
430
|
+
seed,
|
|
431
|
+
},
|
|
432
|
+
// Music generation (esp. full-song Lyria 3 Pro) runs well past the
|
|
433
|
+
// 60s client default — allow 3 minutes before aborting.
|
|
434
|
+
{ signal, timeout: timeout ?? 180_000 },
|
|
435
|
+
);
|
|
436
|
+
return await res.json();
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Generate a one-shot sound effect from a text prompt (ElevenLabs).
|
|
441
|
+
* @returns {Promise<{audioUrl:string, model:string, durationSeconds:number|null, prompt?:string, usage:{creditsUsed:number}}>}
|
|
442
|
+
*/
|
|
443
|
+
async generateSfx({
|
|
444
|
+
prompt,
|
|
445
|
+
model,
|
|
446
|
+
durationSeconds,
|
|
447
|
+
promptInfluence,
|
|
448
|
+
signal,
|
|
449
|
+
timeout,
|
|
450
|
+
} = {}) {
|
|
451
|
+
if (!prompt || typeof prompt !== 'string') {
|
|
452
|
+
throw new AIFlowError('prompt is required');
|
|
453
|
+
}
|
|
454
|
+
const resolvedModel = model || (await this._resolveDefaultModel('sfx'));
|
|
455
|
+
const res = await this._request(
|
|
456
|
+
'/sfx',
|
|
457
|
+
{
|
|
458
|
+
model: resolvedModel,
|
|
459
|
+
prompt,
|
|
460
|
+
durationSeconds,
|
|
461
|
+
promptInfluence,
|
|
462
|
+
},
|
|
463
|
+
{ signal, timeout: timeout ?? 120_000 },
|
|
357
464
|
);
|
|
358
465
|
return await res.json();
|
|
359
466
|
}
|
|
@@ -403,17 +510,115 @@ export class AIFlowClient {
|
|
|
403
510
|
return await res.json();
|
|
404
511
|
}
|
|
405
512
|
|
|
513
|
+
/**
|
|
514
|
+
* Open a real-time speech-translation session over WebSocket (Gemini Live
|
|
515
|
+
* via the platform gateway — no Google key in the browser). Stream 16 kHz
|
|
516
|
+
* 16-bit mono PCM audio in; receive translated audio (24 kHz PCM) and
|
|
517
|
+
* source/target transcripts back.
|
|
518
|
+
*
|
|
519
|
+
* Requires the optional peer dependency `socket.io-client`.
|
|
520
|
+
*
|
|
521
|
+
* Input is AUDIO ONLY — text input is not supported by the translate model.
|
|
522
|
+
*
|
|
523
|
+
* @param {object} opts
|
|
524
|
+
* @param {string} opts.targetLang Target language to translate into (e.g. "ko" / "Korean"). Required.
|
|
525
|
+
* @param {string} [opts.sourceLang] Source language hint. Optional — the model auto-detects.
|
|
526
|
+
* @param {'speech'|'text'} [opts.mode] 'speech' (render audio + transcripts, default) or 'text' (transcripts only).
|
|
527
|
+
* @param {string} [opts.voice] Prebuilt voice for the spoken translation.
|
|
528
|
+
* @param {boolean} [opts.echoTargetLanguage] Speak audio even when input is already in the target language (default true).
|
|
529
|
+
* @param {string} [opts.wsUrl] Override the ws origin (defaults to baseUrl's origin).
|
|
530
|
+
* @param {boolean} [opts.autoStart] Send `translate:start` automatically on connect (default true).
|
|
531
|
+
* @param {(p:object)=>void} [opts.onReady]
|
|
532
|
+
* @param {(p:{role:'input'|'output',text:string,isFinal:boolean})=>void} [opts.onTranscript]
|
|
533
|
+
* @param {(p:{chunk:string,mimeType:string})=>void} [opts.onAudio]
|
|
534
|
+
* @param {(p:{interrupted:boolean})=>void} [opts.onTurnComplete]
|
|
535
|
+
* @param {(p:{code:string,message:string})=>void} [opts.onError]
|
|
536
|
+
* @param {(p:{reason:string,usage:object})=>void} [opts.onClosed]
|
|
537
|
+
* @returns {Promise<LiveTranslateSession>} Resolves once connected.
|
|
538
|
+
*/
|
|
539
|
+
async connectLiveTranslate({
|
|
540
|
+
targetLang,
|
|
541
|
+
sourceLang,
|
|
542
|
+
mode,
|
|
543
|
+
voice,
|
|
544
|
+
echoTargetLanguage,
|
|
545
|
+
wsUrl,
|
|
546
|
+
autoStart = true,
|
|
547
|
+
onReady,
|
|
548
|
+
onTranscript,
|
|
549
|
+
onAudio,
|
|
550
|
+
onTurnComplete,
|
|
551
|
+
onError,
|
|
552
|
+
onClosed,
|
|
553
|
+
} = {}) {
|
|
554
|
+
if (!targetLang) {
|
|
555
|
+
throw new AIFlowError(
|
|
556
|
+
'connectLiveTranslate requires targetLang',
|
|
557
|
+
);
|
|
558
|
+
}
|
|
559
|
+
const io = await loadSocketIoClient();
|
|
560
|
+
let origin = wsUrl;
|
|
561
|
+
if (!origin) {
|
|
562
|
+
try {
|
|
563
|
+
origin = new URL(this.baseUrl).origin;
|
|
564
|
+
} catch {
|
|
565
|
+
throw new AIFlowError(
|
|
566
|
+
'Could not derive the WebSocket origin from baseUrl — pass opts.wsUrl.',
|
|
567
|
+
);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
const session = new LiveTranslateSession({
|
|
571
|
+
io,
|
|
572
|
+
origin,
|
|
573
|
+
appId: this.appId,
|
|
574
|
+
params: { targetLang, sourceLang, mode, voice, echoTargetLanguage },
|
|
575
|
+
autoStart,
|
|
576
|
+
handlers: {
|
|
577
|
+
onReady,
|
|
578
|
+
onTranscript,
|
|
579
|
+
onAudio,
|
|
580
|
+
onTurnComplete,
|
|
581
|
+
onError,
|
|
582
|
+
onClosed,
|
|
583
|
+
},
|
|
584
|
+
});
|
|
585
|
+
await session._connect();
|
|
586
|
+
return session;
|
|
587
|
+
}
|
|
588
|
+
|
|
406
589
|
// ────────────────────────────────────────────────────────────────────────
|
|
407
590
|
// Internals
|
|
408
591
|
// ────────────────────────────────────────────────────────────────────────
|
|
409
592
|
|
|
593
|
+
/**
|
|
594
|
+
* Auth/identity headers attached to every gateway call: the public app id
|
|
595
|
+
* and (when set) the current end-user id that scopes the knowledge base.
|
|
596
|
+
*/
|
|
597
|
+
_authHeaders() {
|
|
598
|
+
const h = { 'x-app-id': this.appId };
|
|
599
|
+
if (this.endUserId) h['x-end-user-id'] = this.endUserId;
|
|
600
|
+
return h;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/** POST a JSON body to the gateway. */
|
|
410
604
|
async _request(path, body, { signal, stream = false, timeout } = {}) {
|
|
411
|
-
const url = `${this.baseUrl}${path}`;
|
|
412
605
|
const headers = {
|
|
413
606
|
'Content-Type': 'application/json',
|
|
414
|
-
|
|
607
|
+
...this._authHeaders(),
|
|
415
608
|
Accept: stream ? 'text/event-stream' : 'application/json',
|
|
416
609
|
};
|
|
610
|
+
return this._fetchWithRetry(
|
|
611
|
+
`${this.baseUrl}${path}`,
|
|
612
|
+
{ method: 'POST', headers, body: JSON.stringify(body) },
|
|
613
|
+
{ signal, timeout },
|
|
614
|
+
);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* Send a request with timeout + retry (429/5xx + network errors). `init`
|
|
619
|
+
* carries method/headers/body; the abort signal is composed per attempt.
|
|
620
|
+
*/
|
|
621
|
+
async _fetchWithRetry(url, init, { signal, timeout } = {}) {
|
|
417
622
|
// Per-call timeout override — image/video calls run far longer than the
|
|
418
623
|
// 60s client default, so they pass a larger value here.
|
|
419
624
|
const effectiveTimeout = timeout ?? this.timeout;
|
|
@@ -430,9 +635,7 @@ export class AIFlowClient {
|
|
|
430
635
|
let res;
|
|
431
636
|
try {
|
|
432
637
|
res = await this._fetch(url, {
|
|
433
|
-
|
|
434
|
-
headers,
|
|
435
|
-
body: JSON.stringify(body),
|
|
638
|
+
...init,
|
|
436
639
|
signal: composedSignal,
|
|
437
640
|
});
|
|
438
641
|
} catch (err) {
|
|
@@ -444,7 +647,7 @@ export class AIFlowClient {
|
|
|
444
647
|
continue;
|
|
445
648
|
}
|
|
446
649
|
throw new AIFlowError(
|
|
447
|
-
`Network error calling ${
|
|
650
|
+
`Network error calling ${url}: ${err?.message || err}`,
|
|
448
651
|
{ cause: err },
|
|
449
652
|
);
|
|
450
653
|
}
|
|
@@ -474,6 +677,240 @@ export class AIFlowClient {
|
|
|
474
677
|
return res;
|
|
475
678
|
}
|
|
476
679
|
}
|
|
680
|
+
|
|
681
|
+
// ────────────────────────────────────────────────────────────────────────
|
|
682
|
+
// Knowledge base (per-user RAG) internals
|
|
683
|
+
// ────────────────────────────────────────────────────────────────────────
|
|
684
|
+
|
|
685
|
+
async _knowledgeIngest(file, { signal, timeout } = {}) {
|
|
686
|
+
if (!file) {
|
|
687
|
+
throw new AIFlowError('a File/Blob is required to ingest knowledge');
|
|
688
|
+
}
|
|
689
|
+
if (!this.endUserId) {
|
|
690
|
+
throw new AIFlowError(
|
|
691
|
+
'setEndUser(id) must be called before uploading knowledge',
|
|
692
|
+
);
|
|
693
|
+
}
|
|
694
|
+
if (typeof FormData === 'undefined') {
|
|
695
|
+
throw new AIFlowError(
|
|
696
|
+
'FormData is not available in this environment — knowledge upload needs a browser or Node 18+ with global FormData.',
|
|
697
|
+
);
|
|
698
|
+
}
|
|
699
|
+
const form = new FormData();
|
|
700
|
+
// Field name is irrelevant — the gateway accepts any (multer().any()).
|
|
701
|
+
form.append('file', file, file.name || 'document');
|
|
702
|
+
// NO Content-Type header — fetch sets the multipart boundary itself.
|
|
703
|
+
const res = await this._fetchWithRetry(
|
|
704
|
+
`${this.baseUrl}/knowledge/ingest`,
|
|
705
|
+
{ method: 'POST', headers: this._authHeaders(), body: form },
|
|
706
|
+
// Extracting + embedding a large doc can run long; the server does it
|
|
707
|
+
// in the background but the upload itself may still take a while.
|
|
708
|
+
{ signal, timeout: timeout ?? 180_000 },
|
|
709
|
+
);
|
|
710
|
+
return await res.json();
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
async _knowledgeList({ signal } = {}) {
|
|
714
|
+
const res = await this._fetchWithRetry(
|
|
715
|
+
`${this.baseUrl}/knowledge/sources`,
|
|
716
|
+
{
|
|
717
|
+
method: 'GET',
|
|
718
|
+
headers: { Accept: 'application/json', ...this._authHeaders() },
|
|
719
|
+
},
|
|
720
|
+
{ signal },
|
|
721
|
+
);
|
|
722
|
+
return await res.json();
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
async _knowledgeDelete(id, { signal } = {}) {
|
|
726
|
+
if (!id) throw new AIFlowError('a source id is required');
|
|
727
|
+
const res = await this._fetchWithRetry(
|
|
728
|
+
`${this.baseUrl}/knowledge/sources/${encodeURIComponent(id)}`,
|
|
729
|
+
{
|
|
730
|
+
method: 'DELETE',
|
|
731
|
+
headers: { Accept: 'application/json', ...this._authHeaders() },
|
|
732
|
+
},
|
|
733
|
+
{ signal },
|
|
734
|
+
);
|
|
735
|
+
return await res.json();
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
740
|
+
// Live translation
|
|
741
|
+
// ────────────────────────────────────────────────────────────────────────────
|
|
742
|
+
|
|
743
|
+
/**
|
|
744
|
+
* A real-time translation session. Created via
|
|
745
|
+
* `AIFlowClient.connectLiveTranslate(...)`. Transport-only: mic capture and
|
|
746
|
+
* audio playback stay in your app. Audio in must be 16 kHz, 16-bit, mono PCM;
|
|
747
|
+
* audio out (`onAudio`) is 24 kHz PCM.
|
|
748
|
+
*/
|
|
749
|
+
export class LiveTranslateSession {
|
|
750
|
+
constructor({ io, origin, appId, params, autoStart, handlers }) {
|
|
751
|
+
this._io = io;
|
|
752
|
+
this._origin = String(origin).replace(/\/+$/, '');
|
|
753
|
+
this._appId = appId;
|
|
754
|
+
this.params = params;
|
|
755
|
+
this._autoStart = autoStart;
|
|
756
|
+
this._handlers = handlers || {};
|
|
757
|
+
this._listeners = new Map();
|
|
758
|
+
this.socket = null;
|
|
759
|
+
this.ready = false;
|
|
760
|
+
this.closed = false;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
async _connect() {
|
|
764
|
+
this.socket = this._io(`${this._origin}/aiflow-live`, {
|
|
765
|
+
path: '/ws',
|
|
766
|
+
transports: ['websocket'],
|
|
767
|
+
auth: { appId: this._appId },
|
|
768
|
+
});
|
|
769
|
+
|
|
770
|
+
const fwd = (event, cb) =>
|
|
771
|
+
this.socket.on(event, (payload) => {
|
|
772
|
+
cb?.(payload);
|
|
773
|
+
this._emit(event, payload);
|
|
774
|
+
});
|
|
775
|
+
|
|
776
|
+
this.socket.on('translate:ready', (p) => {
|
|
777
|
+
this.ready = true;
|
|
778
|
+
this._handlers.onReady?.(p);
|
|
779
|
+
this._emit('ready', p);
|
|
780
|
+
});
|
|
781
|
+
fwd('translate:transcript', this._handlers.onTranscript);
|
|
782
|
+
fwd('translate:audio', this._handlers.onAudio);
|
|
783
|
+
fwd('translate:turn_complete', this._handlers.onTurnComplete);
|
|
784
|
+
fwd('translate:error', this._handlers.onError);
|
|
785
|
+
this.socket.on('translate:closed', (p) => {
|
|
786
|
+
this.closed = true;
|
|
787
|
+
this._handlers.onClosed?.(p);
|
|
788
|
+
this._emit('closed', p);
|
|
789
|
+
});
|
|
790
|
+
|
|
791
|
+
await new Promise((resolve, reject) => {
|
|
792
|
+
const timer = setTimeout(
|
|
793
|
+
() =>
|
|
794
|
+
reject(
|
|
795
|
+
new AIFlowError('AIFlow Live connection timed out'),
|
|
796
|
+
),
|
|
797
|
+
15_000,
|
|
798
|
+
);
|
|
799
|
+
this.socket.once('connect', () => {
|
|
800
|
+
clearTimeout(timer);
|
|
801
|
+
resolve();
|
|
802
|
+
});
|
|
803
|
+
this.socket.once('connect_error', (err) => {
|
|
804
|
+
clearTimeout(timer);
|
|
805
|
+
reject(
|
|
806
|
+
new AIFlowError(
|
|
807
|
+
`AIFlow Live connection failed: ${err?.message || err}`,
|
|
808
|
+
{ cause: err },
|
|
809
|
+
),
|
|
810
|
+
);
|
|
811
|
+
});
|
|
812
|
+
});
|
|
813
|
+
|
|
814
|
+
if (this._autoStart) this.start();
|
|
815
|
+
return this;
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/** (Re)start the translation turn with the configured params. */
|
|
819
|
+
start(params) {
|
|
820
|
+
this.socket?.emit('translate:start', params || this.params);
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/**
|
|
824
|
+
* Push a realtime audio chunk. Accepts a base64 string, an ArrayBuffer, or
|
|
825
|
+
* a typed array of 16 kHz 16-bit mono PCM.
|
|
826
|
+
*/
|
|
827
|
+
sendAudio(chunk) {
|
|
828
|
+
this.socket?.emit('translate:audio', { chunk: toBase64(chunk) });
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
/** Push text to translate (alternative to audio). */
|
|
832
|
+
sendText(text) {
|
|
833
|
+
this.socket?.emit('translate:text', { text });
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/** Signal that the audio input stream ended (mic off). */
|
|
837
|
+
audioEnd() {
|
|
838
|
+
this.socket?.emit('translate:audio_end');
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
/** Stop the session (settles billing and closes upstream). */
|
|
842
|
+
stop() {
|
|
843
|
+
this.socket?.emit('translate:stop');
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
/** Tear down the socket immediately. */
|
|
847
|
+
close() {
|
|
848
|
+
try {
|
|
849
|
+
this.socket?.close();
|
|
850
|
+
} catch {
|
|
851
|
+
/* noop */
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
/** Subscribe to an event ('ready'|'transcript'|'audio'|'turn_complete'|'error'|'closed' or the raw `translate:*`). */
|
|
856
|
+
on(event, cb) {
|
|
857
|
+
const key = event.startsWith('translate:')
|
|
858
|
+
? event.slice('translate:'.length)
|
|
859
|
+
: event;
|
|
860
|
+
if (!this._listeners.has(key)) this._listeners.set(key, new Set());
|
|
861
|
+
this._listeners.get(key).add(cb);
|
|
862
|
+
return () => this._listeners.get(key)?.delete(cb);
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
_emit(event, payload) {
|
|
866
|
+
const key = event.startsWith('translate:')
|
|
867
|
+
? event.slice('translate:'.length)
|
|
868
|
+
: event;
|
|
869
|
+
const set = this._listeners.get(key);
|
|
870
|
+
if (set) for (const cb of set) cb(payload);
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
async function loadSocketIoClient() {
|
|
875
|
+
try {
|
|
876
|
+
const mod = await import('socket.io-client');
|
|
877
|
+
return mod.io || mod.default?.io || mod.default;
|
|
878
|
+
} catch (err) {
|
|
879
|
+
throw new AIFlowError(
|
|
880
|
+
'socket.io-client is required for live translation — install it: npm i socket.io-client',
|
|
881
|
+
{ cause: err },
|
|
882
|
+
);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
function toBase64(chunk) {
|
|
887
|
+
if (typeof chunk === 'string') return chunk; // assume already base64
|
|
888
|
+
let bytes;
|
|
889
|
+
if (chunk instanceof Uint8Array) bytes = chunk;
|
|
890
|
+
else if (chunk instanceof ArrayBuffer) bytes = new Uint8Array(chunk);
|
|
891
|
+
else if (ArrayBuffer.isView(chunk))
|
|
892
|
+
bytes = new Uint8Array(
|
|
893
|
+
chunk.buffer,
|
|
894
|
+
chunk.byteOffset,
|
|
895
|
+
chunk.byteLength,
|
|
896
|
+
);
|
|
897
|
+
else
|
|
898
|
+
throw new AIFlowError(
|
|
899
|
+
'sendAudio expects a base64 string, ArrayBuffer, or typed array',
|
|
900
|
+
);
|
|
901
|
+
|
|
902
|
+
if (typeof btoa === 'function') {
|
|
903
|
+
let bin = '';
|
|
904
|
+
const CHUNK = 0x8000;
|
|
905
|
+
for (let i = 0; i < bytes.length; i += CHUNK) {
|
|
906
|
+
bin += String.fromCharCode.apply(
|
|
907
|
+
null,
|
|
908
|
+
bytes.subarray(i, i + CHUNK),
|
|
909
|
+
);
|
|
910
|
+
}
|
|
911
|
+
return btoa(bin);
|
|
912
|
+
}
|
|
913
|
+
return Buffer.from(bytes).toString('base64');
|
|
477
914
|
}
|
|
478
915
|
|
|
479
916
|
// ────────────────────────────────────────────────────────────────────────────
|