1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
|
//! Tests against the real servers.
//!
//! They skip themselves when nothing is listening, so `cargo test` stays
//! useful without 5 GB of models loaded. With the servers up they check what
//! unit tests cannot: that the protocol written here is the one the servers
//! speak, and that latencies are still where they were measured.
//!
//! To run them: scripts/servers.sh start && cargo test -- --ignored
use std::path::PathBuf;
use std::sync::{Mutex, MutexGuard, OnceLock};
use std::time::{Duration, Instant};
use asist_core::config::Config;
use asist_core::http::Cancel;
use asist_core::tools::{Tool, ToolRegistry};
use asist_llm::chat::Conversation;
use asist_llm::{Delta, LlmClient, Message};
use asist_tools::FrameSource;
use asist_tts::TtsClient;
/// The tests take turns on the GPU.
///
/// Both servers share a 4 GB card, and measured: with the synthesis test
/// running at the same time, the LLM first token goes from ~0.5 s to ~5 s.
/// In parallel this does not measure latency, it measures who got there
/// first. The real pipeline does not have this problem because synthesis
/// does not start until the model closes its first sentence.
fn exclusive() -> MutexGuard<'static, ()> {
static GPU: OnceLock<Mutex<()>> = OnceLock::new();
GPU.get_or_init(|| Mutex::new(()))
.lock()
.unwrap_or_else(|e| e.into_inner())
}
fn config() -> Config {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../config/asistente.toml");
Config::load(path).expect("could not load the configuration")
}
/// Returns the clients, or `None` if the servers are not up.
fn clients() -> Option<(Config, LlmClient, TtsClient)> {
let config = config();
let llm = LlmClient::new(config.llm_authority(), &config.llm);
let tts = TtsClient::new(config.tts_authority(), &config.tts);
if !llm.healthy() || !tts.healthy() {
eprintln!("servidores no disponibles; prueba omitida");
return None;
}
Some((config, llm, tts))
}
#[test]
fn llm_streams_without_thinking_aloud() {
let _gpu = exclusive();
let Some((config, llm, _)) = clients() else {
return;
};
let mut chat = Conversation::new(&config.general.system_prompt, 4);
chat.push(Message::user("Saluda en una frase corta."));
let started = Instant::now();
let mut ttft = None;
let outcome = llm
.stream(&chat, None, &Cancel::new(), |delta| {
if let Delta::Text(_) = delta {
ttft.get_or_insert_with(|| started.elapsed());
}
true
})
.expect("the LLM request failed");
assert!(!outcome.text.trim().is_empty(), "empty answer");
// The template with an unclosed <think> puts this at 7-9 s. If this test
// fails, llama-server was almost certainly started without --chat-template-file.
let ttft = ttft.expect("no fragment with text arrived");
assert!(
ttft < Duration::from_secs(3),
"the first token took {ttft:?}: was llama-server started with the no-reasoning template?"
);
assert!(
!outcome.text.contains("<think>"),
"reasoning is leaking into the answer: {}",
outcome.text
);
}
#[test]
fn llm_can_request_a_tool() {
let _gpu = exclusive();
let Some((config, llm, _)) = clients() else {
return;
};
let tools = ToolRegistry::from_config(&config.tools);
let mut chat = Conversation::new(
"Eres un asistente. Usa las herramientas disponibles cuando hagan falta.",
4,
);
chat.push(Message::user(
"¿Qué hora es exactamente? Usa la herramienta.",
));
let outcome = llm
.stream(&chat, Some(&tools), &Cancel::new(), |_| true)
.expect("the LLM request failed");
if outcome.tool_calls.is_empty() {
// A 2B model does not always manage to call; what is checked is that the
// round trip works, not that the model is smart.
eprintln!("the model did not ask for a tool: {}", outcome.text);
return;
}
let call = &outcome.tool_calls[0];
assert_eq!(call.name, "hora_actual");
let result = tools.dispatch(call);
assert!(result.ok, "the tool failed: {}", result.output);
assert!(!result.output.trim().is_empty());
}
#[test]
fn synthesis_starts_playing_before_it_finishes() {
let _gpu = exclusive();
let Some((config, _, tts)) = clients() else {
return;
};
if let Some(reference) = &config.tts.reference {
tts.register_voice(reference)
.expect("the voice was not registered");
}
// Without warmup, the first synthesis loads the graphs and measures the
// server startup instead of the steady state.
tts.warmup().expect("warmup failed");
let mut blocks = 0usize;
let outcome = tts
.speak(
"Hola, esto es una prueba de latencia del sintetizador de voz.",
&Cancel::new(),
|samples| {
if !samples.is_empty() {
blocks += 1;
}
true
},
)
.expect("synthesis failed");
assert!(outcome.samples > 0, "no audio received");
assert!(
blocks > 1,
"the audio arrived all at once ({blocks} block): check --codec-chunk-dur, \
whose 24 s default blocks streaming"
);
let ttfb = outcome.ttfb.expect("no first-block mark");
assert!(
ttfb < Duration::from_secs(2),
"first audio took {ttfb:?}; 585 ms was measured with --codec-chunk-dur 1.0"
);
eprintln!(
"ttfb={:?} audio={:.2}s rtf={:.2}",
ttfb,
outcome.audio_secs(),
outcome.rtf()
);
}
#[test]
fn synthesis_can_be_cut_mid_sentence() {
let _gpu = exclusive();
let Some((config, _, tts)) = clients() else {
return;
};
if let Some(reference) = &config.tts.reference {
let _ = tts.register_voice(reference);
}
// It is the operation barge-in relies on: if it could not be cut, the
// assistant would keep talking over the user until the sentence ended.
let cancel = Cancel::new();
let mut received = 0usize;
let outcome = tts
.speak(
"Esta es una frase larga que no debería llegar a escucharse entera \
porque se va a cortar en cuanto empiece a sonar el primer bloque.",
&cancel,
|samples| {
received += samples.len();
// Cut at the first block.
false
},
)
.expect("synthesis failed");
assert!(outcome.cancelled, "it should have been marked as cancelled");
assert!(
outcome.audio_secs() < 3.0,
"{:.1} s of audio received: the cut had no effect",
outcome.audio_secs()
);
}
#[test]
fn cloned_voice_gets_registered() {
let _gpu = exclusive();
let Some((config, _, tts)) = clients() else {
return;
};
let Some(reference) = &config.tts.reference else {
eprintln!("no reference voice configured; test skipped");
return;
};
tts.register_voice(reference)
.expect("the voice was not registered");
let voices = tts.voices().expect("could not list the voices");
assert!(
voices.contains(&reference.name),
"«{}» no aparece entre {voices:?}",
reference.name
);
}
#[test]
#[ignore = "loads the ASR model (~200 MB) and decodes; slow"]
fn asr_transcribes_what_tts_synthesizes() {
let _gpu = exclusive();
// The full loop without a microphone: a known sentence is synthesized and
// the recognizer is checked to get it back. It is the only test that
// exercises ASR and TTS on the same audio.
let Some((config, _, tts)) = clients() else {
return;
};
if let Some(reference) = &config.tts.reference {
let _ = tts.register_voice(reference);
}
let sentence = "hola qué tal estás hoy";
let mut audio: Vec<f32> = Vec::new();
tts.speak(sentence, &Cancel::new(), |samples| {
audio.extend_from_slice(samples);
true
})
.expect("synthesis failed");
assert!(!audio.is_empty(), "no audio was generated");
let
|