-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconnection.py
More file actions
2423 lines (2104 loc) · 110 KB
/
Copy pathconnection.py
File metadata and controls
2423 lines (2104 loc) · 110 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 os
import sys
import copy
import json
import uuid
import time
import queue
import asyncio
import threading
import traceback
import subprocess
import websockets
from core.utils.exit_handler import is_exit_command, handle_exit
import re
from datetime import datetime
from core.utils.util import (
extract_json_from_string,
check_vad_update,
check_asr_update,
filter_sensitive_info,
)
from typing import Dict, Any, Optional
from collections import deque
from core.utils.modules_initialize import (
initialize_modules,
initialize_tts,
initialize_asr,
)
from core.handle.reportHandle import report
from core.providers.tts.default import DefaultTTS
from concurrent.futures import ThreadPoolExecutor
from core.utils.dialogue import Message, Dialogue
from core.providers.asr.dto.dto import InterfaceType
from core.handle.textHandle import handleTextMessage
from core.providers.tools.unified_tool_handler import UnifiedToolHandler
from plugins_func.loadplugins import auto_import_modules
from plugins_func.register import Action
from core.auth import AuthenticationError
from config.config_loader import get_private_config_from_api
from core.providers.tts.dto.dto import ContentType, TTSMessageDTO, SentenceType
from config.logger import setup_logging, build_module_string, create_connection_logger
from config.manage_api_client import DeviceNotFoundException, DeviceBindException
from core.utils.prompt_manager import PromptManager
from core.utils.voiceprint_provider import VoiceprintProvider
from core.utils import textUtils
from core.utils.news_rag import news_rag
from core.utils.history_rag import history_rag
from core.providers.tools.device_mcp import send_mcp_message
from plugins_func.functions.get_weather import get_weather
TAG = __name__
auto_import_modules("plugins_func.functions")
class TTSException(RuntimeError):
pass
class ConnectionHandler:
def __init__(
self,
config: Dict[str, Any],
_vad,
_asr,
_tts,
_llm,
_memory,
_intent,
server=None,
):
self.common_config = config
self.config = copy.deepcopy(config)
self.session_id = str(uuid.uuid4())
self.logger = setup_logging()
self.server = server # Save server instance reference
self.need_bind = False # Whether device binding is needed
self.bind_completed_event = asyncio.Event()
self.bind_code = None # Verification code for device binding
self.last_bind_prompt_time = 0 # Timestamp of last binding prompt (seconds)
self.bind_prompt_interval = 60 # Binding prompt interval (seconds)
self.read_config_from_api = self.config.get("read_config_from_api", False)
self.websocket = None
self.headers = None
self.device_id = None
self.client_ip = None
self.prompt = None
self.pipeline_prompts = {}
self.welcome_msg = None
self.max_output_size = 0
self.chat_history_conf = 0
self.audio_format = "opus"
# Client status related
self.client_abort = False
self.client_is_speaking = False
self.mcp_battery = None
self.mcp_charging = None
self.mcp_volume = None
self.mcp_brightness = None
self.client_listen_mode = "auto"
# Thread task related
self.loop = None # Get running event loop in handle_connection
self.stop_event = threading.Event()
self.executor = ThreadPoolExecutor(max_workers=5)
# Add report thread pool
self.report_queue = queue.Queue()
self.report_thread = None
# In the future, this can be modified to adjust asr report and tts report, currently both are enabled by default
self.report_asr_enable = self.read_config_from_api
self.report_tts_enable = self.read_config_from_api
# Dependent components
self.vad = None
self.asr = None
self.tts = None
self._asr = _asr
self._tts = _tts
self._vad = _vad
self.llm = _llm
self.memory = _memory
self.intent = _intent
# Manage voiceprint recognition separately for each connection
self.voiceprint_provider = None
# VAD related variables
self.client_audio_buffer = bytearray()
self.client_have_voice = False
self.client_voice_window = deque(maxlen=5)
self.first_activity_time = 0.0 # Record first activity time (ms)
self.last_activity_time = 0.0 # Unified activity timestamp (ms)
self.client_voice_stop = False
self.last_is_voice = False
# ASR related variables
# Since public local ASR might be used during deployment, variables cannot be exposed to public ASR
# So variables related to ASR need to be defined here, belonging to connection's private variables
self.asr_audio = []
self.asr_audio_queue = queue.Queue()
self.current_speaker = None # Store current speaker
self.current_language_tag = None # Store current ASR recognized language tag
# LLM related variables
self.llm_finish_task = True
self.dialogue = Dialogue()
# TTS related variables
self.sentence_id = None
# Handle TTS response with no text returned
self.tts_MessageText = ""
# IoT related variables
self.iot_descriptors = {}
self.func_handler = None
self.cmd_exit = self.config["exit_commands"]
# Whether to close connection after chat ends
self.close_after_chat = False
self.load_function_plugin = False
self.intent_type = "nointent"
self.timeout_seconds = (
int(self.config.get("close_connection_no_voice_time", 120)) + 60
) # Add 60 seconds to original first timeout for second timeout check
self.timeout_task = None
# {"mcp":true} indicates MCP function enabled
self.features = None
# Mark if connection is from MQTT
self.conn_from_mqtt_gateway = False
# Initialize prompt manager
self.prompt_manager = PromptManager(self.config, self.logger)
async def handle_connection(self, ws):
try:
# Get running event loop (must be in async context)
self.loop = asyncio.get_running_loop()
# Get and verify headers
self.headers = dict(ws.request.headers)
real_ip = self.headers.get("x-real-ip") or self.headers.get(
"x-forwarded-for"
)
if real_ip:
self.client_ip = real_ip.split(",")[0].strip()
else:
self.client_ip = ws.remote_address[0]
self.logger.bind(tag=TAG).info(
f"{self.client_ip} conn - Headers: {self.headers}"
)
self.device_id = self.headers.get("device-id", None)
# Prioritize client-id for session identification, fallback to device-id
self.client_id = self.headers.get("client-id", self.device_id)
# Force-map this physical device to your desired coach/client
if self.device_id == "b0:a6:04:5b:d7:98":
old_client_id = self.client_id
self.client_id = "26ea0ba9-2d55-4368-a56d-19c4a27c0772"
self.headers["client-id"] = self.client_id
self.logger.bind(tag=TAG).info(
f"[FORCE MAP WS] device {self.device_id}: {old_client_id} -> {self.client_id}"
)
# Authentication passed, continue processing
self.websocket = ws
# Check if from MQTT connection
request_path = ws.request.path
self.conn_from_mqtt_gateway = request_path.endswith("?from=mqtt_gateway")
if self.conn_from_mqtt_gateway:
self.logger.bind(tag=TAG).info("Connection from: MQTT gateway")
# Initialize activity timestamp
self.first_activity_time = time.time() * 1000
self.last_activity_time = time.time() * 1000
# Start timeout check task
self.timeout_task = asyncio.create_task(self._check_timeout())
self.welcome_msg = self.config["xiaozhi"]
self.welcome_msg["session_id"] = self.session_id
# Initialize config and components in background (completely non-blocking main loop)
asyncio.create_task(self._background_initialize())
try:
async for message in self.websocket:
await self._route_message(message)
except websockets.exceptions.ConnectionClosed:
self.logger.bind(tag=TAG).info("Client disconnected")
except AuthenticationError as e:
self.logger.bind(tag=TAG).error(f"Authentication failed: {str(e)}")
return
except Exception as e:
stack_trace = traceback.format_exc()
self.logger.bind(tag=TAG).error(f"Connection error: {str(e)}-{stack_trace}")
return
finally:
try:
await self._save_and_close(ws)
except Exception as final_error:
self.logger.bind(tag=TAG).error(f"Error during final cleanup: {final_error}")
# Ensure connection is closed even if saving memory fails
try:
await self.close(ws)
except Exception as close_error:
self.logger.bind(tag=TAG).error(
f"Error during forced connection close: {close_error}"
)
async def _save_and_close(self, ws):
"""Save memory and close connection"""
try:
if self.memory:
# Use thread pool to save memory asynchronously
def save_memory_task():
try:
# Create new event loop (avoid conflict with main loop)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(
self.memory.save_memory(
self.dialogue.dialogue, self.session_id
)
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"Failed to save memory: {e}")
finally:
try:
loop.close()
except Exception:
pass
# Start thread to save memory, do not wait for completion
threading.Thread(target=save_memory_task, daemon=True).start()
except Exception as e:
self.logger.bind(tag=TAG).error(f"Failed to save memory: {e}")
finally:
# Close connection immediately, do not wait for memory save completion
try:
await self.close(ws)
except Exception as close_error:
self.logger.bind(tag=TAG).error(
f"Failed to close connection after saving memory: {close_error}"
)
async def _discard_message_with_bind_prompt(self):
"""Discard message and check if binding prompt is needed"""
current_time = time.time()
# Check if binding prompt is needed
if current_time - self.last_bind_prompt_time >= self.bind_prompt_interval:
self.last_bind_prompt_time = current_time
# Reuse existing binding prompt logic
from core.handle.receiveAudioHandle import check_bind_device
asyncio.create_task(check_bind_device(self))
async def _route_message(self, message):
"""Message routing"""
# 1. Bypass bind check for protocol handshake
is_hello_msg = False
if isinstance(message, str):
try:
msg_json = json.loads(message)
if isinstance(msg_json, dict) and msg_json.get("type") == "hello":
is_hello_msg = True
except:
pass
# Check if real binding status has been obtained
if not is_hello_msg and not self.bind_completed_event.is_set():
# Real status not obtained yet, wait until real status obtained or timeout
try:
await asyncio.wait_for(self.bind_completed_event.wait(), timeout=1)
except asyncio.TimeoutError:
# Timeout still not obtained real status, discard message
await self._discard_message_with_bind_prompt()
return
# Real status obtained, check if binding is needed
if not is_hello_msg and self.need_bind:
# Binding needed, discard message
await self._discard_message_with_bind_prompt()
return
# Binding not needed, continue processing message
if isinstance(message, str):
await handleTextMessage(self, message)
elif isinstance(message, bytes):
if self.vad is None or self.asr is None:
return
# Handle audio packet from MQTT gateway
if self.conn_from_mqtt_gateway and len(message) >= 16:
handled = await self._process_mqtt_audio_message(message)
if handled:
return
# Directly process raw message when no header processing needed or no header
self.asr_audio_queue.put(message)
async def _process_mqtt_audio_message(self, message):
"""
Handle audio message from MQTT gateway, parse 16-byte header and extract audio data
Args:
message: Audio message with header
Returns:
bool: Whether the message processed successfully
"""
try:
# Extract header info
timestamp = int.from_bytes(message[8:12], "big")
audio_length = int.from_bytes(message[12:16], "big")
# Extract audio data
if audio_length > 0 and len(message) >= 16 + audio_length:
# Specified length, extract exact audio data
audio_data = message[16 : 16 + audio_length]
# Process based on timestamp sorting
self._process_websocket_audio(audio_data, timestamp)
return True
elif len(message) > 16:
# No specified length or invalid length, process remaining data after removing header
audio_data = message[16:]
self.asr_audio_queue.put(audio_data)
return True
except Exception as e:
self.logger.bind(tag=TAG).error(f"Failed to parse WebSocket audio packet: {e}")
# Process failed, return False indicating continue processing
return False
def _process_websocket_audio(self, audio_data, timestamp):
"""Process WebSocket format audio packet"""
# Initialize timestamp sequence management
if not hasattr(self, "audio_timestamp_buffer"):
self.audio_timestamp_buffer = {}
self.last_processed_timestamp = 0
self.max_timestamp_buffer_size = 20
# If timestamp is increasing, process directly
if timestamp >= self.last_processed_timestamp:
self.asr_audio_queue.put(audio_data)
self.last_processed_timestamp = timestamp
# Process subsequent packets in buffer
processed_any = True
while processed_any:
processed_any = False
for ts in sorted(self.audio_timestamp_buffer.keys()):
if ts > self.last_processed_timestamp:
buffered_audio = self.audio_timestamp_buffer.pop(ts)
self.asr_audio_queue.put(buffered_audio)
self.last_processed_timestamp = ts
processed_any = True
break
else:
# Out of order packet, buffer it
if len(self.audio_timestamp_buffer) < self.max_timestamp_buffer_size:
self.audio_timestamp_buffer[timestamp] = audio_data
else:
self.asr_audio_queue.put(audio_data)
async def handle_restart(self, message):
"""Handle server restart request"""
try:
self.logger.bind(tag=TAG).info("Received server restart command, preparing to execute...")
# Send confirmation response
await self.websocket.send(
json.dumps(
{
"type": "server",
"status": "success",
"message": "Server restarting...",
"content": {"action": "restart"},
}
)
)
# Async execute restart operation
def restart_server():
"""Actual restart execution method"""
time.sleep(1)
self.logger.bind(tag=TAG).info("Executing server restart...")
subprocess.Popen(
[sys.executable, "app.py"],
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr,
start_new_session=True,
)
os._exit(0)
# Use thread to execute restart to avoid blocking event loop
threading.Thread(target=restart_server, daemon=True).start()
except Exception as e:
self.logger.bind(tag=TAG).error(f"Restart failed: {str(e)}")
await self.websocket.send(
json.dumps(
{
"type": "server",
"status": "error",
"message": f"Restart failed: {str(e)}",
"content": {"action": "restart"},
}
)
)
def _initialize_components(self):
try:
if self.tts is None:
# Check if a private voice override is set for this client
selected_module = self.config.get("selected_module", {}).get("TTS")
has_private_voice = False
if selected_module and selected_module in self.config.get("TTS", {}):
has_private_voice = "private_voice" in self.config["TTS"][selected_module]
# Try to reuse global TTS instance ONLY if no private voice override is present
if self._tts is not None and not has_private_voice:
self.tts = self._tts
else:
self.logger.bind(tag=TAG).info(f"Initializing private TTS instance (has_private_voice={has_private_voice})")
self.tts = self._initialize_tts(use_cache=not has_private_voice)
# Open audio synthesis channel
asyncio.run_coroutine_threadsafe(
self.tts.open_audio_channels(self), self.loop
)
if self.need_bind:
self.bind_completed_event.set()
return
self.selected_module_str = build_module_string(
self.config.get("selected_module", {})
)
self.logger = create_connection_logger(self.selected_module_str)
"""Initialize components"""
prompt = None
self._load_pipeline_prompts()
persona_prompt = self.pipeline_prompts.get("persona") if self.pipeline_prompts else None
if persona_prompt:
prompt = persona_prompt
self.logger.bind(tag=TAG).info(
f"Layered persona prompt loaded successfully {prompt[:50]}..."
)
elif self.config.get("prompt") is not None:
user_prompt = self.config["prompt"]
# Legacy fallback: use quick prompt for initialization
client_id = self.headers.get("client-id")
prompt = self.prompt_manager.get_quick_prompt(user_prompt, self.device_id, client_id)
self.change_system_prompt(prompt)
self.logger.bind(tag=TAG).info(
f"Quick component initialization: prompt success {prompt[:50]}..."
)
"""Initialize local components"""
if self.vad is None:
self.vad = self._vad
if self.asr is None:
self.asr = self._initialize_asr()
# Initialize voiceprint recognition
self._initialize_voiceprint()
# Open audio recognition channel
asyncio.run_coroutine_threadsafe(
self.asr.open_audio_channels(self), self.loop
)
# Protocol Enhancement: Notify client that initialization is complete and listening has started
asyncio.run_coroutine_threadsafe(
self.websocket.send(json.dumps({"type": "stt", "state": "listening", "session_id": self.session_id})),
self.loop
)
self.logger.bind(tag=TAG).info("ASR components ready, notified client: state=listening")
"""Load memory"""
self._initialize_memory()
"""Load intent recognition"""
self._initialize_intent()
"""Initialize report thread"""
self._init_report_threads()
"""Update system prompt"""
self._init_prompt_enhancement(prompt if 'prompt' in locals() else None)
except Exception as e:
self.logger.bind(tag=TAG).error(f"Failed to instantiate components: {e}")
def _init_prompt_enhancement(self, current_prompt=None):
# Update context info
self.prompt_manager.update_context_info(self, self.client_ip)
# Prefer persona prompt from the layered pipeline if available.
persona_prompt = None
if self.pipeline_prompts:
persona_prompt = self.pipeline_prompts.get("persona")
# Fallback order:
# 1. explicit current_prompt passed in
# 2. layered persona prompt
# 3. config default prompt
base_prompt = current_prompt if current_prompt else (persona_prompt or self.config["prompt"])
client_id = self.headers.get("client-id") if self.headers else None
enhanced_prompt = self.prompt_manager.build_enhanced_prompt(
base_prompt, self.device_id, self.client_ip, client_id=client_id
)
if enhanced_prompt:
self.change_system_prompt(enhanced_prompt)
self.logger.bind(tag=TAG).debug("System prompt enhanced successfully")
def _get_volume_level(self):
"""Unified method to get volume level from headers or MCP"""
if self.mcp_volume and self.mcp_volume != "unknown":
return str(self.mcp_volume)
# Lazy sync if unknown
if hasattr(self, "mcp_client") and self.mcp_client:
try:
status_tool = "get_device_status" if self.mcp_client.has_tool("get_device_status") else None
if not status_tool:
for t in self.mcp_client.tools:
if "status" in t.lower(): status_tool = t; break
if status_tool:
from core.providers.tools.device_mcp.mcp_handler import sync_device_hardware_status
future = asyncio.run_coroutine_threadsafe(sync_device_hardware_status(self, status_tool), self.loop)
future.result(timeout=2.0)
if self.mcp_volume and self.mcp_volume != "unknown":
return str(self.mcp_volume)
except: pass
return "unknown"
def _get_battery_level(self):
"""Unified method to get battery level from headers or IoT status"""
# 1. Check HTTP Headers (Session Initialization)
if self.headers:
battery_keys = ["battery", "x-battery", "battery-level", "x-device-battery", "bat"]
for key in battery_keys:
level = self.headers.get(key)
if level and level != "unknown":
return str(level)
# 2. Check MCP Status (Cache)
if self.mcp_battery and self.mcp_battery != "unknown":
return str(self.mcp_battery)
# 3. Check IoT Descriptors
try:
for desc in self.iot_descriptors.values():
for prop in desc.properties:
prop_name = prop.get("name", "").lower()
if prop_name in ["battery", "bat", "battery_level", "vbat", "power_level"]:
level = prop.get("value")
if level is not None: return str(level)
except: pass
# 4. Lazy MCP Sync
if (not self.mcp_battery or self.mcp_battery == "unknown") and hasattr(self, "mcp_client") and self.mcp_client:
try:
status_tool = "get_device_status" if self.mcp_client.has_tool("get_device_status") else None
if not status_tool:
for t in self.mcp_client.tools:
if "status" in t.lower(): status_tool = t; break
if status_tool:
from core.providers.tools.device_mcp.mcp_handler import sync_device_hardware_status
future = asyncio.run_coroutine_threadsafe(sync_device_hardware_status(self, status_tool), self.loop)
future.result(timeout=2.5)
if self.mcp_battery and self.mcp_battery != "unknown":
return str(self.mcp_battery)
except: pass
return "unknown"
def _init_report_threads(self):
"""Initialize ASR and TTS report threads"""
if not self.read_config_from_api or self.need_bind:
return
if self.chat_history_conf == 0:
return
if self.report_thread is None or not self.report_thread.is_alive():
self.report_thread = threading.Thread(
target=self._report_worker, daemon=True
)
self.report_thread.start()
self.logger.bind(tag=TAG).info("TTS report thread started")
def _initialize_tts(self, use_cache=True):
"""Initialize TTS"""
tts = None
if not self.need_bind:
tts = initialize_tts(self.config, use_cache=use_cache)
if tts is None:
tts = DefaultTTS(self.config, delete_audio_file=True)
return tts
def _initialize_asr(self):
"""Initialize ASR"""
# Check if we can reuse the global ASR instance
# Conditions:
# 1. Global instance exists
# 2. Global instance is Local type (reusable)
# 3. Client config matches global config (no override)
current_asr = self.config["selected_module"]["ASR"]
global_asr = self.common_config["selected_module"]["ASR"]
if (
self._asr is not None
and hasattr(self._asr, "interface_type")
and self._asr.interface_type == InterfaceType.LOCAL
and current_asr == global_asr
):
# If public ASR is a local service AND matches client config, reuse it
asr = self._asr
else:
# If public ASR is remote, OR client requested a different module, initialize new instance
asr = initialize_asr(self.config)
return asr
def _initialize_voiceprint(self):
"""Initialize voiceprint recognition for current connection"""
try:
voiceprint_config = self.config.get("voiceprint", {})
if voiceprint_config:
voiceprint_provider = VoiceprintProvider(voiceprint_config)
if voiceprint_provider is not None and voiceprint_provider.enabled:
self.voiceprint_provider = voiceprint_provider
self.logger.bind(tag=TAG).info("Voiceprint recognition enabled dynamically on connection")
else:
self.logger.bind(tag=TAG).warning("Voiceprint recognition enabled but configuration incomplete")
else:
self.logger.bind(tag=TAG).info("Voiceprint recognition not enabled")
except Exception as e:
self.logger.bind(tag=TAG).warning(f"Voiceprint recognition initialization failed: {str(e)}")
def _load_local_client_config(self):
"""Load local client config to override default settings"""
if not self.headers:
return
client_id = self.headers.get("client-id", self.device_id)
if not client_id:
return
try:
config_path = os.path.join("data", client_id, "config.json")
if os.path.exists(config_path):
with open(config_path, "r") as f:
client_config = json.load(f)
# Override TTS voice if present
if "voice" in client_config:
voice = client_config["voice"]
selected_module = self.config.get("selected_module", {}).get("TTS")
if selected_module and selected_module in self.config.get("TTS", {}):
# Most TTS providers use 'private_voice' as an override
self.config["TTS"][selected_module]["private_voice"] = voice
self.logger.bind(tag=TAG).info(f"Overriding TTS voice for client {client_id}: {voice}")
# Override ASR module if present
if "asr_module" in client_config:
asr_module = client_config["asr_module"]
if asr_module in self.config.get("ASR", {}):
self.config["selected_module"]["ASR"] = asr_module
self.logger.bind(tag=TAG).info(f"Overriding ASR module for client {client_id}: {asr_module}")
else:
self.logger.bind(tag=TAG).warning(f"Client {client_id} requested invalid ASR module: {asr_module}")
except Exception as e:
self.logger.bind(tag=TAG).error(f"Failed to load local client config: {e}")
async def _background_initialize(self):
"""Initialize config and components in background (completely non-blocking main loop)"""
try:
# Load local client config first to ensure it can override other settings
self._load_local_client_config()
# Async get diff config
await self._initialize_private_config_async()
# Initialize components in thread pool
self.executor.submit(self._initialize_components)
except Exception as e:
self.logger.bind(tag=TAG).error(f"Background initialization failed: {e}")
async def _initialize_private_config_async(self):
"""Fetch private config from API async (async version, non-blocking main loop)"""
if not self.read_config_from_api:
self.need_bind = False
self.bind_completed_event.set()
return
try:
begin_time = time.time()
private_config = await get_private_config_from_api(
self.config,
self.headers.get("device-id"),
self.headers.get("client-id", self.headers.get("device-id")),
)
private_config["delete_audio"] = bool(self.config.get("delete_audio", True))
self.logger.bind(tag=TAG).info(
f"{time.time() - begin_time} seconds, async fetch private config success: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}"
)
self.need_bind = False
self.bind_completed_event.set()
except DeviceNotFoundException as e:
self.need_bind = True
private_config = {}
except DeviceBindException as e:
self.need_bind = True
self.bind_code = e.bind_code
private_config = {}
except Exception as e:
self.need_bind = True
self.logger.bind(tag=TAG).error(f"Async fetch private config failed: {e}")
private_config = {}
init_llm, init_tts, init_memory, init_intent = (
False,
False,
False,
False,
)
init_vad = check_vad_update(self.common_config, private_config)
init_asr = check_asr_update(self.common_config, private_config)
if init_vad:
self.config["VAD"] = private_config["VAD"]
self.config["selected_module"]["VAD"] = private_config["selected_module"][
"VAD"
]
if init_asr:
self.config["ASR"] = private_config["ASR"]
self.config["selected_module"]["ASR"] = private_config["selected_module"][
"ASR"
]
if private_config.get("TTS", None) is not None:
init_tts = True
self.config["TTS"] = private_config["TTS"]
self.config["selected_module"]["TTS"] = private_config["selected_module"][
"TTS"
]
if private_config.get("LLM", None) is not None:
init_llm = True
self.config["LLM"] = private_config["LLM"]
self.config["selected_module"]["LLM"] = private_config["selected_module"][
"LLM"
]
if private_config.get("VLLM", None) is not None:
self.config["VLLM"] = private_config["VLLM"]
self.config["selected_module"]["VLLM"] = private_config["selected_module"][
"VLLM"
]
if private_config.get("Memory", None) is not None:
init_memory = True
self.config["Memory"] = private_config["Memory"]
self.config["selected_module"]["Memory"] = private_config[
"selected_module"
]["Memory"]
if private_config.get("Intent", None) is not None:
init_intent = True
self.config["Intent"] = private_config["Intent"]
model_intent = private_config.get("selected_module", {}).get("Intent", {})
self.config["selected_module"]["Intent"] = model_intent
# Load plugin config
if model_intent != "Intent_nointent":
plugin_from_server = private_config.get("plugins", {})
for plugin, config_str in plugin_from_server.items():
plugin_from_server[plugin] = json.loads(config_str)
self.config["plugins"] = plugin_from_server
self.config["Intent"][self.config["selected_module"]["Intent"]][
"functions"
] = plugin_from_server.keys()
if private_config.get("prompt", None) is not None:
self.config["prompt"] = private_config["prompt"]
# Get voiceprint info
if private_config.get("voiceprint", None) is not None:
self.config["voiceprint"] = private_config["voiceprint"]
if private_config.get("summaryMemory", None) is not None:
self.config["summaryMemory"] = private_config["summaryMemory"]
if private_config.get("device_max_output_size", None) is not None:
self.max_output_size = int(private_config["device_max_output_size"])
if private_config.get("chat_history_conf", None) is not None:
self.chat_history_conf = int(private_config["chat_history_conf"])
if private_config.get("mcp_endpoint", None) is not None:
self.config["mcp_endpoint"] = private_config["mcp_endpoint"]
if private_config.get("context_providers", None) is not None:
self.config["context_providers"] = private_config["context_providers"]
# Use run_in_executor to execute initialize_modules in thread pool, avoid blocking main loop
try:
modules = await self.loop.run_in_executor(
None, # Use default thread pool
initialize_modules,
self.logger,
private_config,
init_vad,
init_asr,
init_llm,
init_tts,
init_memory,
init_intent,
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"Failed to initialize components: {e}")
modules = {}
if modules.get("tts", None) is not None:
self.tts = modules["tts"]
if modules.get("vad", None) is not None:
self.vad = modules["vad"]
if modules.get("asr", None) is not None:
self.asr = modules["asr"]
if modules.get("llm", None) is not None:
self.llm = modules["llm"]
if modules.get("Intent", None) is not None:
self.intent = modules["Intent"]
if modules.get("memory", None) is not None:
self.memory = modules["memory"]
def _initialize_memory(self):
if self.memory is None:
return
"""Initialize memory module"""
self.memory.init_memory(
role_id=self.device_id,
llm=self.llm,
summary_memory=self.config.get("summaryMemory", None),
save_to_file=not self.read_config_from_api,
)
# Get memory summary config
memory_config = self.config["Memory"]
memory_type = self.config["Memory"][self.config["selected_module"]["Memory"]][
"type"
]
# If nomen is used, return directly
if memory_type == "nomem":
return
# Use mem_local_short mode
elif memory_type == "mem_local_short":
memory_llm_name = memory_config[self.config["selected_module"]["Memory"]][
"llm"
]
if memory_llm_name and memory_llm_name in self.config["LLM"]:
# If dedicated LLM configured, create independent LLM instance
from core.utils import llm as llm_utils
memory_llm_config = self.config["LLM"][memory_llm_name]
memory_llm_type = memory_llm_config.get("type", memory_llm_name)
memory_llm = llm_utils.create_instance(
memory_llm_type, memory_llm_config
)
self.logger.bind(tag=TAG).info(
f"Created dedicated LLM for memory summary: {memory_llm_name}, type: {memory_llm_type}"
)
self.memory.set_llm(memory_llm)
else:
# Otherwise use main LLM
self.memory.set_llm(self.llm)
self.logger.bind(tag=TAG).info("Using main LLM as intent recognition model")
def _initialize_intent(self):
"""Standardized to Uppercase 'Intent' to match config.yaml"""
if self.intent is None:
return
# Use Uppercase 'Intent' everywhere
selected_intent = self.config["selected_module"].get("Intent")
if not selected_intent:
return
self.intent_type = self.config["Intent"][selected_intent]["type"]
if self.intent_type == "function_call" or self.intent_type == "intent_llm":
self.load_function_plugin = True
intent_config = self.config["Intent"]
if self.intent_type == "nointent":
return
elif self.intent_type == "intent_llm":
intent_llm_name = intent_config[selected_intent].get("llm")
if intent_llm_name and intent_llm_name in self.config["LLM"]:
from core.utils import llm as llm_utils
intent_llm_config = self.config["LLM"][intent_llm_name]
intent_llm_type = intent_llm_config.get("type", intent_llm_name)
intent_llm = llm_utils.create_instance(intent_llm_type, intent_llm_config)
self.intent.set_llm(intent_llm)
self.logger.bind(tag=TAG).info(f"Intent Brain Linked: {intent_llm_name}")
else:
self.intent.set_llm(self.llm)
self.logger.bind(tag=TAG).info("Using Main LLM for Intent.")
"""Load unified tool handler"""
self.func_handler = UnifiedToolHandler(self)
def change_system_prompt(self, prompt):
self.prompt = prompt
# Update system prompt to context
self.dialogue.update_system_message(self.prompt)
def _load_pipeline_prompts(self):
"""Load persona / decision / interpretation prompts for the current client."""
try:
client_id = self.headers.get("client-id") if self.headers else None
self.pipeline_prompts = self.prompt_manager.get_pipeline_prompts(
client_id=client_id,
device_id=self.device_id,
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"Failed to load pipeline prompts: {e}")
self.pipeline_prompts = {}
def _llm_single_shot(self, system_prompt: str, user_payload: Any) -> str:
"""Run a one-shot LLM call without mutating the main dialogue history."""
if not self.llm:
return ""
try:
if isinstance(user_payload, str):
user_content = user_payload
else:
user_content = json.dumps(user_payload, ensure_ascii=False, indent=2)
temp_dialogue = Dialogue()
temp_dialogue.update_system_message(system_prompt)
temp_dialogue.put(Message(role="user", content=user_content))
memory_str = None
messages = temp_dialogue.get_llm_dialogue_with_memory(
memory_str, self.config.get("voiceprint", {})
)
chunks = []
temp_session_id = str(uuid.uuid4())
for chunk in self.llm.response(temp_session_id, messages):