@cartanova/qgrid-cli 2.16.0 → 2.17.1
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/bundle/dist/application/qgrid/qgrid.frame.js +76 -26
- package/bundle/dist/application/qgrid/qgrid.types.js +11 -3
- package/bundle/dist/utils/providers/common/model-cost.js +48 -2
- package/bundle/dist/utils/providers/grok/grok-types.js +8 -2
- package/bundle/dist/utils/providers/grok/grok-voice-client.js +4 -4
- package/bundle/dist/utils/speech-alignment.js +129 -0
- package/bundle/src/application/qgrid/qgrid.frame.test.ts +85 -10
- package/bundle/src/application/qgrid/qgrid.frame.ts +95 -33
- package/bundle/src/application/qgrid/qgrid.types.ts +17 -2
- package/bundle/src/utils/providers/common/model-cost.test.ts +14 -0
- package/bundle/src/utils/providers/common/model-cost.ts +57 -0
- package/bundle/src/utils/providers/grok/grok-types.ts +15 -10
- package/bundle/src/utils/providers/grok/grok-voice-client.ts +4 -4
- package/bundle/src/utils/speech-alignment.test.ts +72 -0
- package/bundle/src/utils/speech-alignment.ts +178 -0
- package/bundle/web-dist/client/assets/TimedPlayer-cuEgYA3Q.js +1 -0
- package/bundle/web-dist/client/assets/index-Co8uAhSV.css +1 -0
- package/bundle/web-dist/client/assets/{index-SGfYBzGT.js → index-D56cIqxW.js} +3 -3
- package/bundle/web-dist/client/assets/{logs-DrTz38re.js → logs-pMW62Hvw.js} +1 -1
- package/bundle/web-dist/client/assets/{monit-klIY-HEI.js → monit-COC4S7gf.js} +1 -1
- package/bundle/web-dist/client/assets/{routes-bGN3y2NW.js → routes-C38qmify.js} +1 -1
- package/bundle/web-dist/client/assets/{settings-BHwEvAZL.js → settings-BWGSVpiQ.js} +1 -1
- package/bundle/web-dist/client/assets/show-aQTLNz5k.js +2 -0
- package/bundle/web-dist/client/assets/{tokens-DMWMG9O5.js → tokens-Ha8SwMPG.js} +1 -1
- package/bundle/web-dist/client/assets/{use-oauth-login-flow-D1v4h9zA.js → use-oauth-login-flow-JoEnKQis.js} +1 -1
- package/bundle/web-dist/client/assets/{use-update-token-mutation-BVBUlqBN.js → use-update-token-mutation-cdCVcOY5.js} +1 -1
- package/bundle/web-dist/client/assets/voice-COmvUTZO.js +1 -0
- package/bundle/web-dist/client/index.html +2 -2
- package/bundle/web-dist/server/assets/TimedPlayer-DAwjkP4z.js +54 -0
- package/bundle/web-dist/server/assets/{show-D8r2sVK0.js → show-B_l5dOcT.js} +43 -8
- package/bundle/web-dist/server/assets/{voice-C2HfwkGp.js → voice-CHoPEIfo.js} +76 -68
- package/bundle/web-dist/server/entry-server.generated.js +3 -3
- package/package.json +1 -1
- package/skills/qgrid/references/ai-sdk-provider-contract.md +1 -1
- package/skills/qgrid/references/grok-runtime.md +5 -1
- package/skills/qgrid/references/request-log-run-lifecycle.md +2 -0
- package/skills/qgrid/references/sonamu-api-web-flow.md +2 -2
- package/bundle/web-dist/client/assets/index-DyrPRt6O.css +0 -1
- package/bundle/web-dist/client/assets/show-BiJkyrfB.js +0 -2
- package/bundle/web-dist/client/assets/voice-CwD3asSF.js +0 -1
|
@@ -27,6 +27,10 @@ import {
|
|
|
27
27
|
type GrokMediaCost,
|
|
28
28
|
grokImageCost,
|
|
29
29
|
grokReportedCost,
|
|
30
|
+
grokSpeechCost,
|
|
31
|
+
openaiSpeechCost,
|
|
32
|
+
sttCost,
|
|
33
|
+
type VoiceCost,
|
|
30
34
|
} from "../../utils/providers/common/model-cost";
|
|
31
35
|
import {
|
|
32
36
|
type MediaDispatcher,
|
|
@@ -80,9 +84,11 @@ import {
|
|
|
80
84
|
OPENAI_REALTIME_DEFAULT_SPEECH_MODEL,
|
|
81
85
|
OPENAI_REALTIME_DEFAULT_TRANSCRIPTION_MODEL,
|
|
82
86
|
OPENAI_REALTIME_DEFAULT_VOICE,
|
|
87
|
+
OPENAI_REALTIME_SAMPLE_RATE,
|
|
83
88
|
wrapPcmAsWav,
|
|
84
89
|
} from "../../utils/providers/openai/openai-realtime-protocol";
|
|
85
90
|
import { OpenAIVoiceInputError } from "../../utils/providers/openai/openai-voice-client";
|
|
91
|
+
import { alignScriptToWords, wordsFromCharTimestamps } from "../../utils/speech-alignment";
|
|
86
92
|
import {
|
|
87
93
|
type FinishRunParams,
|
|
88
94
|
MICRO_USD,
|
|
@@ -771,7 +777,14 @@ function imageTagForLog(b64: string, mimeType: string, alt: string | undefined):
|
|
|
771
777
|
return `<img src="data:${mimeType};base64,${b64}" alt="${safeAlt}" />`;
|
|
772
778
|
}
|
|
773
779
|
|
|
774
|
-
type MediaLogStart = {
|
|
780
|
+
type MediaLogStart = {
|
|
781
|
+
kind: MediaKind;
|
|
782
|
+
model: string;
|
|
783
|
+
prompt: string;
|
|
784
|
+
projectName?: string;
|
|
785
|
+
/** OpenAI speech style instructions or STT prompt, shown as the run's system prompt. */
|
|
786
|
+
systemPrompt?: string;
|
|
787
|
+
};
|
|
775
788
|
|
|
776
789
|
// Creating the running row is a precondition of a logged provider call, as for query.
|
|
777
790
|
async function startMediaRun(
|
|
@@ -782,6 +795,7 @@ async function startMediaRun(
|
|
|
782
795
|
|
|
783
796
|
return RequestLogModel.createRun({
|
|
784
797
|
user_prompt: start.prompt,
|
|
798
|
+
system_prompt: start.systemPrompt,
|
|
785
799
|
requested_model_name: start.model,
|
|
786
800
|
project_name: start.projectName,
|
|
787
801
|
is_image_generation: start.kind === "image",
|
|
@@ -824,7 +838,7 @@ type MediaLogSuccess = {
|
|
|
824
838
|
durationMs: number;
|
|
825
839
|
response: string;
|
|
826
840
|
steps: MediaLogSteps;
|
|
827
|
-
cost?: GrokMediaCost;
|
|
841
|
+
cost?: GrokMediaCost | VoiceCost;
|
|
828
842
|
/** Speech only: time to the first audio byte, measured from the same start as `durationMs`. */
|
|
829
843
|
ttftMs?: number;
|
|
830
844
|
};
|
|
@@ -832,22 +846,12 @@ type MediaLogSuccess = {
|
|
|
832
846
|
// Voice rows embed browser-playable audio (TTS output in the response, STT input in the user
|
|
833
847
|
// prompt) so the request-log detail page can play it, as image rows embed their images. Other
|
|
834
848
|
// formats (raw PCM, mu-law, A-law) keep the byte-count placeholder.
|
|
835
|
-
const LOG_PLAYABLE_AUDIO =
|
|
836
|
-
"audio/wav",
|
|
837
|
-
"audio/x-wav",
|
|
838
|
-
"audio/wave",
|
|
839
|
-
"audio/mpeg",
|
|
840
|
-
"audio/mp3",
|
|
841
|
-
"audio/mp4",
|
|
842
|
-
"audio/ogg",
|
|
843
|
-
"audio/webm",
|
|
844
|
-
"audio/flac",
|
|
845
|
-
]);
|
|
849
|
+
const LOG_PLAYABLE_AUDIO = /^audio\/(wav|x-wav|wave|mpeg|mp3|mp4|ogg|webm|flac)$/;
|
|
846
850
|
|
|
847
851
|
function audioForLog(b64: string, mimeType: string, byteLength: number): string {
|
|
848
852
|
const base = mimeType.split(";")[0]!.trim().toLowerCase();
|
|
849
853
|
|
|
850
|
-
return LOG_PLAYABLE_AUDIO.
|
|
854
|
+
return LOG_PLAYABLE_AUDIO.test(base)
|
|
851
855
|
? `<audio src="data:${base};base64,${b64}"></audio>`
|
|
852
856
|
: `[audio ${mimeType} ${byteLength} bytes]`;
|
|
853
857
|
}
|
|
@@ -882,7 +886,7 @@ type MediaCostFields = Pick<FinishRunParams, "cost_usd" | "cost_source"> &
|
|
|
882
886
|
function mediaCostFields(
|
|
883
887
|
kind: MediaKind,
|
|
884
888
|
model: string,
|
|
885
|
-
cost: GrokMediaCost | undefined,
|
|
889
|
+
cost: GrokMediaCost | VoiceCost | undefined,
|
|
886
890
|
): MediaCostFields {
|
|
887
891
|
if (kind === "image") {
|
|
888
892
|
return {
|
|
@@ -1111,6 +1115,7 @@ async function transcribeOpenAI(input: TranscribeInput): Promise<TranscribeOutpu
|
|
|
1111
1115
|
kind: "stt",
|
|
1112
1116
|
model: route,
|
|
1113
1117
|
prompt: audioForLog(input.audio, input.mediaType, audio.byteLength),
|
|
1118
|
+
systemPrompt: input.prompt,
|
|
1114
1119
|
projectName: input.projectName,
|
|
1115
1120
|
logger: input.logger,
|
|
1116
1121
|
} as const;
|
|
@@ -1142,6 +1147,7 @@ async function transcribeOpenAI(input: TranscribeInput): Promise<TranscribeOutpu
|
|
|
1142
1147
|
const log: MediaRunLog = {
|
|
1143
1148
|
tokenName: output.tokenName,
|
|
1144
1149
|
response: output.text,
|
|
1150
|
+
cost: sttCost(route, durationSec),
|
|
1145
1151
|
steps: [
|
|
1146
1152
|
{
|
|
1147
1153
|
toolCallId: "transcription:0",
|
|
@@ -1165,6 +1171,35 @@ async function transcribeOpenAI(input: TranscribeInput): Promise<TranscribeOutpu
|
|
|
1165
1171
|
});
|
|
1166
1172
|
}
|
|
1167
1173
|
|
|
1174
|
+
/**
|
|
1175
|
+
* OpenAI realtime speech carries no timing, so the generated audio is transcribed with Grok STT and
|
|
1176
|
+
* the heard words are aligned to the script (`alignScriptToWords`). The Grok call goes through the
|
|
1177
|
+
* Grok dispatcher on an automatically selected token, like any Grok STT request.
|
|
1178
|
+
*/
|
|
1179
|
+
async function alignOpenAISpeech(wav: Uint8Array, script: string, signal: AbortSignal) {
|
|
1180
|
+
const selection = await resolveGrokTokenSelection(undefined);
|
|
1181
|
+
|
|
1182
|
+
const dispatched = await grokVoice().transcribe({
|
|
1183
|
+
audio: wav,
|
|
1184
|
+
mediaType: "audio/wav",
|
|
1185
|
+
model: GROK_STT_DEFAULT_MODEL,
|
|
1186
|
+
signal,
|
|
1187
|
+
...selection,
|
|
1188
|
+
});
|
|
1189
|
+
|
|
1190
|
+
const words = dispatched.result.words ?? [];
|
|
1191
|
+
|
|
1192
|
+
if (words.length === 0) throw new Error("Grok STT returned no word timing");
|
|
1193
|
+
// 44-byte WAV header, PCM16 mono at the realtime sample rate.
|
|
1194
|
+
const durationSec = (wav.byteLength - 44) / (2 * OPENAI_REALTIME_SAMPLE_RATE);
|
|
1195
|
+
|
|
1196
|
+
return {
|
|
1197
|
+
...alignScriptToWords(script, words, durationSec),
|
|
1198
|
+
durationSec,
|
|
1199
|
+
heard: dispatched.result.text,
|
|
1200
|
+
};
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1168
1203
|
/**
|
|
1169
1204
|
* OpenAI realtime speech (openai/<id>): a conversational realtime model repeating the text over
|
|
1170
1205
|
* the direct realtime socket. Output is PCM16 24 kHz, wrapped as WAV unless `format` is pcm.
|
|
@@ -1199,6 +1234,7 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
|
|
|
1199
1234
|
kind: "tts",
|
|
1200
1235
|
model: route,
|
|
1201
1236
|
prompt: input.text,
|
|
1237
|
+
systemPrompt: input.instructions,
|
|
1202
1238
|
projectName: input.projectName,
|
|
1203
1239
|
logger: input.logger,
|
|
1204
1240
|
} as const;
|
|
@@ -1216,15 +1252,34 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
|
|
|
1216
1252
|
if (requestLogId !== undefined) output.requestLogId = requestLogId;
|
|
1217
1253
|
|
|
1218
1254
|
// pcm output is always 24 kHz PCM16, so the log copy is wrapped as WAV to stay playable.
|
|
1219
|
-
const
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1255
|
+
const wav = mediaType === "audio/wav" ? audio : wrapPcmAsWav(audio);
|
|
1256
|
+
const logAudio = mediaType === "audio/wav" ? output.audio : Buffer.from(wav).toString("base64");
|
|
1257
|
+
let alignment: Awaited<ReturnType<typeof alignOpenAISpeech>> | undefined;
|
|
1258
|
+
|
|
1259
|
+
if (input.withTimestamps) {
|
|
1260
|
+
try {
|
|
1261
|
+
alignment = await alignOpenAISpeech(wav, input.text, signal);
|
|
1262
|
+
output.audioTimestamps = alignment.audioTimestamps;
|
|
1263
|
+
output.durationSec = alignment.durationSec;
|
|
1264
|
+
output.timestampsSource = "aligned";
|
|
1265
|
+
} catch (error) {
|
|
1266
|
+
// The speech itself succeeded; timing is best-effort and its failure is reported, not thrown.
|
|
1267
|
+
output.timestampsError = error instanceof Error ? error.message : String(error);
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
const speechCost = openaiSpeechCost(id, usage);
|
|
1272
|
+
|
|
1273
|
+
// The alignment pass is a Grok STT call over the same audio, priced with the speech.
|
|
1274
|
+
const alignCost = alignment
|
|
1275
|
+
? (sttCost(`grok/${GROK_STT_DEFAULT_MODEL}`, alignment.durationSec)?.costUsd ?? 0)
|
|
1276
|
+
: 0;
|
|
1223
1277
|
|
|
1224
1278
|
const log: MediaRunLog = {
|
|
1225
1279
|
tokenName: output.tokenName,
|
|
1226
1280
|
response: audioForLog(logAudio, "audio/wav", audio.byteLength),
|
|
1227
1281
|
firstOutputAt: firstAudioAt,
|
|
1282
|
+
cost: speechCost && { ...speechCost, costUsd: speechCost.costUsd + alignCost },
|
|
1228
1283
|
steps: [
|
|
1229
1284
|
{
|
|
1230
1285
|
toolCallId: "speech:0",
|
|
@@ -1235,6 +1290,7 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
|
|
|
1235
1290
|
voice: request.voice,
|
|
1236
1291
|
format: request.format ?? "wav",
|
|
1237
1292
|
instructions: input.instructions,
|
|
1293
|
+
withTimestamps: input.withTimestamps,
|
|
1238
1294
|
characters: input.text.length,
|
|
1239
1295
|
},
|
|
1240
1296
|
result: JSON.stringify({
|
|
@@ -1242,6 +1298,14 @@ async function speakOpenAI(input: SpeakInput): Promise<SpeakOutput> {
|
|
|
1242
1298
|
audioBytes: audio.byteLength,
|
|
1243
1299
|
transcript,
|
|
1244
1300
|
usage,
|
|
1301
|
+
alignment: alignment && {
|
|
1302
|
+
heard: alignment.heard,
|
|
1303
|
+
matchedWords: alignment.matchedWords,
|
|
1304
|
+
scriptWords: alignment.scriptWords,
|
|
1305
|
+
},
|
|
1306
|
+
timestampsError: output.timestampsError,
|
|
1307
|
+
// Word timing for the request-log detail player.
|
|
1308
|
+
words: alignment && wordsFromCharTimestamps(alignment.audioTimestamps),
|
|
1245
1309
|
}),
|
|
1246
1310
|
},
|
|
1247
1311
|
],
|
|
@@ -2227,7 +2291,7 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2227
2291
|
...selection,
|
|
2228
2292
|
});
|
|
2229
2293
|
|
|
2230
|
-
const { text, language, duration } = dispatched.result;
|
|
2294
|
+
const { text, language, duration, words } = dispatched.result;
|
|
2231
2295
|
|
|
2232
2296
|
const output: TranscribeOutput = { text, model: route, tokenName: dispatched.tokenName };
|
|
2233
2297
|
|
|
@@ -2237,9 +2301,12 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2237
2301
|
|
|
2238
2302
|
if (requestLogId !== undefined) output.requestLogId = requestLogId;
|
|
2239
2303
|
|
|
2304
|
+
if (words) output.words = words.map((w) => ({ text: w.text, start: w.start, end: w.end }));
|
|
2305
|
+
|
|
2240
2306
|
const log: MediaRunLog = {
|
|
2241
2307
|
tokenName: output.tokenName,
|
|
2242
2308
|
response: output.text,
|
|
2309
|
+
cost: sttCost(route, output.durationSec),
|
|
2243
2310
|
steps: [
|
|
2244
2311
|
{
|
|
2245
2312
|
toolCallId: "transcription:0",
|
|
@@ -2255,6 +2322,8 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2255
2322
|
text: output.text,
|
|
2256
2323
|
language: output.language,
|
|
2257
2324
|
durationSec: output.durationSec,
|
|
2325
|
+
// Word timing of the input audio for the request-log detail player.
|
|
2326
|
+
words: output.words,
|
|
2258
2327
|
}),
|
|
2259
2328
|
},
|
|
2260
2329
|
],
|
|
@@ -2269,17 +2338,7 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2269
2338
|
async speak(params: SpeakInput): Promise<SpeakOutput> {
|
|
2270
2339
|
const input = parseMediaInput(SpeakInput, params);
|
|
2271
2340
|
|
|
2272
|
-
if (voiceProvider(input.model) === "openai")
|
|
2273
|
-
if (input.withTimestamps) {
|
|
2274
|
-
throw new BadRequestException(
|
|
2275
|
-
SD("qgrid.openaiVoiceInvalidRequest")(
|
|
2276
|
-
"withTimestamps is available only for grok/ speech; OpenAI realtime has no timing data",
|
|
2277
|
-
),
|
|
2278
|
-
);
|
|
2279
|
-
}
|
|
2280
|
-
|
|
2281
|
-
return speakOpenAI(input);
|
|
2282
|
-
}
|
|
2341
|
+
if (voiceProvider(input.model) === "openai") return speakOpenAI(input);
|
|
2283
2342
|
|
|
2284
2343
|
const voice = grokVoice();
|
|
2285
2344
|
const selection = await resolveGrokTokenSelection(input.tokenName);
|
|
@@ -2290,7 +2349,7 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2290
2349
|
voice: input.voice ?? GROK_TTS_DEFAULT_VOICE,
|
|
2291
2350
|
language: input.language ?? GROK_TTS_DEFAULT_LANGUAGE,
|
|
2292
2351
|
format: input.format ?? GROK_TTS_DEFAULT_FORMAT,
|
|
2293
|
-
|
|
2352
|
+
with_timestamps: input.withTimestamps,
|
|
2294
2353
|
};
|
|
2295
2354
|
|
|
2296
2355
|
const start = {
|
|
@@ -2315,6 +2374,7 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2315
2374
|
|
|
2316
2375
|
if (dispatched.result.audioTimestamps) {
|
|
2317
2376
|
output.audioTimestamps = dispatched.result.audioTimestamps;
|
|
2377
|
+
output.timestampsSource = "provider";
|
|
2318
2378
|
}
|
|
2319
2379
|
|
|
2320
2380
|
if (dispatched.result.durationSec !== undefined) {
|
|
@@ -2325,6 +2385,7 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2325
2385
|
tokenName: output.tokenName,
|
|
2326
2386
|
response: audioForLog(output.audio, output.mimeType, audioBytes),
|
|
2327
2387
|
firstOutputAt: dispatched.result.firstByteAt,
|
|
2388
|
+
cost: grokSpeechCost(input.text.length),
|
|
2328
2389
|
steps: [
|
|
2329
2390
|
{
|
|
2330
2391
|
toolCallId: "speech:0",
|
|
@@ -2341,7 +2402,8 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2341
2402
|
mimeType: output.mimeType,
|
|
2342
2403
|
audioBytes,
|
|
2343
2404
|
durationSec: output.durationSec,
|
|
2344
|
-
|
|
2405
|
+
// Word timing for the request-log detail player.
|
|
2406
|
+
words: output.audioTimestamps && wordsFromCharTimestamps(output.audioTimestamps),
|
|
2345
2407
|
}),
|
|
2346
2408
|
},
|
|
2347
2409
|
],
|
|
@@ -530,6 +530,12 @@ export const TranscribeInput = z.object({
|
|
|
530
530
|
|
|
531
531
|
export type TranscribeInput = z.infer<typeof TranscribeInput>;
|
|
532
532
|
|
|
533
|
+
const TranscribedWord = z.object({
|
|
534
|
+
text: z.string(),
|
|
535
|
+
start: z.number(),
|
|
536
|
+
end: z.number(),
|
|
537
|
+
});
|
|
538
|
+
|
|
533
539
|
export const TranscribeOutput = z.object({
|
|
534
540
|
text: z.string(),
|
|
535
541
|
language: z.string().optional(),
|
|
@@ -537,6 +543,9 @@ export const TranscribeOutput = z.object({
|
|
|
537
543
|
model: z.string(),
|
|
538
544
|
tokenName: z.string(),
|
|
539
545
|
requestLogId: z.number().optional(),
|
|
546
|
+
// Grok only: each heard word with its [start, end] seconds. OpenAI realtime transcription
|
|
547
|
+
// reports no timing.
|
|
548
|
+
words: z.array(TranscribedWord).optional(),
|
|
540
549
|
});
|
|
541
550
|
|
|
542
551
|
export type TranscribeOutput = z.infer<typeof TranscribeOutput>;
|
|
@@ -549,8 +558,9 @@ export const SpeakInput = z.object({
|
|
|
549
558
|
format: z.enum(["mp3", "wav", "pcm", "mulaw", "alaw"]).optional(),
|
|
550
559
|
// OpenAI realtime speech only: style guidance appended to the verbatim-repeat instruction.
|
|
551
560
|
instructions: z.string().min(1).max(2_000).optional(),
|
|
552
|
-
//
|
|
553
|
-
// no timing data
|
|
561
|
+
// Per-character timing in the output (`audioTimestamps`). Grok returns it natively; for OpenAI
|
|
562
|
+
// realtime (no timing data) qgrid transcribes the generated audio with Grok STT and aligns the
|
|
563
|
+
// heard words to the text (`timestampsSource: "aligned"`).
|
|
554
564
|
withTimestamps: z.boolean().optional(),
|
|
555
565
|
...MediaCallOptions,
|
|
556
566
|
});
|
|
@@ -572,6 +582,11 @@ export const SpeakOutput = z.object({
|
|
|
572
582
|
})
|
|
573
583
|
.optional(),
|
|
574
584
|
durationSec: z.number().optional(),
|
|
585
|
+
// "provider" when the TTS provider timed the audio itself, "aligned" when qgrid inferred it from
|
|
586
|
+
// Grok STT word timing.
|
|
587
|
+
timestampsSource: z.enum(["provider", "aligned"]).optional(),
|
|
588
|
+
// Set when timestamps were requested but could not be produced; the audio is still returned.
|
|
589
|
+
timestampsError: z.string().optional(),
|
|
575
590
|
});
|
|
576
591
|
|
|
577
592
|
export type SpeakOutput = z.infer<typeof SpeakOutput>;
|
|
@@ -5,6 +5,8 @@ import {
|
|
|
5
5
|
getModelCosts,
|
|
6
6
|
grokImageCost,
|
|
7
7
|
grokReportedCost,
|
|
8
|
+
openaiSpeechCost,
|
|
9
|
+
sttCost,
|
|
8
10
|
usdFromGrokTicks,
|
|
9
11
|
} from "./model-cost";
|
|
10
12
|
|
|
@@ -407,3 +409,15 @@ describe("calculateCostUsd", () => {
|
|
|
407
409
|
);
|
|
408
410
|
});
|
|
409
411
|
});
|
|
412
|
+
|
|
413
|
+
describe("voice cost", () => {
|
|
414
|
+
it("prices OpenAI speech by token type and transcription by minute; unknown models stay unpriced", () => {
|
|
415
|
+
// The 6-second ballad clip: 226 text in, 66 text out, 131 audio out on gpt-realtime-2.1-mini.
|
|
416
|
+
const usage = { inputTokens: 226, textTokens: 66, audioTokens: 131 };
|
|
417
|
+
|
|
418
|
+
expect(openaiSpeechCost("gpt-realtime-2.1-mini", usage)?.costUsd).toBeCloseTo(0.0029, 4);
|
|
419
|
+
expect(openaiSpeechCost("gpt-realtime-9", usage)).toBeUndefined();
|
|
420
|
+
expect(sttCost("openai/gpt-4o-transcribe", 30)?.costUsd).toBeCloseTo(0.003, 6);
|
|
421
|
+
expect(sttCost("openai/gpt-4o-transcribe", undefined)).toBeUndefined();
|
|
422
|
+
});
|
|
423
|
+
});
|
|
@@ -455,3 +455,60 @@ export function calculateCostUsd(
|
|
|
455
455
|
(serviceTier === "fast" ? (OPENAI_FAST_MULTIPLIERS.get(normalizedModel) ?? 1) : 1)
|
|
456
456
|
);
|
|
457
457
|
}
|
|
458
|
+
|
|
459
|
+
/** A voice call priced from the public API list price; subscription calls have no per-call bill. */
|
|
460
|
+
export type VoiceCost = { costUsd: number; costSource: "pricing_table"; ticks?: undefined };
|
|
461
|
+
|
|
462
|
+
// Public API list prices, checked 2026-11-09. OpenAI realtime speech: USD per 1M tokens (the usage
|
|
463
|
+
// does not split cached input, so all input is charged as uncached text).
|
|
464
|
+
const OPENAI_SPEECH_PRICES = new Map([
|
|
465
|
+
["gpt-realtime-2.1", { textIn: 4, textOut: 24, audioOut: 64 }],
|
|
466
|
+
["gpt-realtime-2.1-mini", { textIn: 0.6, textOut: 2.4, audioOut: 20 }],
|
|
467
|
+
["gpt-realtime-1.5", { textIn: 4, textOut: 16, audioOut: 64 }],
|
|
468
|
+
]);
|
|
469
|
+
|
|
470
|
+
// Transcription, USD per minute of audio (OpenAI's published per-minute estimates; Grok $0.10/hour).
|
|
471
|
+
const STT_USD_PER_MINUTE = new Map([
|
|
472
|
+
["openai/gpt-4o-transcribe", 0.006],
|
|
473
|
+
["openai/gpt-4o-mini-transcribe", 0.003],
|
|
474
|
+
["openai/gpt-transcribe", 0.0045],
|
|
475
|
+
["openai/gpt-live-transcribe", 0.017],
|
|
476
|
+
["openai/gpt-realtime-whisper", 0.017],
|
|
477
|
+
["openai/whisper-1", 0.006],
|
|
478
|
+
["grok/grok-voice-transcribe-2.0", 0.1 / 60],
|
|
479
|
+
]);
|
|
480
|
+
|
|
481
|
+
const GROK_TTS_USD_PER_CHARACTER = 15 / 1_000_000;
|
|
482
|
+
|
|
483
|
+
const priced = (costUsd: number): VoiceCost => ({ costUsd, costSource: "pricing_table" });
|
|
484
|
+
|
|
485
|
+
/** OpenAI realtime speech from its response usage; unknown models stay unpriced. */
|
|
486
|
+
export function openaiSpeechCost(
|
|
487
|
+
model: string,
|
|
488
|
+
usage: { inputTokens: number; textTokens: number; audioTokens: number },
|
|
489
|
+
): VoiceCost | undefined {
|
|
490
|
+
const price = OPENAI_SPEECH_PRICES.get(model);
|
|
491
|
+
|
|
492
|
+
if (!price) return undefined;
|
|
493
|
+
|
|
494
|
+
return priced(
|
|
495
|
+
(usage.inputTokens * price.textIn +
|
|
496
|
+
usage.textTokens * price.textOut +
|
|
497
|
+
usage.audioTokens * price.audioOut) /
|
|
498
|
+
1_000_000,
|
|
499
|
+
);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** Transcription by audio length; unknown models or a missing duration stay unpriced. */
|
|
503
|
+
export function sttCost(route: string, durationSec: number | undefined): VoiceCost | undefined {
|
|
504
|
+
const perMinute = STT_USD_PER_MINUTE.get(route);
|
|
505
|
+
|
|
506
|
+
return perMinute === undefined || durationSec === undefined
|
|
507
|
+
? undefined
|
|
508
|
+
: priced((perMinute * durationSec) / 60);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** Grok `/tts` by input characters. */
|
|
512
|
+
export function grokSpeechCost(characters: number): VoiceCost {
|
|
513
|
+
return priced(characters * GROK_TTS_USD_PER_CHARACTER);
|
|
514
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
|
|
3
|
+
import { type CharTimestamps } from "../../speech-alignment";
|
|
3
4
|
import { type JsonValue } from "../common/provider-types";
|
|
4
5
|
import { GROK_AUTH_ISSUER } from "./grok-constants";
|
|
5
6
|
|
|
@@ -274,6 +275,18 @@ export const GrokSttResponse = z.looseObject({
|
|
|
274
275
|
text: z.string(),
|
|
275
276
|
language: z.string().optional(),
|
|
276
277
|
duration: z.number().nonnegative().optional(),
|
|
278
|
+
// Word-level timing, sent by default (verified on the subscription token 2026-11-09); `speaker`
|
|
279
|
+
// only with diarize.
|
|
280
|
+
words: z
|
|
281
|
+
.array(
|
|
282
|
+
z.looseObject({
|
|
283
|
+
text: z.string(),
|
|
284
|
+
start: z.number(),
|
|
285
|
+
end: z.number(),
|
|
286
|
+
speaker: z.number().optional(),
|
|
287
|
+
}),
|
|
288
|
+
)
|
|
289
|
+
.optional(),
|
|
277
290
|
});
|
|
278
291
|
|
|
279
292
|
export type GrokSttResponse = z.infer<typeof GrokSttResponse>;
|
|
@@ -364,19 +377,11 @@ export interface GrokTranscribeRequest {
|
|
|
364
377
|
signal?: AbortSignal;
|
|
365
378
|
}
|
|
366
379
|
|
|
367
|
-
/** Per-character timing of the spoken text, named as `@ai-sdk/xai` exposes it. */
|
|
368
|
-
export interface GrokAudioTimestamps {
|
|
369
|
-
/** Input characters, including spaces, punctuation and speech tags. */
|
|
370
|
-
graphChars: string[];
|
|
371
|
-
/** `[start, end]` seconds for the character at the same index. */
|
|
372
|
-
graphTimes: Array<[number, number]>;
|
|
373
|
-
}
|
|
374
|
-
|
|
375
380
|
export interface GrokSpeechResult {
|
|
376
381
|
audio: Uint8Array;
|
|
377
382
|
mediaType: string;
|
|
378
|
-
/** Only with `with_timestamps
|
|
379
|
-
audioTimestamps?:
|
|
383
|
+
/** Only with `with_timestamps`; named as `@ai-sdk/xai` exposes it. */
|
|
384
|
+
audioTimestamps?: CharTimestamps;
|
|
380
385
|
durationSec?: number;
|
|
381
386
|
/** Epoch ms when the response headers arrived; /tts is not streamed, so this is first byte. */
|
|
382
387
|
firstByteAt?: number;
|
|
@@ -118,9 +118,9 @@ function transportError(message: string, afterSend: boolean, cause: unknown): Gr
|
|
|
118
118
|
return new GrokHttpError(classification, "", {}, { cause });
|
|
119
119
|
}
|
|
120
120
|
|
|
121
|
-
// `with_timestamps: true` envelope;
|
|
121
|
+
// `with_timestamps: true` envelope; optional fields nullable like @ai-sdk/xai's parser.
|
|
122
122
|
const GrokTtsTimestampsResponse = z.object({
|
|
123
|
-
audio: z.string()
|
|
123
|
+
audio: z.string(),
|
|
124
124
|
content_type: z.string().nullish(),
|
|
125
125
|
duration: z.number().nullish(),
|
|
126
126
|
audio_timestamps: z
|
|
@@ -154,7 +154,7 @@ async function readTimestampsBody(
|
|
|
154
154
|
throw invalidBodyError(response, "invalid timestamped TTS response", error);
|
|
155
155
|
}
|
|
156
156
|
|
|
157
|
-
const audio = new Uint8Array(Buffer.from(parsed.audio
|
|
157
|
+
const audio = new Uint8Array(Buffer.from(parsed.audio, "base64"));
|
|
158
158
|
|
|
159
159
|
if (audio.byteLength === 0) throw invalidBodyError(response, "empty audio body");
|
|
160
160
|
|
|
@@ -254,7 +254,7 @@ export class GrokVoiceClient implements GrokVoicePort {
|
|
|
254
254
|
voice: request.voice ?? GROK_TTS_DEFAULT_VOICE,
|
|
255
255
|
language: request.language ?? GROK_TTS_DEFAULT_LANGUAGE,
|
|
256
256
|
format: request.format ?? GROK_TTS_DEFAULT_FORMAT,
|
|
257
|
-
|
|
257
|
+
with_timestamps: request.with_timestamps,
|
|
258
258
|
});
|
|
259
259
|
|
|
260
260
|
const headers = {
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
|
|
3
|
+
import { alignScriptToWords, wordsFromCharTimestamps } from "./speech-alignment";
|
|
4
|
+
|
|
5
|
+
const spanOf = (alignment: ReturnType<typeof alignScriptToWords>, script: string, word: string) => {
|
|
6
|
+
const from = script.indexOf(word);
|
|
7
|
+
const times = alignment.audioTimestamps.graphTimes;
|
|
8
|
+
|
|
9
|
+
return [times[from]![0], times[from + word.length - 1]![1]];
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
describe("alignScriptToWords", () => {
|
|
13
|
+
it("spreads each heard word over its characters and gives spaces the pause", () => {
|
|
14
|
+
const script = "Hi there.";
|
|
15
|
+
const result = alignScriptToWords(
|
|
16
|
+
script,
|
|
17
|
+
[
|
|
18
|
+
{ text: "Hi", start: 0.1, end: 0.3 },
|
|
19
|
+
{ text: "there", start: 0.5, end: 1.0 },
|
|
20
|
+
],
|
|
21
|
+
1.2,
|
|
22
|
+
);
|
|
23
|
+
|
|
24
|
+
expect(result.matchedWords).toBe(2);
|
|
25
|
+
expect(result.audioTimestamps.graphChars.join("")).toBe(script);
|
|
26
|
+
expect(result.audioTimestamps.graphTimes[0]).toEqual([0.1, 0.2]);
|
|
27
|
+
expect(result.audioTimestamps.graphTimes[2]).toEqual([0.3, 0.5]); // the space
|
|
28
|
+
expect(spanOf(result, script, "there.")).toEqual([0.5, 1.0]);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it("skips a spoken preamble, keeps a mis-heard name in place, and fills a dropped word", () => {
|
|
32
|
+
const script = "I'm Carina. Nice to meet you.";
|
|
33
|
+
const heard = [
|
|
34
|
+
{ text: "Okay,", start: 0.0, end: 0.3 },
|
|
35
|
+
{ text: "let's", start: 0.3, end: 0.5 },
|
|
36
|
+
{ text: "read", start: 0.5, end: 0.7 },
|
|
37
|
+
{ text: "I'm", start: 1.0, end: 1.2 },
|
|
38
|
+
{ text: "Karina,", start: 1.2, end: 1.7 },
|
|
39
|
+
{ text: "nice", start: 2.0, end: 2.3 },
|
|
40
|
+
{ text: "meet", start: 2.5, end: 2.8 },
|
|
41
|
+
{ text: "you.", start: 2.8, end: 3.1 },
|
|
42
|
+
];
|
|
43
|
+
|
|
44
|
+
const result = alignScriptToWords(script, heard, 3.3);
|
|
45
|
+
|
|
46
|
+
expect(result).toMatchObject({ matchedWords: 4, scriptWords: 6 });
|
|
47
|
+
expect(spanOf(result, script, "I'm")).toEqual([1.0, 1.2]);
|
|
48
|
+
expect(spanOf(result, script, "Carina.")).toEqual([1.2, 1.7]);
|
|
49
|
+
// "to" was not heard: it takes the gap between "nice" and "meet".
|
|
50
|
+
expect(spanOf(result, script, "to")).toEqual([2.3, 2.5]);
|
|
51
|
+
expect(spanOf(result, script, "you.")).toEqual([2.8, 3.1]);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it("groups per-character timing into words spanning first to last character", () => {
|
|
55
|
+
expect(
|
|
56
|
+
wordsFromCharTimestamps({
|
|
57
|
+
graphChars: ["H", "i", " ", "y", "o", "u"],
|
|
58
|
+
graphTimes: [
|
|
59
|
+
[0, 0.1],
|
|
60
|
+
[0.1, 0.2],
|
|
61
|
+
[0.2, 0.3],
|
|
62
|
+
[0.3, 0.4],
|
|
63
|
+
[0.4, 0.5],
|
|
64
|
+
[0.5, 0.6],
|
|
65
|
+
],
|
|
66
|
+
}),
|
|
67
|
+
).toEqual([
|
|
68
|
+
{ text: "Hi", start: 0, end: 0.2 },
|
|
69
|
+
{ text: "you", start: 0.3, end: 0.6 },
|
|
70
|
+
]);
|
|
71
|
+
});
|
|
72
|
+
});
|