-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgroupcall.py
More file actions
1328 lines (1118 loc) · 58.6 KB
/
Copy pathgroupcall.py
File metadata and controls
1328 lines (1118 loc) · 58.6 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
import asyncio
import os
import json
import numpy as np
from typing import Optional, List, Dict, Any, Union
from autogen.agentchat import GroupChat, Agent, UserProxyAgent
from fastrtc import get_tts_model, get_stt_model, get_twilio_turn_credentials, KokoroTTSOptions
from aiortc.mediastreams import AudioStreamTrack as FastRTCAudioStreamTrack
from fastrtc.reply_on_pause import ReplyOnPause, AlgoOptions, AppState
from fastrtc.stream import Stream as FastRTCStream
import time
import random
from threading import Lock
class AudioGroupChat(GroupChat):
"""Real-time audio group chat implementation enabling voice and text communication between humans and AI agents."""
def __init__(self, agents=None, messages=None, max_round=10, speaker_selection_method="round_robin", allow_repeat_speaker=False):
"""Initialize AudioGroupChat with audio processing capabilities."""
super().__init__(
agents=agents or [],
messages=messages or [],
max_round=max_round,
speaker_selection_method=speaker_selection_method,
allow_repeat_speaker=allow_repeat_speaker,
)
# Enable agent voice by default
self.agent_voice_enabled = True
# Initialize audio processing components
print("Initializing TTS models...")
# Map of agent names to voice models and options
self.tts_models = {}
self.voice_options = {} # Store voice options separately
# Create distinct voices using Kokoro's options
self.available_voices = [
("energetic", KokoroTTSOptions(speed=1.5, lang="en-us")), # Fast, energetic voice
("calm", KokoroTTSOptions(speed=0.75, lang="en-us")), # Slower, calmer voice
("british", KokoroTTSOptions(speed=1.0, lang="en-gb")), # British accent
("authoritative", KokoroTTSOptions(speed=0.9, lang="en-us")), # Slightly slower, authoritative
("default", KokoroTTSOptions(speed=1.0, lang="en-us")), # Normal voice
]
self.next_voice_index = 0
# Default model for unassigned agents
self.default_tts_model = get_tts_model("kokoro")
print("Default TTS model initialized")
# Assign voices to initial agents
if agents:
for agent in agents:
if isinstance(agent, UserProxyAgent):
print(f"Skipping voice assignment for human user {agent.name}")
continue
voice_name, voice_options = self.available_voices[self.next_voice_index % len(self.available_voices)]
print(f"Assigning voice '{voice_name}' to agent {agent.name} (speed={voice_options.speed}, lang={voice_options.lang})")
self.tts_models[agent.name] = get_tts_model("kokoro")
self.voice_options[agent.name] = voice_options # Store voice options
self.next_voice_index += 1
self.tts_sample_rate = 24000 # Standard sample rate for TTS output
print("Initializing STT model...")
self.stt_model = get_stt_model()
print("STT model initialized")
# Configure WebRTC settings
self.rtc_config = get_twilio_turn_credentials() if os.environ.get("TWILIO_ACCOUNT_SID") else None
# Create FastRTC stream for audio handling with ReplyOnPause
algo_options = AlgoOptions(
audio_chunk_duration=1.0, # Longer chunks for better transcription
started_talking_threshold=0.2, # More sensitive to speech start
speech_threshold=0.1, # More sensitive to ongoing speech
)
# Create a handler that maintains state per participant
self.participant_states = {}
# Create main handler for audio processing
async def audio_callback(frame, additional_inputs=None):
try:
# Get user ID from additional inputs
user_id = None
if additional_inputs and len(additional_inputs) > 0:
if isinstance(additional_inputs[0], str):
user_id = additional_inputs[0]
elif hasattr(additional_inputs[0], 'value'):
user_id = additional_inputs[0].value
if not user_id:
print("No user ID provided in audio callback")
return None
print(f"Processing audio from user: {user_id}")
# Handle different audio input formats
if isinstance(frame, tuple) and len(frame) == 2:
sample_rate, audio_array = frame
elif isinstance(frame, dict):
# Handle Gradio's audio format
sample_rate = frame.get('sr', 48000) # Default to 48kHz
audio_array = frame.get('value', None)
if audio_array is None:
print("No audio array in data")
return None
else:
print(f"Unexpected audio format: {type(frame)}")
return None
print(f"Processing audio: sr={sample_rate}, shape={getattr(audio_array, 'shape', None)}")
# Ensure audio data is in correct format
if isinstance(audio_array, bytes):
audio_array = np.frombuffer(audio_array, dtype=np.float32)
elif isinstance(audio_array, list):
audio_array = np.array(audio_array, dtype=np.float32)
# Convert to mono if stereo
if len(audio_array.shape) > 1:
audio_array = np.mean(audio_array, axis=1)
# Ensure 1D array
audio_array = audio_array.reshape(-1)
# Normalize audio to [-1, 1] range
if audio_array.dtype != np.float32:
audio_array = audio_array.astype(np.float32)
if np.max(np.abs(audio_array)) > 1.0:
audio_array = audio_array / 32768.0
print("Before STT model call") # ADDED LOGGING
print(f"Audio data shape before STT: {audio_array.shape}, dtype: {audio_array.dtype}") # ADDED LOGGING
text = self.stt_model.stt((sample_rate, audio_array))
print("After STT model call") # ADDED LOGGING
if not text:
print("No speech detected")
return None
print(f"Transcribed text: {text}")
# Create chat message
message = {
"role": "user",
"content": text,
"name": user_id
}
# Add to chat history
await self.text_queue.put({
"type": "chat",
"text": text,
"sender": user_id,
"channel": "voice"
})
# Add message to messages list for UI updates
self.messages.append(message)
# Process the message through the chat handler
await self._handle_chat_message(user_id, message)
# Return messages for Gradio Chatbot
return self.messages
except Exception as e:
print(f"Error in audio callback: {str(e)}")
import traceback
traceback.print_exc()
return None
# Create main handler using FastRTC's ReplyOnPause
handler = ReplyOnPause(
fn=audio_callback,
algo_options=algo_options,
can_interrupt=True,
expected_layout="mono",
output_sample_rate=24000,
output_frame_size=480, # Standard frame size for 24kHz
input_sample_rate=48000,
)
# Initialize handler with required attributes
handler._loop = asyncio.get_event_loop()
handler.queue = asyncio.Queue()
handler.args_set = asyncio.Event() # Required by StreamHandlerBase
handler.channel_set = asyncio.Event() # Required by StreamHandlerBase
handler._channel = None # Will be set by AudioCallback
handler._phone_mode = False # Required by StreamHandlerBase
self._lock = Lock()
# Create a clear_queue function that clears the handler's queue
def clear_queue():
while not handler.queue.empty():
handler.queue.get_nowait()
handler._clear_queue = clear_queue
# Create FastRTC stream for audio handling
self.stream = FastRTCStream(
modality="audio",
mode="send-receive",
handler=handler, # This sets event_handler internally
rtc_configuration=self.rtc_config,
concurrency_limit=10, # Allow up to 10 concurrent connections
time_limit=None, # No time limit on sessions
additional_inputs=[], # Initialize empty, will be set by UI
additional_outputs=[], # Initialize empty, will be set by UI
additional_outputs_handler=lambda prev, curr: curr, # Simple handler
ui_args={
"title": "Huddle Audio Group Chat",
"subtitle": "Click the microphone button to start speaking",
"show_audio_input": True,
"show_audio_output": True,
"show_text": True
}
)
# Verify handler is properly set
if not self.stream.event_handler:
raise RuntimeError("Failed to initialize stream event_handler")
# Initialize participant tracking
self.human_participants = {}
self.active_calls = {}
# Channel configuration
self.voice_enabled = True # Enable voice by default
self.text_enabled = True # Enable text by default
self.agent_voice_enabled = True # Enable agent voice by default
# Track last message count to detect new messages
self._last_message_count = 0
# Required for autogen compatibility
self.client_cache = []
self.previous_cache = []
# Message queues for each channel: Initialize queues
self.voice_queue = asyncio.Queue()
self.text_queue = asyncio.Queue()
async def initialize(self):
"""Initialize async tasks and processors for real-time operation."""
try:
print("Initializing audio group chat...")
# Start background tasks
self._process_voice_queue_task = asyncio.create_task(self._process_voice_queue())
self._process_text_queue_task = asyncio.create_task(self._process_text_queue())
self._monitor_agent_messages_task = asyncio.create_task(self._monitor_agent_messages())
# Add error handlers and names for better tracking
for task, name in [
(self._process_voice_queue_task, "voice_queue"),
(self._process_text_queue_task, "text_queue"),
(self._monitor_agent_messages_task, "agent_monitor")
]:
task.set_name(name)
task.add_done_callback(self._task_error_handler)
# Wait for tasks to start
await asyncio.sleep(0.1)
# Verify tasks are running
for task in [self._process_voice_queue_task, self._process_text_queue_task, self._monitor_agent_messages_task]:
if task.done():
exc = task.exception()
if exc:
print(f"Task {task.get_name()} failed to start: {exc}")
raise exc
else:
print(f"Task {task.get_name()} started successfully")
print("Audio group chat initialized successfully")
except Exception as e:
print(f"Error initializing audio group chat: {e}")
import traceback
traceback.print_exc()
raise
def _task_error_handler(self, task):
"""Handle errors in real-time processing tasks."""
try:
# Skip if task was cancelled normally
if task.cancelled():
return
# Get the exception if any
exc = task.exception()
if exc:
task_name = task.get_name()
print(f"Background task '{task_name}' error: {exc}")
import traceback
traceback.print_exc()
# Restart the task if it's one of our monitored tasks
if task in [self._process_voice_queue_task, self._process_text_queue_task, self._monitor_agent_messages_task]:
print(f"Restarting failed task '{task_name}'...")
# Create new task with same name
new_task = asyncio.create_task(task.get_coro())
new_task.set_name(task_name)
new_task.add_done_callback(self._task_error_handler)
# Update task reference
if task == self._process_voice_queue_task:
self._process_voice_queue_task = new_task
elif task == self._process_text_queue_task:
self._process_text_queue_task = new_task
elif task == self._monitor_agent_messages_task:
self._monitor_agent_messages_task = new_task
print(f"Task '{task_name}' restarted")
except asyncio.CancelledError:
pass
except Exception as e:
print(f"Error in task error handler: {e}")
import traceback
traceback.print_exc()
def add_agent(self, agent: Agent):
"""Add an agent to the chat and assign it a unique voice."""
# Skip voice assignment for human users
if isinstance(agent, UserProxyAgent):
print(f"Skipping voice assignment for human user {agent.name}")
# Add agent to group chat
if not hasattr(self, 'agents'):
self.agents = []
self.agents.append(agent)
return
# Add agent to group chat
if not hasattr(self, 'agents'):
self.agents = []
self.agents.append(agent)
# Assign a unique voice to the agent if not already assigned
if agent.name not in self.tts_models:
voice_name, voice_options = self.available_voices[self.next_voice_index % len(self.available_voices)]
print(f"Assigning voice '{voice_name}' to agent {agent.name} (speed={voice_options.speed}, lang={voice_options.lang})")
self.tts_models[agent.name] = get_tts_model("kokoro")
self.voice_options[agent.name] = voice_options # Store voice options
self.next_voice_index += 1
return agent
def add_human_participant(self, user_id: str) -> str:
"""Add a human participant to the group chat."""
print(f"\nAdding human participant: {user_id}")
try:
# Create session ID
session_id = str(random.getrandbits(64))
# Create user proxy agent
user_agent = UserProxyAgent(
name=user_id,
human_input_mode="NEVER",
code_execution_config={"use_docker": False}
)
# Add participant info
self.human_participants[user_id] = {
"session_id": session_id,
"agent": user_agent,
"active": False,
"stream": None
}
# Add agent to chat
if user_agent not in self.agents:
self.agents.append(user_agent)
print(f"Participant {user_id} added successfully")
print("Current participants:", list(self.human_participants.keys()))
return session_id
except Exception as e:
print(f"Error adding participant {user_id}: {e}")
import traceback
traceback.print_exc()
raise
async def start_audio_session(self, user_id: str):
"""Start an audio session for a participant and initialize the group chat."""
try:
# Verify participant exists
participant = self.human_participants.get(user_id)
if not participant:
print(f"Error: Participant {user_id} not found")
print("Available participants:", list(self.human_participants.keys()))
return
print(f"\nStarting audio session for {user_id}...")
# Mark participant as active
participant["active"] = True
# Use the main AudioGroupChat stream for this participant
if "stream" not in participant:
participant["stream"] = self.stream
print(f"Using main stream for participant {user_id}")
print(f"Audio session started for {user_id}")
except Exception as e:
print(f"Error in start_audio_session: {e}")
import traceback
traceback.print_exc()
raise
async def _handle_audio_input(self, audio_data: tuple[int, np.ndarray], user_id: str = None) -> dict:
"""Process incoming audio from a user in real-time."""
try:
print("Received audio input:", type(audio_data))
if audio_data is None:
print("No audio data received")
return None
# Handle different audio input formats
if isinstance(audio_data, tuple) and len(audio_data) == 2:
sample_rate, audio_array = audio_data
elif isinstance(audio_data, dict):
# Handle Gradio's audio format
sample_rate = audio_data.get('sr', 48000) # Default to 48kHz
audio_array = audio_data.get('value', None)
if audio_array is None:
print("No audio array in data")
return None
else:
print(f"Unexpected audio format: {type(audio_data)}")
return None
print(f"Processing audio: sr={sample_rate}, shape={getattr(audio_array, 'shape', None)}")
# Ensure audio data is in correct format
if isinstance(audio_array, bytes):
audio_array = np.frombuffer(audio_array, dtype=np.float32)
elif isinstance(audio_array, list):
audio_array = np.array(audio_array, dtype=np.float32)
# Convert to mono if stereo
if len(audio_array.shape) > 1:
audio_array = np.mean(audio_array, axis=1)
# Ensure 1D array (sequence_length,)
audio_array = audio_array.reshape(-1)
# Normalize audio to [-1, 1] range
if audio_array.dtype != np.float32:
audio_array = audio_array.astype(np.float32)
if np.max(np.abs(audio_array)) > 1.0:
audio_array = audio_array / 32768.0
print("Audio preprocessing complete")
# Get participant's state
participant = self.human_participants.get(user_id)
if not participant:
print(f"No participant found for user_id: {user_id}")
return None
# Use STT model to convert accumulated speech to text
text = self.stt_model.stt((sample_rate, audio_array))
if text and text.strip():
# Create message for processing
message = {
"type": "chat",
"text": text,
"sender": user_id,
"channel": "voice"
}
print(f"Transcribed text: {text}")
# Process the message through the group chat manager
await self._handle_chat_message(user_id, message)
return {"text": text}
else:
print("No text transcribed from audio")
return None
except Exception as e:
print(f"Error in handle_audio_input: {e}")
import traceback
traceback.print_exc()
return None
async def handle_audio_output(self):
"""Process and return the next audio output for real-time playback."""
try:
# Check the voice queue
try:
# Get next message from voice queue without blocking
message = self.voice_queue.get_nowait()
print(f"Processing voice queue message: {message}")
if isinstance(message, dict):
if message.get("type") == "chat":
text = message.get("text")
sender = message.get("sender")
if text and sender and sender not in self.human_participants:
print(f"Converting to speech from voice queue: {text} from {sender}")
try:
# Extract text from ChatResult if needed
if hasattr(text, 'content'):
text = text.content
elif isinstance(text, dict):
text = text.get("content", "")
elif isinstance(text, str):
text = text
# Skip empty messages
if not text or not text.strip():
print("Empty text content, skipping")
return None
# Convert to speech with timeout
tts_result = self.tts_models.get(sender, self.default_tts_model).tts(text, options=self.voice_options.get(sender, None))
if asyncio.iscoroutine(tts_result):
sample_rate, audio_data = await asyncio.wait_for(tts_result, timeout=5.0)
else:
sample_rate, audio_data = tts_result
if audio_data is not None:
# Ensure correct format
if audio_data.dtype != np.float32:
audio_data = audio_data.astype(np.float32)
# Normalize audio to [-1, 1] range
max_val = np.max(np.abs(audio_data))
if max_val > 0: # Avoid division by zero
audio_data = audio_data / max_val
print(f"Broadcasting TTS audio for {sender}: {text}")
print(f"Audio stats - min: {np.min(audio_data):.3f}, max: {np.max(audio_data):.3f}, mean: {np.mean(audio_data):.3f}")
# Broadcast to all participants
await self._broadcast_audio_to_participants((sample_rate, audio_data))
# Return for Gradio UI
return audio_data
else:
print(f"TTS failed for message from {sender}: {text}")
except asyncio.TimeoutError:
print(f"TTS timed out for message: {text}")
except Exception as e:
print(f"Error converting message to speech: {e}")
import traceback
traceback.print_exc()
elif message.get("type") == "audio":
# Direct audio data
audio_data = message.get("audio_data")
if audio_data is not None:
return audio_data
except asyncio.QueueEmpty:
pass
return None
except Exception as e:
print(f"Error in audio output handler: {e}")
import traceback
traceback.print_exc()
return None
async def text_to_speech(self, text: str | dict, user_id: str = None) -> tuple[int, np.ndarray] | None:
"""Convert text to speech with real-time processing and delivery."""
try:
# Check if TTS is enabled and model is initialized
if not hasattr(self, 'tts_models') or not self.tts_models:
print("TTS models not initialized")
return None
# Extract text from chat result if needed
if isinstance(text, dict):
text = text.get("content", "")
elif not isinstance(text, str):
text = str(text)
# Skip empty messages
if not text or text.strip() == "":
return None
# Extract sender from chat result if needed
if isinstance(text, dict):
sender = text.get("sender", user_id)
else:
sender = user_id or ""
# Skip TTS for human participants
if sender in self.human_participants:
print(f"Skipping TTS for human participant {sender}")
return None
# Convert to speech using tts() method with timeout
try:
# Get the appropriate TTS model and voice options for the sender
tts_model = self.tts_models.get(sender, self.default_tts_model)
voice_options = self.voice_options.get(sender, None)
print(f"Using voice model for {sender} with options: {voice_options}")
# Call tts() with the voice options
tts_result = tts_model.tts(text, options=voice_options)
if not hasattr(tts_result, '__await__'):
# If not awaitable, assume it's already the result
sample_rate, audio_data = tts_result
else:
# If awaitable, wait for result with timeout
sample_rate, audio_data = await asyncio.wait_for(
tts_result,
timeout=5.0 # 5 second timeout
)
print(f"TTS generated audio: sr={sample_rate}, shape={audio_data.shape}")
except asyncio.TimeoutError:
print("TTS timed out")
return None
if audio_data is None:
print("TTS failed to generate audio")
return None
# Ensure correct format
if audio_data.dtype != np.float32:
audio_data = audio_data.astype(np.float32)
# AUTOMATIC GAIN CONTROL
peak = np.max(np.abs(audio_data))
if peak > 0:
target_peak = 0.9 # Scale to 90% of max volume
gain = target_peak / peak
audio_data *= gain
else:
print("Silent audio detected")
return None
# Clip to [-1.0, 1.0] and convert to int16
audio_data = np.clip(audio_data, -1.0, 1.0)
audio_data = (audio_data * 32767).astype(np.int16) # Convert to 16-bit integers
# Add to voice queue for broadcasting
await self.voice_queue.put({
"type": "audio",
"sample_rate": sample_rate,
"audio_data": audio_data,
"sender": sender
})
print(f"Added TTS audio to voice queue: {text}")
return sample_rate, audio_data
except Exception as e:
print(f"Error in text_to_speech: {e}")
import traceback
traceback.print_exc()
return None
async def _send_audio_to_participant(self, user_id: str, audio_frame: tuple[int, np.ndarray], max_retries: int = 3) -> bool:
"""Send audio data to a specific participant."""
participant = self.human_participants.get(user_id)
if not participant or not participant.get("active"):
print(f"Participant {user_id} not found or not active")
return False
stream = participant.get("stream")
if not stream:
print(f"No stream found for participant {user_id}")
return False
sample_rate, audio_data = audio_frame
# Ensure audio data is in correct format
if audio_data.dtype != np.float32:
audio_data = audio_data.astype(np.float32)
if np.max(np.abs(audio_data)) > 1.0:
audio_data = audio_data / 32768.0
for attempt in range(max_retries):
try:
print(f"Sending audio to {user_id} (attempt {attempt + 1})")
# Send audio through FastRTC stream
if stream and stream.event_handler:
print(f"Sending audio to {user_id}")
# Create coroutine to send audio through queue
async def send_audio():
await stream.event_handler.queue.put((sample_rate, audio_data))
await send_audio()
print(f"Successfully sent audio to {user_id}")
return True
except Exception as e:
print(f"Error sending audio to {user_id} (attempt {attempt + 1}): {e}")
import traceback
traceback.print_exc()
await asyncio.sleep(0.5) # Brief delay before retry
return False
async def broadcast_audio(self, audio_frame: tuple[int, np.ndarray], sender_id: str = None):
"""Broadcast audio to all participants except the sender."""
print("\n=== Broadcasting Audio ===")
sample_rate, audio_data = audio_frame
print(f"Audio frame: sr={sample_rate}Hz, shape={audio_data.shape}, dtype={audio_data.dtype}")
# Get list of active participants excluding sender
participants = [
user_id for user_id, participant in self.human_participants.items()
if user_id != sender_id and participant.get("active") and participant.get("stream") is not None
]
if not participants:
print("No active participants with streams to broadcast to")
return False
print(f"Broadcasting to participants: {participants}")
# Ensure audio data is in correct format
if audio_data.dtype == np.int16:
pass # Already in correct format (no scaling needed)
else:
if audio_data.dtype != np.float32:
audio_data = audio_data.astype(np.float32)
if np.max(np.abs(audio_data)) > 1.0:
audio_data = audio_data / 32768.0 # Only for non-integer data
# Add to voice queue for local playback (REMOVE THIS LINE for debugging if needed, it might cause repeated processing)
# await self.voice_queue.put({
# "type": "audio",
# "sample_rate": sample_rate,
# "audio_data": audio_data,
# "sender": sender_id
# })
# Send to all participants in parallel
tasks = []
for user_id in participants:
try:
participant = self.human_participants[user_id]
stream = participant.get("stream")
if stream and stream.event_handler:
print(f"Preparing to send audio to {user_id}")
tasks.append(self._send_audio_to_participant(user_id, (sample_rate, audio_data)))
else:
print(f"Stream for {user_id} is closed or invalid")
except Exception as e:
print(f"Error preparing to send to {user_id}: {e}")
import traceback
traceback.print_exc()
if not tasks:
print("No tasks created for broadcasting")
return False
# Wait for all sends to complete
print(f"Sending audio to {len(tasks)} participants...")
results = await asyncio.gather(*tasks, return_exceptions=True)
# Check for any failures
success = False
for user_id, result in zip(participants, results):
if isinstance(result, Exception):
print(f"Failed to send to {user_id}: {result}")
elif not result:
print(f"Failed to send to {user_id}")
else:
success = True
print(f"Successfully sent audio to {user_id}")
if success:
print("Successfully broadcasted audio to at least one participant")
else:
print("Failed to broadcast audio to any participants")
return success
async def _handle_chat_message(self, user_id: str, msg: Dict[str, Any]) -> None:
"""Handle incoming chat messages."""
try:
if msg.get("type") == "chat" and msg.get("text"):
# Create task to handle message asynchronously
asyncio.create_task(self._process_chat_message(user_id, msg))
except Exception as e:
print(f"Error handling chat message: {e}")
import traceback
traceback.print_exc()
async def _process_chat_message(self, user_id: str, message: Dict[str, Any]) -> None:
"""Process chat messages and handle responses in real-time."""
try:
print("\n=== Processing Chat Message ===")
print(f"From User: {user_id}")
print(f"Message: {message}")
# Get message content
text = None
if isinstance(message, dict):
text = message.get("content", message.get("text", ""))
elif hasattr(message, 'content'): # Handle ChatResult objects
text = message.content
if not text or not text.strip():
print("Empty message, skipping")
return
# Create chat message
chat_message = {
"role": "user" if user_id in self.human_participants else "assistant",
"content": text,
"name": user_id
}
# Add to voice queue if it's an agent message and voice is enabled
if user_id not in self.human_participants and self.agent_voice_enabled:
await self.voice_queue.put({
"type": "chat",
"text": text,
"sender": user_id,
"channel": "both"
})
print(f"Added agent message to voice queue: {text[:100]}..." if len(text) > 100 else f"Added agent message to voice queue: {text}")
chat_message["_voice_queued"] = True # Use dict entry instead of attribute
# Add message to messages list for UI updates
#print(f"Adding message to chat history: {chat_message}")
#self.messages.append(chat_message)
# Add message to both queues to ensure it's displayed and spoken
message_for_queues = {
"type": "chat",
"text": text,
"sender": user_id,
"channel": "both"
}
# Always add to text queue for display
await self.text_queue.put(message_for_queues)
print(f"Added message to text queue: {text[:100]}..." if len(text) > 100 else f"Added message to text queue: {text}")
# Get the first available agent as recipient
recipient = next((agent for agent in self.agents if agent.name != user_id), None)
if recipient:
# Get sender agent object
sender = self.agent(user_id)
if sender:
# Initiate chat with the message
response = await self.manager.a_initiate_chat(
message=text,
sender=sender,
recipient=recipient
)
# Process response if any
if response:
# Extract latest message from ChatResult
if hasattr(response, 'chat_history') and response.chat_history:
# Get the last message from chat_history
latest_msg = response.chat_history[-1]
response_text = latest_msg.get('content', '') if isinstance(latest_msg, dict) else str(latest_msg)
elif hasattr(response, 'summary'):
response_text = response.summary
elif hasattr(response, 'content'):
response_text = response.content
elif isinstance(response, dict):
response_text = response.get('content', '')
else:
response_text = str(response)
response_msg = {
"role": "assistant",
"content": response_text,
"name": recipient.name
}
self.messages.append(response_msg)
# Create base message
base_message = {
"type": "chat",
"text": response_text,
"sender": recipient.name
}
# Add to text queue
text_message = base_message.copy()
text_message["channel"] = "text"
await self.text_queue.put(text_message)
print(f"Added agent response to text queue: {response_text[:100]}..." if len(response_text) > 100 else f"Added agent response to text queue: {response_text}")
# Add to voice queue if agent voice is enabled
if self.agent_voice_enabled:
voice_message = base_message.copy()
voice_message["channel"] = "voice"
await self.voice_queue.put(voice_message)
print(f"Added agent response to voice queue: {response_text[:100]}..." if len(response_text) > 100 else f"Added agent response to voice queue: {voice_text}") # Corrected log var name
# Mark the original message and response as queued
message["_voice_queued"] = True
response_msg["_voice_queued"] = True
except Exception as e:
print(f"Error processing chat message: {e}")
import traceback
traceback.print_exc()
async def _monitor_agent_messages(self):
"""Monitor messages between agents and add them to the voice queue."""
processed_messages = set() # Track processed messages by content hash
print("\n=== Starting Agent Message Monitor ===\n")
while True:
await asyncio.sleep(0.1) # Prevent tight loop
try:
with self._lock:
current_count = len(self.messages)
message_count_changed = current_count > self._last_message_count
if message_count_changed:
with self._lock: # Atomic update of last count
self._last_message_count = current_count
if message_count_changed: # CHECK FLAG OUTSIDE LOCK
print(f"\n=== Monitoring Agent Messages ===")
print(f"Current message count: {len(self.messages)}, Last processed: {self._last_message_count}")
# Get only the latest message
last_message = self.messages[-1]
print(f"Processing latest message: {last_message}")
# Extract text and sender from message
text = None
sender = None
if isinstance(last_message, tuple):
text = last_message[1] # Agent's response is in second position
sender = last_message[0].name if hasattr(last_message[0], 'name') else str(last_message[0])
elif isinstance(last_message, dict): # ASSUMING DICTIONARY - MIGHT BE WRONG FOR AGENT-AGENT MESSAGES
text = last_message.get('content', '')
sender = last_message.get('name', '') # **THIS IS POTENTIALLY WRONG FOR AGENT-AGENT MESSAGES**
else: # ADDED ELSE BLOCK TO HANDLE UNEXPECTED TYPES
print(f"Unexpected message type in monitor: {type(last_message)}") # ADDED LOGGING
continue # SKIP PROCESSING IF UNEXPECTED TYPE
if not sender: # ADDED CHECK FOR EMPTY SENDER
print("Warning: Sender is empty, skipping message") # ADDED LOGGING
continue # SKIP PROCESSING IF NO SENDER
message_hash = hash(f"{sender}:{text}")
print(f"Message hash: {message_hash}")
# Check processing conditions
is_agent = sender not in self.human_participants
voice_enabled = self.agent_voice_enabled
not_processed = message_hash not in processed_messages
not_queued = not (isinstance(last_message, dict) and last_message.get("_voice_queued", False))
print(f"Message Analysis:")
print(f"- Sender: {sender}")
print(f"- Is agent: {is_agent} - Result: {is_agent}") # ADDED LOGGING
print(f"- Voice enabled: {voice_enabled} - Result: {voice_enabled}") # ADDED LOGGING
print(f"- Not processed: {not_processed} - Result: {not_processed}") # ADDED LOGGING
print(f"- Not queued: {not_queued} - Result: {not_queued}") # ADDED LOGGING
print(f"- Text preview: {text[:100]}..." if len(text) > 100 else f"- Text: {text}")
# Process agent messages that haven't been processed
if is_agent and voice_enabled and not_processed and not_queued:
print(f"\n✓ Processing new agent message from {sender}")
# Create message for voice queue
message_for_queues = {
"type": "chat",
"text": text,
"sender": sender,
"channel": "voice"
}
# Add to voice queue
print(f"Adding to voice queue: {text[:100]}..." if len(text) > 100 else f"Adding to voice queue: {text}")
await self.voice_queue.put(message_for_queues)
# Mark original message as queued and track processed message
if isinstance(last_message, dict):
last_message["_voice_queued"] = True
print("Marked message as queued")
processed_messages.add(message_hash)
print(f"Added to processed messages (total: {len(processed_messages)})")
# Add small delay for conversation flow
print("Adding delay for conversation flow...")
await asyncio.sleep(0.2)
else:
print(f"✗ Message skipped - Conditions not met for sender: {sender}")