-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvoice_agent_audio_input_evaluation.py
More file actions
2262 lines (1995 loc) · 95.4 KB
/
Copy pathvoice_agent_audio_input_evaluation.py
File metadata and controls
2262 lines (1995 loc) · 95.4 KB
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Voice Agent Audio Input Evaluation — Modern CLI Tool
Processes audio files through the Azure VoiceLive SDK for evaluation.
Uses async/await directly (no threading wrappers) with PTT/VAD mode support.
Patterns aligned with the container-app implementation.
"""
import os
import re
import json
import secrets
import sys
import wave
import base64
import logging
import argparse
import asyncio
import tempfile
import shutil
import numpy as np
import requests
from datetime import datetime
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Any
from dotenv import load_dotenv
from azure.identity import DefaultAzureCredential
from azure.core.credentials import AzureKeyCredential, AccessToken
from azure.ai.voicelive.aio import connect as voicelive_connect
from azure.ai.voicelive.models import (
ServerEventType,
RequestSession,
ServerVad,
AzureSemanticVadMultilingual,
AzureStandardVoice,
OpenAIVoice,
Modality,
InputAudioFormat,
OutputAudioFormat,
AudioInputTranscriptionOptions,
AudioNoiseReduction,
AudioEchoCancellation,
EouDetection,
FunctionCallOutputItem,
ItemType,
)
# Force UTF-8 encoding for stdout/stderr to handle international characters
if sys.stdout.encoding != 'utf-8':
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
if sys.stderr.encoding != 'utf-8':
sys.stderr.reconfigure(encoding='utf-8', errors='replace')
logger = logging.getLogger(__name__)
class StaticTokenCredential:
"""Credential that returns a pre-fetched bearer token (avoids AzureCLI timeout)."""
def __init__(self, token: str):
self._token = token
def get_token(self, *scopes, **kwargs):
return AccessToken(self._token, 0)
# ---------------------------------------------------------------------------
# Default system instruction
# ---------------------------------------------------------------------------
SYSTEM_INSTRUCTION = "You are a helpful agent assisting users with their questions."
# ---------------------------------------------------------------------------
# Eval naming helpers (aligned with evaluation agent naming)
# ---------------------------------------------------------------------------
def _sanitize_eval_name(name: str, max_length: int = 80) -> str:
"""Sanitize a name for use in eval group/run names (safe for Foundry and Table Storage)."""
clean = re.sub(r'[^A-Za-z0-9_-]', '_', name)
clean = re.sub(r'_+', '_', clean).strip('_')
return clean[:max_length] if clean else "unnamed"
def generate_harness_eval_group_name(
config=None,
dataset_name: str = "",
group_by: str = "dataset",
) -> str:
"""Generate eval group name, grouped by dataset (default) or settings.
Args:
config: SessionConfig object (used when group_by="settings").
dataset_name: Dataset file path or name (used when group_by="dataset").
group_by: "dataset" (default) or "settings".
Returns:
Sanitized eval group name string.
"""
if group_by == "settings":
return _generate_harness_eval_group_name_by_settings(config)
# Default: group by dataset
basename = os.path.splitext(os.path.basename(dataset_name))[0] if dataset_name else ""
if not basename:
return _generate_harness_eval_group_name_by_settings(config)
return f"harness_{_sanitize_eval_name(basename, max_length=72)}"
def _generate_harness_eval_group_name_by_settings(config) -> str:
"""Generate eval group name from session config (legacy behavior).
Format: harness_{model}_{voice}_{vad}_{eod}
"""
model = getattr(config, 'model', None) or 'gpt-realtime'
voice = getattr(config, 'voice', None) or 'alloy'
vad = getattr(config, 'vad_threshold', None)
eod = getattr(config, 'silence_duration_ms', None)
model_clean = str(model).replace("-", "").replace(".", "")
voice_short = _short_voice_name(str(voice))
vad_str = str(vad) if vad is not None else "default"
eod_str = str(eod) if eod is not None else "default"
return f"harness_{model_clean}_{voice_short}_{vad_str}_{eod_str}"
def _short_voice_name(voice: str) -> str:
"""Extract a short, readable voice identifier.
e.g. 'en-US-Ava:DragonHDLatestNeural' -> 'Ava'
'alloy' -> 'alloy'
"""
if not voice or voice == "None":
return ""
if ':' in voice:
# Azure voice format: "en-US-Ava:DragonHDLatestNeural" -> "Ava"
prefix = voice.split(':')[0] # "en-US-Ava"
parts = prefix.split('-')
return parts[-1] if len(parts) >= 3 else prefix
return voice
def _settings_summary(config) -> str:
"""Short settings summary for run names (when grouping by dataset)."""
if not config:
return ""
model = str(getattr(config, 'model', '') or '').replace("-", "").replace(".", "")
voice = _short_voice_name(str(getattr(config, 'voice', '') or ''))
vad = getattr(config, 'vad_threshold', None)
eod = getattr(config, 'silence_duration_ms', None)
parts = [model, voice]
if vad is not None:
parts.append(f"vad{vad}")
if eod is not None:
parts.append(f"eod{eod}")
return "_".join(p for p in parts if p)
def generate_harness_run_name(
dataset_name: str,
dataset_version: str,
evaluators: list,
config=None,
group_by: str = "dataset",
) -> str:
"""Generate run name with metadata, matching agent naming pattern.
Content complements the eval group:
- group_by="dataset": run highlights settings (config already identifies dataset)
- group_by="settings": run highlights dataset (config already identifies settings)
Format: YYYYMMDD-HHMMSS-xxx | {complement_info} | {evaluator_summary}
"""
timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
random_suffix = secrets.token_hex(2)[:3]
if not evaluators or len(evaluators) >= 10:
eval_summary = "all"
elif len(evaluators) >= 5:
eval_summary = "default"
else:
eval_summary = "subset"
dataset_base = os.path.splitext(os.path.basename(dataset_name))[0] if dataset_name else "dataset"
if group_by == "dataset" and config:
# Group is the dataset — run name highlights settings
hint = _settings_summary(config)
return f"{timestamp}-{random_suffix} | {hint} | {eval_summary}" if hint else \
f"{timestamp}-{random_suffix} | {dataset_base}_v{dataset_version} | {eval_summary}"
else:
# Group is the settings (or no config) — run name highlights dataset
return f"{timestamp}-{random_suffix} | {dataset_base}_v{dataset_version} | {eval_summary}"
def journal_harness_eval_group(
eval_group_name: str,
config,
eval_group_id: str = "",
output_dir: str = ".",
group_by: str = "dataset",
) -> None:
"""Record eval group -> config mapping in a local journal file.
Writes to {output_dir}/eval_journal.jsonl (append mode).
"""
journal_path = os.path.join(output_dir, "eval_journal.jsonl")
entry = {
"timestamp": datetime.now().isoformat(),
"eval_group_name": eval_group_name,
"eval_group_id": eval_group_id,
"group_by": group_by,
"model": getattr(config, 'model', '') if config else '',
"voice": getattr(config, 'voice', '') if config else '',
"vad_threshold": str(getattr(config, 'vad_threshold', '')) if config else '',
"silence_duration_ms": str(getattr(config, 'silence_duration_ms', '')) if config else '',
}
try:
with open(journal_path, 'a', encoding='utf-8') as f:
f.write(json.dumps(entry) + '\n')
logger.info(f"Journaled eval group: {eval_group_name} -> {journal_path}")
except Exception as e:
logger.warning(f"Failed to journal eval group: {e}")
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def sanitize_text_for_utf8(text: str) -> str:
"""Sanitize text to valid UTF-8, replacing smart quotes and control chars."""
if not isinstance(text, str) or not text:
return text or ""
try:
replacements = {
'\u2018': "'", '\u2019': "'", '\u201A': "'", '\u201B': "'",
'\u201C': '"', '\u201D': '"', '\u201E': '"', '\u201F': '"',
'\u2013': '-', '\u2014': '-', '\u2015': '-',
'\u2026': '...', '\u00A0': ' ',
}
for uc, asc in replacements.items():
text = text.replace(uc, asc)
text = re.sub(r'[\x00-\x1F\x7F-\x9F]', '', text)
text = text.replace('\ufffd', '').replace('\u0000', '')
text = text.encode('utf-8', errors='replace').decode('utf-8')
text = re.sub(r'\s+', ' ', text).strip()
return text
except (UnicodeEncodeError, UnicodeDecodeError, AttributeError):
try:
return text.encode('ascii', errors='ignore').decode('ascii').strip()
except Exception:
return ""
# ---------------------------------------------------------------------------
# Dataclasses
# ---------------------------------------------------------------------------
@dataclass
class SessionConfig:
"""Configuration for a VoiceLive session.
Aligned with Container App's SessionConfig for feature parity.
Parameters can be set via CLI args or loaded from a JSON config file.
Note: `instructions`, `tools`, and `tool_definitions` are set from dataset
metadata, not via CLI or config file.
"""
instructions: str = SYSTEM_INSTRUCTION
model: str = "gpt-realtime"
voice: str = "en-US-Ava:DragonHDLatestNeural"
voice_type: str = "azure-standard"
sample_rate: int = 24000
push_to_talk: bool = False
enable_barge_in: bool = True
# Audio processing
noise_reduction: str = "azure_deep_noise_suppression"
echo_cancellation: str = "server_echo_cancellation"
# Transcription
transcription_model: Optional[str] = None # Auto-set based on model if None
# Turn detection (VAD)
vad_type: str = "azure_semantic_vad_multilingual"
vad_threshold: Optional[float] = None
silence_duration_ms: Optional[int] = None
# End-of-utterance detection
use_eou_detection: bool = True
eou_model: str = "semantic_detection_v1_multilingual"
# Tools
tools: Optional[List[Dict[str, Any]]] = None
tool_definitions: Optional[List[Dict[str, Any]]] = None
# Agent mode (Foundry Agent integration)
agent_name: Optional[str] = None
project_name: Optional[str] = None
agent_version: Optional[str] = None
conversation_id: Optional[str] = None
foundry_resource_override: Optional[str] = None
authentication_identity_client_id: Optional[str] = None
# Override tracking (set during config resolution, not by user)
_voice_explicitly_set: bool = False
_vad_explicitly_set: bool = False
def get_transcription_model(self) -> str:
"""Return the appropriate transcription model for the configured model."""
if self.transcription_model:
return self.transcription_model
if self.model == "gpt-realtime":
return "gpt-4o-transcribe"
elif self.model == "gpt-realtime-mini":
return "gpt-4o-mini-transcribe"
return "azure-speech"
def supports_eou_detection(self) -> bool:
"""Check if the model supports end-of-utterance detection."""
return self.model not in ("gpt-realtime", "gpt-realtime-mini")
def get_final_instructions(self) -> str:
"""Return instructions with tool hint when tools are configured."""
if self.tools:
return f"{self.instructions} Use available tools when appropriate."
return self.instructions
@property
def is_agent_mode(self) -> bool:
"""True when agent_name and project_name are set (Foundry Agent integration)."""
return bool(self.agent_name and self.project_name)
def build_agent_config(self) -> Optional[Dict[str, Any]]:
"""Build agent connection kwargs for VoiceLive connect() in agent mode.
As of azure-ai-voicelive 1.2.0, agent settings are passed as individual
keyword arguments to connect() (the old AgentSessionConfig dict param was
removed). The keys returned here match connect()'s kwarg names exactly.
"""
if not self.is_agent_mode:
return None
config: Dict[str, Any] = {
"agent_name": self.agent_name,
"project_name": self.project_name,
}
if self.agent_version:
config["agent_version"] = self.agent_version
if self.conversation_id:
config["conversation_id"] = self.conversation_id
if self.foundry_resource_override:
config["foundry_resource_override"] = self.foundry_resource_override
if self.authentication_identity_client_id and self.foundry_resource_override:
config["authentication_identity_client_id"] = self.authentication_identity_client_id
return config
@dataclass
class ConversationTurn:
"""Data collected from a single conversation turn."""
turn_number: int = 0
user_transcription: str = ""
assistant_response: str = ""
assistant_audio_received: bool = False
tool_calls: List[Dict[str, Any]] = field(default_factory=list)
tool_results: List[Dict[str, Any]] = field(default_factory=list)
response_audio_chunks: List[bytes] = field(default_factory=list)
# Barge-in / auto-truncation
was_truncated: bool = False
response_full: str = "" # Full response before truncation
# Timing
audio_send_end_time: Optional[datetime] = None
transcription_complete_time: Optional[datetime] = None
first_text_response_time: Optional[datetime] = None
first_audio_response_time: Optional[datetime] = None
def calculate_metrics(self) -> Dict[str, float]:
"""Calculate latency metrics for this turn."""
metrics: Dict[str, float] = {}
if self.audio_send_end_time:
if self.transcription_complete_time:
metrics["transcription_latency_seconds"] = (
self.transcription_complete_time - self.audio_send_end_time
).total_seconds()
if self.first_text_response_time:
metrics["text_response_latency_seconds"] = (
self.first_text_response_time - self.audio_send_end_time
).total_seconds()
if self.first_audio_response_time:
metrics["audio_response_latency_seconds"] = (
self.first_audio_response_time - self.audio_send_end_time
).total_seconds()
return metrics
@dataclass
class DatasetEntry:
"""Parsed entry from a JSONL dataset file.
Supports two audio source formats:
- Legacy: ``audio_path`` points to a local WAV file (WavPath field).
- Media: ``audio_media_ref`` holds ``{"data": "<url_or_base64>", "format": "wav"}``
from Foundry's ``input_audio`` content type. Resolved to a temp
file at processing time via ``_resolve_audio_from_media()``.
"""
audio_path: Optional[str] = None
audio_media_ref: Optional[Dict[str, str]] = None
ground_truth: Optional[str] = None
question: Optional[str] = None
tool_definitions: Optional[List[Dict[str, Any]]] = None
conversation_id: str = "default"
system_prompt: Optional[str] = None
barge_in: bool = False
# ---------------------------------------------------------------------------
# Tool registry
# ---------------------------------------------------------------------------
def get_horoscope(sign: str) -> str:
"""Return a horoscope for the given zodiac sign."""
return f"{sign}: Next Tuesday you will befriend a baby otter."
def fetchWeather(location: str) -> str:
"""Return a fake weather report for *location*."""
return f"The weather in {location} is sunny with a high of 75°F."
TOOL_REGISTRY: Dict[str, Any] = {
"get_horoscope": get_horoscope,
"fetchWeather": fetchWeather,
# Generic stubs from container app
"get_weather": lambda **a: json.dumps({"temperature": 72, "condition": "sunny", "location": a.get("location", "unknown")}),
"search": lambda **a: json.dumps({"results": [f"Result for: {a.get('query', '')}"]}),
"get_time": lambda **a: json.dumps({"time": datetime.now().strftime("%H:%M"), "timezone": a.get("timezone", "UTC")}),
}
def execute_tool(name: str, args: dict) -> str:
"""Execute a tool by name and return the result string."""
tool_fn = TOOL_REGISTRY.get(name)
if tool_fn:
try:
if isinstance(args, dict) and "raw" not in args:
return str(tool_fn(**args) if args else tool_fn())
return f"[{name}: {args}]"
except Exception as e:
return f"[Tool {name} error: {e}]"
return json.dumps({"error": f"Unknown tool: {name}", "status": "not_found"})
# ---------------------------------------------------------------------------
# Audio loading
# ---------------------------------------------------------------------------
def load_audio_file(path: str, target_rate: int = 24000) -> bytes:
"""Load a WAV file and return PCM16 bytes resampled to *target_rate*.
Supports PCM (8/16/24/32-bit) and IEEE float32 WAVs.
"""
import struct as _struct
try:
with wave.open(path, 'rb') as wf:
sample_rate = wf.getframerate()
n_channels = wf.getnchannels()
sample_width = wf.getsampwidth()
raw = wf.readframes(wf.getnframes())
if sample_width == 2:
audio = np.frombuffer(raw, dtype=np.int16)
elif sample_width == 1:
audio = np.frombuffer(raw, dtype=np.uint8).astype(np.int16) * 256
elif sample_width == 4:
audio = np.frombuffer(raw, dtype=np.int32)
audio = (audio >> 16).astype(np.int16)
else:
raise ValueError(f"Unsupported sample width: {sample_width}")
except wave.Error:
# IEEE float32 WAVs (format tag 3) — wave module can't read these
with open(path, 'rb') as f:
data = f.read()
# Parse RIFF header manually
if data[:4] != b'RIFF' or data[8:12] != b'WAVE':
raise ValueError(f"Not a valid WAV file: {path}")
pos = 12
sample_rate = n_channels = 0
audio_data = b''
while pos < len(data) - 8:
chunk_id = data[pos:pos+4]
chunk_size = _struct.unpack_from('<I', data, pos+4)[0]
if chunk_id == b'fmt ':
n_channels = _struct.unpack_from('<H', data, pos+10)[0]
sample_rate = _struct.unpack_from('<I', data, pos+12)[0]
elif chunk_id == b'data':
audio_data = data[pos+8:pos+8+chunk_size]
pos += 8 + chunk_size
if not audio_data:
raise ValueError(f"No audio data found in: {path}")
# Convert float32 samples to int16
float_audio = np.frombuffer(audio_data, dtype=np.float32)
audio = np.clip(float_audio * 32767, -32768, 32767).astype(np.int16)
# Stereo → mono
if n_channels == 2:
audio = audio.reshape(-1, 2).mean(axis=1).astype(np.int16)
# Resample
if sample_rate != target_rate:
duration = len(audio) / sample_rate
target_length = int(duration * target_rate)
indices = np.linspace(0, len(audio) - 1, target_length)
audio = np.interp(indices, np.arange(len(audio)), audio).astype(np.int16)
return audio.tobytes()
# ---------------------------------------------------------------------------
# Dataset reading
# ---------------------------------------------------------------------------
def read_dataset(path: str) -> List[DatasetEntry]:
"""Read a JSONL dataset file and return parsed entries.
Supports three audio source formats:
1. **Legacy (WavPath)** — ``{"WavPath": "file.wav", ...}``
2. **Media in messages** — Foundry media dataset with ``input_audio``
content parts inside a ``messages`` array.
3. **Top-level media** — ``{"audio": {"type": "input_audio", ...}, ...}``
"""
if not os.path.exists(path):
logger.error(f"Dataset file not found: {path}")
return []
dataset_dir = os.path.dirname(os.path.abspath(path))
entries: List[DatasetEntry] = []
with open(path, 'r', encoding='utf-8') as f:
for line_num, line in enumerate(f, 1):
line = line.strip()
if not line:
continue
try:
record = json.loads(line)
except json.JSONDecodeError as e:
logger.warning(f"Line {line_num}: JSON parse error: {e}")
continue
# --- Detect audio source format --------------------------------
audio_path: Optional[str] = None
audio_media_ref: Optional[Dict[str, str]] = None
# 1. Check for input_audio inside messages (Foundry media format)
media_ref = _extract_media_ref(record)
if media_ref:
audio_media_ref = media_ref
else:
# 2. Legacy WavPath / audio / audio_path field (strings only)
raw_audio = record.get('audio')
wav_path = (
record.get('WavPath')
or (raw_audio if isinstance(raw_audio, str) else None)
or record.get('audio_path')
)
if wav_path:
resolved = _resolve_audio_path(wav_path, dataset_dir)
if resolved:
audio_path = resolved
else:
logger.warning(f"Line {line_num}: audio file not found: {wav_path}")
continue
if not audio_path and not audio_media_ref:
logger.warning(f"Line {line_num}: no audio source found (WavPath or input_audio)")
continue
# --- Extract metadata ------------------------------------------
tool_defs = record.get('tool_definitions', [])
if isinstance(tool_defs, dict):
tool_defs = [tool_defs]
answer_raw = record.get('Answer') or record.get('answer') or record.get('expected_output')
# Normalize list-type answers (e.g. speech-trivia-qa uses ["Paris", "City of Paris"])
if isinstance(answer_raw, list):
answer_raw = " OR ".join(str(a) for a in answer_raw if a) if answer_raw else None
# Extract question from legacy field or from messages text parts
question = record.get('Question') or record.get('question')
if not question:
question = _extract_text_from_messages(record)
# Extract system prompt from legacy field or from messages
system_prompt = record.get('system_prompt')
if not system_prompt:
system_prompt = _extract_system_prompt_from_messages(record)
entries.append(DatasetEntry(
audio_path=audio_path,
audio_media_ref=audio_media_ref,
ground_truth=answer_raw,
question=question,
tool_definitions=tool_defs if tool_defs else [],
conversation_id=record.get('conversationID') or record.get('conversation_id') or 'default',
system_prompt=system_prompt,
barge_in=bool(record.get('barge_in', False)),
))
media_count = sum(1 for e in entries if e.audio_media_ref)
legacy_count = sum(1 for e in entries if e.audio_path)
logger.info(f"Loaded {len(entries)} entries from {path} (legacy={legacy_count}, media={media_count})")
return entries
def _extract_media_ref(record: dict) -> Optional[Dict[str, str]]:
"""Extract the first ``input_audio`` reference from a record.
Checks both Foundry ``messages`` array and top-level ``audio`` field.
"""
# Check inside messages array (Foundry media dataset format)
for msg in record.get("messages", []):
if msg.get("role") != "user":
continue
content = msg.get("content", [])
if isinstance(content, list):
for part in content:
if isinstance(part, dict) and part.get("type") == "input_audio":
ref = part.get("input_audio")
if ref and ref.get("data"):
return ref
# Check top-level audio field (alternative format)
top_audio = record.get("audio")
if isinstance(top_audio, dict) and top_audio.get("type") == "input_audio":
ref = top_audio.get("input_audio")
if ref and ref.get("data"):
return ref
return None
def _extract_text_from_messages(record: dict) -> Optional[str]:
"""Extract user text from a Foundry messages array."""
for msg in record.get("messages", []):
if msg.get("role") != "user":
continue
content = msg.get("content", [])
if isinstance(content, str):
return content
if isinstance(content, list):
texts = [p.get("text", "") for p in content
if isinstance(p, dict) and p.get("type") == "text"]
combined = " ".join(t for t in texts if t)
if combined:
return combined
return None
def _extract_system_prompt_from_messages(record: dict) -> Optional[str]:
"""Extract system message content from a Foundry messages array."""
for msg in record.get("messages", []):
if msg.get("role") == "system":
content = msg.get("content", "")
return content if isinstance(content, str) else str(content)
return None
def _resolve_audio_path(wav_path: str, dataset_dir: str) -> Optional[str]:
"""Try several strategies to locate an audio file.
Validates that resolved path stays within the dataset directory
or its parent tree (up to 5 levels) to prevent path traversal.
"""
# Absolute path — validate it exists
if os.path.isabs(wav_path) and os.path.exists(wav_path):
return wav_path
# Relative to dataset dir (basename)
candidate = os.path.join(dataset_dir, os.path.basename(wav_path))
if os.path.exists(candidate):
return os.path.abspath(candidate)
# Full relative from dataset dir
candidate = os.path.join(dataset_dir, wav_path)
if os.path.exists(candidate):
resolved = os.path.abspath(candidate)
# Validate resolved path is under dataset_dir (prevent traversal via ../)
if os.path.commonpath([resolved, os.path.abspath(dataset_dir)]) == os.path.abspath(dataset_dir):
return resolved
logger.warning(f"Path traversal blocked: {wav_path} resolved outside dataset directory")
return None
# Walk up to 5 parent directories (path traversal check applied at each level)
repo_root = os.path.abspath(dataset_dir)
current = dataset_dir
for _ in range(5):
candidate = os.path.join(current, wav_path)
if os.path.exists(candidate):
resolved = os.path.abspath(candidate)
# Validate resolved path stays within the search root (prevent traversal via ../)
if os.path.commonpath([resolved, repo_root]) == repo_root:
return resolved
logger.warning(f"Path traversal blocked: {wav_path} resolved outside search root")
return None
parent = os.path.dirname(current)
if parent == current:
break
current = parent
return None
def _redact_url_params(text: str) -> str:
"""Redact query parameters from URLs in error messages to prevent SAS token leakage."""
import re
return re.sub(r'(https?://[^\s?]+)\?[^\s"\']+', r'\1?[REDACTED]', str(text))
def _resolve_audio_from_media(
audio_ref: Dict[str, str],
cache_dir: Optional[str] = None,
) -> Optional[str]:
"""Resolve an ``input_audio`` media reference to a local WAV file path.
Supports two data forms:
- **URL** (``https://...``) — downloaded via ``requests``; Azure blob
URLs are attempted with ``DefaultAzureCredential`` bearer token first.
- **Base64 data-URI** (``data:audio/wav;base64,...``) — prefix stripped
and decoded. This is the Foundry Portal-compatible format.
Args:
audio_ref: ``{"data": "<url_or_base64>", "format": "wav"}``
cache_dir: Directory for downloaded/decoded files. A temp dir is
created when *None*.
Returns:
Absolute path to the local WAV file, or *None* on failure.
"""
data = (audio_ref or {}).get("data", "")
fmt = (audio_ref or {}).get("format", "wav")
if not data:
logger.warning("Empty media data in input_audio reference")
return None
target_dir = cache_dir or tempfile.mkdtemp(prefix="voicelive_media_")
suffix = f".{fmt}" if fmt else ".wav"
# --- URL ---------------------------------------------------------------
if data.startswith("http://") or data.startswith("https://"):
try:
dest = os.path.join(target_dir, f"media_download_{secrets.token_hex(4)}{suffix}")
# Azure blob URLs — use BlobClient with DefaultAzureCredential
from urllib.parse import urlparse
hostname = urlparse(data).hostname or ""
if hostname.endswith(".blob.core.windows.net") or hostname.endswith(".blob.storage.azure.net"):
try:
from azure.storage.blob import BlobClient
blob_client = BlobClient.from_blob_url(data, credential=DefaultAzureCredential())
with open(dest, "wb") as fout:
download_stream = blob_client.download_blob()
fout.write(download_stream.readall())
file_size = os.path.getsize(dest)
logger.info(f"Downloaded blob audio ({file_size} bytes) → {dest}")
return os.path.abspath(dest)
except Exception as exc:
logger.debug(f"BlobClient auth failed ({exc}), trying anonymous HTTP")
# Non-Azure URLs or fallback — plain HTTP GET (streaming with size limit)
resp = requests.get(data, timeout=120, stream=True)
resp.raise_for_status()
max_size = 500 * 1024 * 1024 # 500MB limit
content_length = int(resp.headers.get('content-length', 0))
if content_length > max_size:
logger.error(f"Audio file too large: {content_length} bytes (max {max_size})")
return None
with open(dest, "wb") as fout:
downloaded = 0
for chunk in resp.iter_content(chunk_size=8192):
downloaded += len(chunk)
if downloaded > max_size:
logger.error(f"Audio download exceeded {max_size} byte limit")
return None
fout.write(chunk)
logger.info(f"Downloaded media audio ({downloaded} bytes) → {dest}")
return os.path.abspath(dest)
except Exception as exc:
logger.error(f"Failed to download media audio from URL: {_redact_url_params(str(exc))}")
return None
# --- Base64 data-URI ---------------------------------------------------
if data.startswith("data:"):
# Strip "data:audio/wav;base64," prefix
try:
_, encoded = data.split(",", 1)
except ValueError:
logger.error("Malformed base64 data-URI (no comma separator)")
return None
try:
raw_bytes = base64.b64decode(encoded, validate=True)
except Exception as exc:
logger.error(f"Base64 decode failed for data-URI: {exc}")
return None
dest = os.path.join(target_dir, f"media_b64_{secrets.token_hex(4)}{suffix}")
with open(dest, "wb") as fout:
fout.write(raw_bytes)
logger.info(f"Decoded base64 data-URI ({len(raw_bytes)} bytes) → {dest}")
return os.path.abspath(dest)
logger.warning(f"Unrecognised media data format (length={len(data)}). "
"Expected https:// URL or data: URI.")
return None
# ---------------------------------------------------------------------------
# Session configuration
# ---------------------------------------------------------------------------
async def configure_session(connection: Any, config: SessionConfig) -> None:
"""Send a session.update to the VoiceLive connection.
In agent mode, sends minimal config (the agent manages its own settings).
If voice/VAD/audio settings are explicitly overridden, they are included.
"""
# Voice
if config.voice_type == "preset":
sdk_voice = OpenAIVoice(name=config.voice)
else:
sdk_voice = AzureStandardVoice(name=config.voice, type=config.voice_type)
# Turn detection — select VAD implementation based on vad_type
vad_kwargs = {
"auto_truncate": config.enable_barge_in,
"interrupt_response": config.enable_barge_in,
}
if config.vad_threshold is not None:
vad_kwargs["threshold"] = config.vad_threshold
if config.silence_duration_ms is not None:
vad_kwargs["silence_duration_ms"] = config.silence_duration_ms
if config.vad_type == "server_vad":
sdk_turn_detection = ServerVad(**vad_kwargs)
else:
if config.supports_eou_detection() and config.use_eou_detection:
vad_kwargs["end_of_utterance_detection"] = EouDetection(model=config.eou_model)
sdk_turn_detection = AzureSemanticVadMultilingual(**vad_kwargs)
if config.is_agent_mode:
# Agent mode: minimal session config — agent manages instructions/tools
session_kwargs = {
"modalities": [Modality.TEXT, Modality.AUDIO],
"input_audio_format": InputAudioFormat.PCM16,
"output_audio_format": OutputAudioFormat.PCM16,
"input_audio_sampling_rate": config.sample_rate,
}
# Include overrides only if explicitly set (not defaults)
if config._voice_explicitly_set:
session_kwargs["voice"] = sdk_voice
logger.info(f"Agent mode: overriding voice with local value {config.voice}")
if config._vad_explicitly_set:
session_kwargs["turn_detection"] = sdk_turn_detection
logger.info(f"Agent mode: overriding turn_detection with local value {config.vad_type}")
# Always include audio processing (these are client-side settings)
session_kwargs["input_audio_noise_reduction"] = AudioNoiseReduction(type=config.noise_reduction)
session_kwargs["input_audio_echo_cancellation"] = AudioEchoCancellation(type=config.echo_cancellation)
# Transcription is useful for evaluation
session_kwargs["input_audio_transcription"] = AudioInputTranscriptionOptions(model=config.get_transcription_model())
sdk_session = RequestSession(**session_kwargs)
await connection.session.update(session=sdk_session)
logger.info(
f"Agent mode session configured (minimal): voice_override={config._voice_explicitly_set}, "
f"vad_override={config._vad_explicitly_set}, "
f"noise_reduction={config.noise_reduction}, "
f"transcription={config.get_transcription_model()}"
)
else:
# Model mode: full session configuration (existing behavior)
sdk_session = RequestSession(
modalities=[Modality.TEXT, Modality.AUDIO],
instructions=config.get_final_instructions(),
voice=sdk_voice,
turn_detection=sdk_turn_detection,
input_audio_transcription=AudioInputTranscriptionOptions(model=config.get_transcription_model()),
input_audio_noise_reduction=AudioNoiseReduction(type=config.noise_reduction),
input_audio_echo_cancellation=AudioEchoCancellation(type=config.echo_cancellation),
tools=config.tools if config.tools else None,
input_audio_format=InputAudioFormat.PCM16,
output_audio_format=OutputAudioFormat.PCM16,
input_audio_sampling_rate=config.sample_rate,
)
await connection.session.update(session=sdk_session)
logger.info(
f"Session configured: model={config.model}, voice={config.voice}, "
f"ptt={config.push_to_talk}, barge_in={config.enable_barge_in}, "
f"vad={config.vad_type}, noise_reduction={config.noise_reduction}, "
f"transcription={config.get_transcription_model()}"
)
# ---------------------------------------------------------------------------
# Core audio processing (PTT / VAD)
# ---------------------------------------------------------------------------
async def process_audio(
connection: Any,
audio_data: bytes,
config: SessionConfig,
push_to_talk: bool,
sample_rate: int = 24000,
timeout_seconds: float = 120.0,
) -> ConversationTurn:
"""
Send audio and collect the response.
PTT mode: send all audio → commit → response.create → collect events.
VAD mode: concurrent audio send + silence keepalive + event collection.
"""
turn = ConversationTurn()
chunk_samples = int(sample_rate * 0.02)
chunk_bytes = chunk_samples * 2 # PCM16
silence_chunk = base64.b64encode(b'\x00' * chunk_bytes).decode('utf-8')
# ------------------------------------------------------------------
# PTT: sequential send → commit → response.create, THEN collect
# ------------------------------------------------------------------
if push_to_talk:
logger.info("PTT mode: sending audio synchronously before event collection")
for i in range(0, len(audio_data), chunk_bytes):
chunk = audio_data[i:i + chunk_bytes]
encoded = base64.b64encode(chunk).decode('utf-8')
await connection.input_audio_buffer.append(audio=encoded)
await asyncio.sleep(0.02)
turn.audio_send_end_time = datetime.now()
await connection.input_audio_buffer.commit()
await connection.response.create()
logger.debug("Audio committed and response.create sent (PTT)")
# ------------------------------------------------------------------
# VAD: concurrent audio send + event collection
# ------------------------------------------------------------------
audio_send_complete = asyncio.Event()
audio_task: Optional[asyncio.Task] = None
silence_task: Optional[asyncio.Task] = None
if not push_to_talk:
async def send_audio() -> None:
try:
for i in range(0, len(audio_data), chunk_bytes):
chunk = audio_data[i:i + chunk_bytes]
encoded = base64.b64encode(chunk).decode('utf-8')
await connection.input_audio_buffer.append(audio=encoded)
await asyncio.sleep(0.02)
turn.audio_send_end_time = datetime.now()
logger.debug("Audio sent, starting silence keepalive for VAD")
except Exception as e:
logger.error(f"Audio send error: {e}")
finally:
audio_send_complete.set()
async def send_silence() -> None:
try:
await audio_send_complete.wait()
while True:
await connection.input_audio_buffer.append(audio=silence_chunk)
await asyncio.sleep(0.1)
except asyncio.CancelledError:
pass
except Exception as e:
logger.debug(f"Silence keepalive ended: {e}")
audio_task = asyncio.create_task(send_audio())
silence_task = asyncio.create_task(send_silence())
# ------------------------------------------------------------------
# Event collection
# ------------------------------------------------------------------
text_buffer = ""
audio_transcript_buffer = ""
pending_tool_call = None
pending_tool_item_id: Optional[str] = None
try:
async with asyncio.timeout(timeout_seconds):
logger.info(f"Collecting events (timeout={timeout_seconds}s, ptt={push_to_talk})")
async for event in connection:
etype = event.type
if etype == ServerEventType.SESSION_CREATED:
logger.debug(f"Session: {getattr(event.session, 'id', None)}")
elif etype == ServerEventType.SESSION_UPDATED:
logger.debug("Session updated")
# Capture agent session metadata for transparency
if config.is_agent_mode and hasattr(event, 'session'):
try:
session_data = event.session
agent_meta = {}
if hasattr(session_data, 'agent') and session_data.agent:
a = session_data.agent
agent_meta["agent_name"] = getattr(a, 'name', None)
agent_meta["agent_description"] = getattr(a, 'description', None)
agent_meta["agent_id"] = getattr(a, 'agent_id', None)
agent_meta["thread_id"] = getattr(a, 'thread_id', None)
if hasattr(session_data, 'voice') and session_data.voice:
v = session_data.voice
if isinstance(v, dict):
agent_meta["effective_voice"] = v
else:
agent_meta["effective_voice"] = {
"name": getattr(v, 'name', None),
"type": getattr(v, 'type', None),
"temperature": getattr(v, 'temperature', None),
}
logger.info(f"Agent session metadata: {json.dumps(agent_meta, default=str)}")
except Exception as e:
logger.warning(f"Failed to capture agent session metadata: {e}")
elif etype == ServerEventType.INPUT_AUDIO_BUFFER_SPEECH_STARTED: