This repository was archived by the owner on Jan 7, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathv2.py
More file actions
1678 lines (1447 loc) · 74.3 KB
/
Copy pathv2.py
File metadata and controls
1678 lines (1447 loc) · 74.3 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 asyncio
import base64
import io
import traceback
import yaml
import json
import logging
import time
import random
import cv2
import pyaudio
import PIL.Image
import mss
import argparse
from google import genai
from google.genai import types
# Import GenAI errors for quota detection
try:
from google.genai import errors
GENAI_ERRORS_AVAILABLE = True
except ImportError:
GENAI_ERRORS_AVAILABLE = False
errors = None
# Try to import common WebSocket exceptions that might be raised
try:
from websockets.exceptions import ConnectionClosedError, ConnectionClosedOK
WEBSOCKETS_AVAILABLE = True
except ImportError:
# If websockets library is not available, we'll handle these as generic exceptions
WEBSOCKETS_AVAILABLE = False
ConnectionClosedError = Exception # Fallback
ConnectionClosedOK = Exception # Fallback
# Import our tools module
import tools as memory_tools
# Import OSC module for VRChat integration
import osc
# Import append system for system prompt enhancement
import append
# Import Chat API for WebUI functionality
try:
from api import chat as chat_api
CHAT_API_AVAILABLE = True
except ImportError:
CHAT_API_AVAILABLE = False
chat_api = None
# Import MyInstants for audio timing notifications
try:
from myinstants import myinstants_client
MYINSTANTS_AVAILABLE = True
except ImportError:
MYINSTANTS_AVAILABLE = False
myinstants_client = None
# Session persistence
try:
from session_persistence import get_persistence_manager
SESSION_PERSISTENCE_AVAILABLE = True
except Exception:
get_persistence_manager = None
SESSION_PERSISTENCE_AVAILABLE = False
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Model and default configuration for V2
V2_MODEL = "models/gemini-2.5-flash-native-audio-preview-09-2025"
V2_DEFAULT_MODE = "screen"
# Custom exception for V1 mode switching
class V1ModeSwitchRequested(Exception):
"""Exception raised when V1 mode switch is requested."""
pass
class APIKeyManager:
"""Manages API keys with automatic failover for quota exceeded errors."""
def __init__(self, config):
self.config = config
api_config = config.get('api', {})
# Primary API key
self.primary_key = None
if 'api_key' in api_config:
self.primary_key = api_config['api_key']
elif 'key_env_var' in api_config:
self.primary_key = os.environ.get(api_config['key_env_var'])
else:
self.primary_key = os.environ.get('GEMINI_API_KEY')
# Backup API keys
self.backup_keys = api_config.get('backup_api_keys', [])
# Current state
self.current_key_index = -1 # -1 means using primary key
self.failed_keys = set() # Track keys that have failed
self.last_switch_time = 0
self.switch_cooldown = 60 # 60 seconds cooldown between switches
# Validate we have at least a primary key
if not self.primary_key:
raise ValueError("No primary API key found!")
logger.info(f"APIKeyManager initialized with primary key and {len(self.backup_keys)} backup keys")
def get_current_key(self):
"""Get the currently active API key."""
if self.current_key_index == -1:
return self.primary_key
elif 0 <= self.current_key_index < len(self.backup_keys):
return self.backup_keys[self.current_key_index]
else:
# Fallback to primary if index is invalid
self.current_key_index = -1
return self.primary_key
def get_current_key_description(self):
"""Get a description of the current key for logging."""
if self.current_key_index == -1:
return "primary"
else:
return f"backup #{self.current_key_index + 1}"
def is_quota_error(self, error):
"""Check if an error is a quota exceeded error."""
if not GENAI_ERRORS_AVAILABLE:
# Fallback to string matching if errors module not available
# Consider common quota/billing phrases regardless of HTTP code presence
error_str = str(error).lower()
# Capture attributes from common websocket/client errors
code = getattr(error, 'code', None) or getattr(error, 'status', None)
reason = getattr(error, 'reason', None)
if isinstance(reason, bytes):
try:
reason = reason.decode('utf-8', errors='ignore')
except Exception:
reason = str(reason)
reason_str = (str(reason).lower() if reason is not None else '')
quota_keywords = [
'quota', 'exceeded your current quota', 'exceeded quota', 'billing', 'plan',
'rate limit', 'resource_exhausted', 'resource exhausted', 'over quota'
]
# If websocket closed with 1011 and reason mentions quota/billing
if (code == 1011) and any(k in reason_str or k in error_str for k in quota_keywords):
return True
# If message clearly states quota/billing regardless of code
if any(k in error_str for k in quota_keywords):
return True
# As a final heuristic, allow classic 429 + keywords
return (
'429' in error_str and any(k in error_str for k in quota_keywords)
)
# Use proper error detection with google.genai.errors
if isinstance(error, errors.ClientError):
# Check for 429 status code (Too Many Requests)
if error.code == 429:
return True
# Check for RESOURCE_EXHAUSTED status
if error.status and 'RESOURCE_EXHAUSTED' in str(error.status).upper():
return True
# Check message content for quota-related terms
if error.message:
message_lower = error.message.lower()
return any(keyword in message_lower for keyword in [
'quota', 'exceeded', 'rate limit', 'resource_exhausted', 'billing', 'plan'
])
# Handle ExceptionGroup that might contain quota errors
if hasattr(error, 'exceptions'):
for exc in error.exceptions:
if self.is_quota_error(exc):
return True
# Fallback to string matching without requiring 429
error_str = str(error).lower()
quota_keywords = [
'quota', 'exceeded your current quota', 'exceeded quota', 'billing', 'plan',
'rate limit', 'resource_exhausted', 'resource exhausted', 'over quota'
]
return any(k in error_str for k in quota_keywords)
def can_switch_key(self, ignore_cooldown: bool = False):
"""Check if we can switch to another API key.
Args:
ignore_cooldown: If True, ignore the switch cooldown (useful for hard quota errors).
"""
# Check cooldown unless explicitly ignored
if not ignore_cooldown and (time.time() - self.last_switch_time < self.switch_cooldown):
return False
# Check if we have more keys available
total_keys = 1 + len(self.backup_keys) # primary + backups
available_keys = total_keys - len(self.failed_keys)
return available_keys > 1 # Need at least one more key to switch to
def switch_to_next_key(self, ignore_cooldown: bool = False):
"""Switch to the next available API key.
Args:
ignore_cooldown: If True, bypass cooldown checks to rotate keys immediately.
"""
if not self.can_switch_key(ignore_cooldown=ignore_cooldown):
logger.warning("Cannot switch API key: cooldown active or no more keys available")
return False
# Mark current key as failed
current_key = self.get_current_key()
self.failed_keys.add(current_key)
# Find next available key
next_key_found = False
# Try backup keys first
for i, backup_key in enumerate(self.backup_keys):
if backup_key not in self.failed_keys:
self.current_key_index = i
next_key_found = True
break
# If no backup keys available, try primary (if not failed)
if not next_key_found and self.primary_key not in self.failed_keys:
self.current_key_index = -1
next_key_found = True
if next_key_found:
# Update last switch time unless we're bypassing cooldown (still record moment for telemetry)
self.last_switch_time = time.time()
new_key_desc = self.get_current_key_description()
logger.info(f"Switched to {new_key_desc} API key due to quota exceeded")
return True
else:
logger.error("No more available API keys to switch to!")
return False
def reset_failed_keys(self):
"""Reset the failed keys set (useful for periodic retry)."""
self.failed_keys.clear()
logger.info("Reset failed API keys - all keys available for retry")
def create_client(self):
"""Create a new client with the current API key."""
current_key = self.get_current_key()
api_config = self.config.get('api', {})
if not current_key or not current_key.strip():
raise ValueError("Current API key is empty!")
client = genai.Client(
http_options={"api_version": api_config.get('version', 'v1beta')},
api_key=current_key,
)
logger.info(f"Created new client with {self.get_current_key_description()} API key")
return client
# Global variables that will be set by setup_v2_globals
FORMAT = pyaudio.paInt16
CHANNELS = 1
SEND_SAMPLE_RATE = 16000
RECEIVE_SAMPLE_RATE = 24000
CHUNK_SIZE = 1024
pya = pyaudio.PyAudio()
# Global client instance - will be shared with main.py
client = None
CONFIG = None
def setup_v2_globals(main_config, main_client):
"""Setup V2 globals using the main configuration and client."""
global client, CONFIG, FORMAT, CHANNELS, SEND_SAMPLE_RATE, RECEIVE_SAMPLE_RATE, CHUNK_SIZE
# Use the existing client from main.py
client = main_client
# Audio configuration from main config
audio_config = main_config.get('audio', {})
FORMAT = getattr(pyaudio, f"paInt{audio_config.get('format', 16)}")
CHANNELS = audio_config.get('channels', 1)
SEND_SAMPLE_RATE = audio_config.get('send_sample_rate', 16000)
RECEIVE_SAMPLE_RATE = audio_config.get('receive_sample_rate', 24000)
CHUNK_SIZE = audio_config.get('chunk_size', 1024)
# Tools configuration - use same tools as main
tools_config = main_config.get('tools', {})
tools = []
# Add Google Search tool if enabled
if tools_config.get('google_search', True):
tools.append(types.Tool(google_search=types.GoogleSearch()))
# Add memory system tools if enabled (default: True)
if tools_config.get('memory_system', True):
memory_system_tools = memory_tools.get_all_tools(main_config)
for tool in memory_system_tools:
tools.append(types.Tool(function_declarations=tool['function_declarations']))
# Add custom function declarations from config
function_declarations = tools_config.get('function_declarations', [])
if function_declarations:
tools.append(types.Tool(function_declarations=function_declarations))
# V2 specific configuration using main config as base
live_config = main_config.get('live_connect', {})
speech_config = live_config.get('speech', {})
voice_config = speech_config.get('voice', {})
context_window_config = live_config.get('context_window', {})
# Get system instruction from main config
# Import functions directly to avoid circular import
def load_prompts_v2(prompts_path="prompts.json"):
"""Load prompts from JSON file."""
try:
with open(prompts_path, 'r', encoding='utf-8') as file:
return json.load(file)
except FileNotFoundError:
logger.warning(f"Prompts file {prompts_path} not found. Using default prompt.")
return {
"normal": {
"name": "Default Assistant",
"description": "Gabriel, a helpful assistant",
"prompt": "You are Gabriel, a helpful assistant."
}
}
except json.JSONDecodeError as e:
logger.error(f"Error parsing prompts file: {e}")
return {
"normal": {
"name": "Default Assistant",
"description": "Gabriel, a helpful assistant",
"prompt": "You are Gabriel, a helpful assistant."
}
}
def get_system_instruction_v2(config, prompts):
"""Get the system instruction based on config selection."""
live_config = config.get('live_connect', {})
prompt_key = live_config.get('prompt', 'normal')
# Handle custom prompt
if prompt_key == 'custom':
custom_prompt = live_config.get('custom_prompt')
if custom_prompt:
base_instruction = custom_prompt
else:
logger.warning("Custom prompt selected but custom_prompt not found in config. Using default.")
prompt_key = 'normal'
base_instruction = prompts.get('normal', {}).get('prompt', 'You are Gabriel, a helpful assistant.')
else:
# Get prompt from prompts.json
if prompt_key in prompts:
prompt_info = prompts[prompt_key]
logger.info(f"Using prompt: {prompt_info.get('name', prompt_key)} - {prompt_info.get('description', 'No description')}")
base_instruction = prompt_info['prompt']
else:
logger.warning(f"Prompt '{prompt_key}' not found in prompts.json. Available prompts: {', '.join(prompts.keys())}. Using 'normal'.")
base_instruction = prompts.get('normal', {}).get('prompt', 'You are Gabriel, a helpful assistant.')
# Apply append system to enhance the base instruction
append_config = config.get('append_system', {})
appends_path = append_config.get('file', 'appends.json')
append_variables = append_config.get('variables', {})
# Add config-based variables
if 'add_config_info' in append_config and append_config['add_config_info']:
append_variables.update({
'model_name': config.get('model', {}).get('name', 'Unknown'),
'audio_sample_rate': str(config.get('audio', {}).get('send_sample_rate', 16000)),
'video_mode': config.get('defaults', {}).get('mode', 'camera')
})
# Ensure we append personality name and description only (not full content)
append_variables.setdefault('personalities_include_description', True)
enhanced_instruction = append.append_to_system_instruction(
base_instruction,
appends_path,
append_variables,
config # Pass full config for memory integration
)
return enhanced_instruction
prompts = load_prompts_v2()
system_instruction = get_system_instruction_v2(main_config, prompts)
# Live connect configuration
live_config = main_config.get('live_connect', {})
speech_config = live_config.get('speech', {})
voice_config = speech_config.get('voice', {})
context_window_config = live_config.get('context_window', {})
session_resumption_config = live_config.get('session_resumption', {})
# Setup session resumption configuration for V2
# Note: Session resumption may not be supported on all V2 models
session_resumption = None
if session_resumption_config.get('enabled', False):
try:
session_resumption = types.SessionResumptionConfig(
# The handle parameter is set dynamically by V2SessionManager
# when resuming a session. For new sessions, this will be None.
handle=None
)
logger.info("V2 session resumption enabled")
except Exception as e:
logger.warning(f"V2 session resumption not available: {e}")
session_resumption = None
CONFIG = types.LiveConnectConfig(
response_modalities=live_config.get('response_modalities', ["AUDIO"]),
media_resolution=live_config.get('media_resolution', "MEDIA_RESOLUTION_MEDIUM"),
thinking_config=types.ThinkingConfig(
thinking_budget=live_config.get('thinking_budget', 1024),
include_thoughts=True,
),
speech_config=types.SpeechConfig(
# Note: V2 mode doesn't support language_code, so we omit it
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(
voice_name=voice_config.get('name', 'Puck')
)
)
),
realtime_input_config=types.RealtimeInputConfig(
turn_coverage="TURN_INCLUDES_ALL_INPUT"
),
context_window_compression=types.ContextWindowCompressionConfig(
trigger_tokens=context_window_config.get('trigger_tokens', 25600),
sliding_window=types.SlidingWindow(
target_tokens=context_window_config.get('sliding_window_target_tokens', 12800)
),
),
session_resumption=session_resumption,
tools=tools,
system_instruction=types.Content(
parts=[types.Part.from_text(text=system_instruction)],
role="user"
),
# Enable audio transcription for VRChat text output when using AUDIO mode
output_audio_transcription=live_config.get('output_audio_transcription', {}),
)
logger.info("V2 mode globals initialized successfully")
class V2SessionManager:
"""Manages session resumption and automatic reconnection for V2 mode."""
def __init__(self, config, api_key_manager):
self.config = config
self.api_key_manager = api_key_manager
self.session_config = config.get('session_management', {})
self.auto_reconnect_config = self.session_config.get('auto_reconnect', {})
self.monitoring_config = self.session_config.get('monitoring', {})
# Session state
self.session_handle = None
self.last_consumed_message_index = None
self.is_reconnecting = False
self.connection_start_time = None
self.last_heartbeat = None
# Reconnection settings
self.max_retries = self.auto_reconnect_config.get('max_retries', 5)
self.initial_delay = self.auto_reconnect_config.get('initial_delay', 1.0)
self.max_delay = self.auto_reconnect_config.get('max_delay', 30.0)
self.exponential_base = self.auto_reconnect_config.get('exponential_base', 2.0)
self.jitter = self.auto_reconnect_config.get('jitter', 0.1)
# API key switching state
self.quota_retry_count = 0
self.max_quota_retries = 3 # Max retries per API key
self.persistence = None
self.persistence_task = None
if SESSION_PERSISTENCE_AVAILABLE:
save_interval = self.session_config.get('save_interval', 30)
self.persistence = get_persistence_manager(save_interval)
logger.info(f"V2 session persistence enabled with {save_interval}s interval")
logger.info("V2SessionManager initialized with API key management")
def get_session_config(self):
"""Get the current session configuration with resumption handle if available."""
global CONFIG
# Check if session resumption is available and enabled for V2
if hasattr(CONFIG, 'session_resumption') and CONFIG.session_resumption is not None:
if self.session_handle:
try:
# Update the session resumption config with our handle
CONFIG.session_resumption.handle = self.session_handle
logger.info(f"V2 using session resumption handle: {self.session_handle[:20]}...")
except Exception as e:
logger.warning(f"V2 failed to set session resumption handle: {e}")
else:
# Guard against stale handle lingering in CONFIG when we intentionally cleared it
try:
if getattr(CONFIG.session_resumption, 'handle', None):
CONFIG.session_resumption.handle = None
logger.info("V2 cleared stale session resumption handle in config (fresh session)")
except Exception as e:
logger.warning(f"V2 failed to clear stale session handle: {e}")
return CONFIG
def handle_session_resumption_update(self, update):
"""Handle incoming session resumption update."""
if hasattr(update, 'new_handle') and update.new_handle:
self.session_handle = update.new_handle
logger.info(f"V2 updated session handle: {self.session_handle[:20]}...")
if hasattr(update, 'resumable'):
logger.info(f"V2 session resumable: {update.resumable}")
if hasattr(update, 'last_consumed_client_message_index'):
self.last_consumed_message_index = update.last_consumed_client_message_index
logger.info(f"V2 last consumed message index: {self.last_consumed_message_index}")
def handle_go_away(self, go_away):
"""Handle GoAway message indicating impending disconnection."""
logger.warning("V2 GoAway message received from server")
if hasattr(go_away, 'time_left'):
time_left = go_away.time_left
logger.warning(f"V2 server will disconnect in: {time_left}")
# Parse the duration string (format: "XXXs" for seconds)
if isinstance(time_left, str) and time_left.endswith('s'):
try:
seconds = float(time_left[:-1])
if seconds < 30: # If less than 30 seconds, prepare for reconnection
logger.info("V2 preparing for imminent disconnection...")
self.is_reconnecting = True
except ValueError:
logger.warning(f"V2 could not parse time_left: {time_left}")
# Always set reconnecting flag when GoAway is received
self.is_reconnecting = True
logger.info("V2 GoAway received - marking session for reconnection")
# Log additional GoAway details if available
if hasattr(go_away, 'reason'):
logger.warning(f"V2 GoAway reason: {go_away.reason}")
if hasattr(go_away, 'debug_description'):
logger.warning(f"V2 GoAway debug info: {go_away.debug_description}")
async def handle_quota_exceeded(self, error):
"""Handle quota exceeded errors by switching API keys."""
logger.warning(f"V2 quota exceeded detected: {error}")
# On clear quota/billing errors we should bypass cooldown to recover faster
if self.api_key_manager.can_switch_key(ignore_cooldown=True):
# Try to switch to next available API key
if self.api_key_manager.switch_to_next_key(ignore_cooldown=True):
# Reset quota retry count for new key
self.quota_retry_count = 0
# IMPORTANT: Session handles cannot cross API keys; clear any existing handle
self.clear_session_resumption(reason="API key switched due to quota exceeded")
logger.info("V2 switched to backup API key, will retry connection")
return True
else:
logger.error("V2 no more backup API keys available")
return False
else:
self.quota_retry_count += 1
logger.warning(f"V2 quota retry {self.quota_retry_count}/{self.max_quota_retries} for current API key")
if self.quota_retry_count >= self.max_quota_retries:
# Reset failed keys and try switching again as last resort
logger.info("V2 max quota retries reached, resetting failed keys and trying again")
self.api_key_manager.reset_failed_keys()
if self.api_key_manager.switch_to_next_key():
self.quota_retry_count = 0
return True
else:
logger.error("V2 all API keys exhausted, cannot continue")
return False
# Wait a bit before retrying with same key
await asyncio.sleep(min(5 * self.quota_retry_count, 30))
return True
async def calculate_reconnect_delay(self, retry_count):
"""Calculate delay before reconnection attempt with exponential backoff and jitter."""
if not self.auto_reconnect_config.get('enabled', True):
return None
if retry_count >= self.max_retries:
logger.error(f"V2 max retries ({self.max_retries}) exceeded. Giving up.")
return None
# Exponential backoff
delay = min(self.initial_delay * (self.exponential_base ** retry_count), self.max_delay)
# Add jitter
jitter_amount = delay * self.jitter * (random.random() * 2 - 1) # +/- jitter%
delay += jitter_amount
delay = max(0, delay) # Ensure non-negative
logger.info(f"V2 reconnection attempt {retry_count + 1}/{self.max_retries} in {delay:.2f}s")
return delay
def reset_connection_state(self):
"""Reset connection state for new session."""
self.connection_start_time = time.time()
self.last_heartbeat = self.connection_start_time
self.is_reconnecting = False
logger.info("V2 connection state reset")
def should_attempt_reconnect(self, error):
"""Determine if we should attempt to reconnect based on the error."""
if not self.auto_reconnect_config.get('enabled', True):
return False
# Handle policy violation 1008: session not found -> clear session handle and reconnect
if self._is_policy_session_not_found(error):
self.clear_session_resumption(reason="Server reported session not found (1008 policy violation)")
logger.info("V2 treating 1008 session-not-found as reconnectable after clearing session handle")
return True
# Check for quota exceeded errors first
if self.api_key_manager.is_quota_error(error):
logger.info("V2 quota exceeded error detected - will attempt API key switch")
return True
# If we're already marked for reconnection (e.g., due to GoAway), attempt it
if self.is_reconnecting:
logger.info("V2 reconnection flagged due to GoAway message")
return True
# Handle ExceptionGroup (from TaskGroup) by checking its exceptions
if hasattr(error, 'exceptions'): # ExceptionGroup
for exc in error.exceptions:
# Handle policy violation 1008 inside ExceptionGroup
if self._is_policy_session_not_found(exc):
self.clear_session_resumption(reason="Server reported session not found (1008 policy violation)")
logger.info("V2 treating 1008 session-not-found (inner) as reconnectable after clearing session handle")
return True
# Check for V1ModeSwitchRequested in the exception group
if isinstance(exc, V1ModeSwitchRequested):
logger.info("V1ModeSwitchRequested found in ExceptionGroup - not a reconnection case")
return False
# Check for quota errors in exception group
if self.api_key_manager.is_quota_error(exc):
logger.info("V2 quota exceeded error found in ExceptionGroup")
return True
if self._is_reconnectable_error(exc):
# Log specific details about WebSocket errors
if '1011' in str(exc) or 'deadline expired' in str(exc).lower():
logger.warning(f"V2 detected WebSocket deadline/timeout error: {exc}")
return True
return False
# Check for standalone V1ModeSwitchRequested
if isinstance(error, V1ModeSwitchRequested):
logger.info("V1ModeSwitchRequested - not a reconnection case")
return False
return self._is_reconnectable_error(error)
def _is_reconnectable_error(self, error):
"""Check if a single error is reconnectable."""
# Ignore local screen capture errors (not network related)
try:
ename = error.__class__.__name__.lower()
estr = str(error).lower()
except Exception:
ename = ""
estr = ""
if ("screenshoterror" in ename) or ("gdi32.getdibits" in estr) or ("mss" in ename and "grab" in estr):
logger.info(f"V2 local screen capture error detected (non-network): {type(error).__name__}: {error}")
return False
# Always attempt reconnect for connection-related errors
if isinstance(error, (ConnectionError, asyncio.TimeoutError)):
return True
# Also attempt reconnect for cancelled errors (could be from GoAway)
if isinstance(error, asyncio.CancelledError):
return True
# Handle WebSocket-specific exceptions if available
if WEBSOCKETS_AVAILABLE:
if isinstance(error, (ConnectionClosedError, ConnectionClosedOK)):
logger.info(f"V2 WebSocket connection closed: {error}")
return True
# Handle WebSocket-specific errors that might occur
if hasattr(error, '__class__'):
error_name = error.__class__.__name__.lower()
# Add specific WebSocket error types
if any(keyword in error_name for keyword in [
'websocket', 'connection', 'network', 'timeout', 'aborted',
'connectionclosederror', 'connectionclosed', 'websocketclosed'
]):
return True
# Handle general exceptions that might indicate disconnection
# These are common patterns for network disconnections
if isinstance(error, Exception):
error_str = str(error).lower()
if any(keyword in error_str for keyword in [
'connection', 'disconnect', 'timeout', 'aborted',
'websocket', 'network', 'broken pipe', 'reset by peer',
'deadline expired', 'connectionclosederror', 'internal error',
'websocket closed', 'connection closed', '1011 (internal error)',
'1011', 'service is currently unavailable', 'server error'
]):
logger.info(f"V2 reconnectable error detected: {error}")
return True
logger.warning(f"V2 error not configured for reconnection: {type(error).__name__}: {error}")
return False
def _is_policy_session_not_found(self, error) -> bool:
"""Detect WebSocket 1008 policy violation with 'session not found' message."""
try:
msg = str(error)
low = msg.lower()
except Exception:
return False
# Look for 1008 and session not found indicators
if ("1008" in low or "policy violation" in low) and ("session not found" in low or "bidigeneratecontent" in low):
logger.warning(f"V2 detected 1008 policy violation / session not found: {msg}")
return True
return False
def clear_session_resumption(self, reason: str | None = None):
"""Clear session resumption state so next session starts fresh.
This is required when changing API keys because server session handles
are not valid across different credentials.
"""
global CONFIG
if reason:
logger.info(f"V2 clearing session resumption state: {reason}")
else:
logger.info("V2 clearing session resumption state")
# Clear local state
self.session_handle = None
self.last_consumed_message_index = None
# Best-effort clear on global CONFIG, if available
try:
if hasattr(CONFIG, 'session_resumption') and CONFIG.session_resumption is not None:
CONFIG.session_resumption.handle = None
except Exception as e:
logger.warning(f"V2 failed to clear session resumption handle on CONFIG: {e}")
def start_periodic_save(self, mode: str = "v2"):
if self.persistence and not self.persistence_task:
handle_getter = lambda: self.session_handle
metadata_getter = lambda: {
"last_consumed_index": self.last_consumed_message_index,
"connection_start_time": self.connection_start_time
}
self.persistence_task = asyncio.create_task(
self.persistence.start_periodic_save(handle_getter, mode, metadata_getter)
)
logger.info(f"V2 started periodic session save for {mode} mode")
def stop_periodic_save(self, mode: str = "v2"):
if self.persistence:
self.persistence.stop_periodic_save()
if self.session_handle:
metadata = {
"last_consumed_index": self.last_consumed_message_index,
"connection_start_time": self.connection_start_time
}
self.persistence.save_session_handle(self.session_handle, mode, metadata)
logger.info(f"V2 saved final session handle on stop for {mode} mode")
if self.persistence_task:
self.persistence_task.cancel()
self.persistence_task = None
class V2AudioLoop:
def __init__(self, video_mode=V2_DEFAULT_MODE, session_handle=None, config=None, api_key_manager=None):
self.video_mode = video_mode
self.session_handle = session_handle # For session transfer
self.config = config or {} # Store config reference
self.api_key_manager = api_key_manager
# Get video configuration
self.video_config = self.config.get('video', {})
# Get queue configuration
queue_config = self.config.get('queues', {})
self.output_queue_maxsize = queue_config.get('output_queue_maxsize', 5)
# Get debug configuration
self.debug_config = self.config.get('debug', {})
# Initialize session manager for V2
self.session_manager = V2SessionManager(self.config, self.api_key_manager)
# Set session handle if provided (for session transfer from V1)
if session_handle:
self.session_manager.session_handle = session_handle
logger.info(f"V2 initialized with transferred session handle: {session_handle[:20]}...")
self.audio_in_queue = None
self.out_queue = None
self.session = None
self.receive_audio_task = None
self.play_audio_task = None
# V1 mode switching
self.switch_to_v1_requested = False
# Current client reference (will be updated on API key switches)
self.current_client = None
# Thinking streaming state
self._thinking_task = None
self._thinking_active = False
self._current_thinking_text = ""
self._current_text_response = ""
self._thinking_marquee_started = False
self._final_marquee_started = False
async def _stop_final_marquee_after_delay(self, client, key: str, delay: float):
try:
await asyncio.sleep(delay)
try:
client.stop_ui_marquee(key + ":final")
except Exception:
pass
self._final_marquee_started = False
# Clear the accumulated final response and return to idle UI
try:
self._current_text_response = ""
except Exception:
pass
try:
client.maybe_send_idle_ui()
except Exception:
pass
except asyncio.CancelledError:
return
except Exception:
return
def _get_frame(self, cap):
"""Get frame from camera with V2 optimizations."""
# Get image configuration
image_config = self.video_config.get('image', {})
thumbnail_size = image_config.get('thumbnail_size', [1024, 1024])
image_format = image_config.get('format', 'jpeg')
mime_type = image_config.get('mime_type', 'image/jpeg')
# Read the frame
ret, frame = cap.read()
# Check if the frame was read successfully
if not ret:
return None
# Fix: Convert BGR to RGB color space
# OpenCV captures in BGR but PIL expects RGB format
# This prevents the blue tint in the video feed
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
img = PIL.Image.fromarray(frame_rgb) # Now using RGB frame
img.thumbnail(thumbnail_size)
image_io = io.BytesIO()
img.save(image_io, format=image_format)
image_io.seek(0)
image_bytes = image_io.read()
return {"mime_type": mime_type, "data": base64.b64encode(image_bytes).decode()}
async def get_frames(self):
"""Camera frame capture for V2 mode."""
# Get camera configuration
camera_config = self.video_config.get('camera', {})
device_index = camera_config.get('device_index', 0)
frame_delay = camera_config.get('frame_delay', 1.0)
# This takes about a second, and will block the whole program
# causing the audio pipeline to overflow if you don't to_thread it.
cap = await asyncio.to_thread(
cv2.VideoCapture, device_index
) # device_index represents the camera to use
while True:
frame = await asyncio.to_thread(self._get_frame, cap)
if frame is None:
break
await asyncio.sleep(frame_delay)
await self.out_queue.put(frame)
# Release the VideoCapture object
cap.release()
def _get_screen(self):
"""Get screen capture for V2 mode."""
# Get screen and image configuration
screen_config = self.video_config.get('screen', {})
image_config = self.video_config.get('image', {})
monitor_index = screen_config.get('monitor_index', 0)
image_format = image_config.get('format', 'jpeg')
mime_type = image_config.get('mime_type', 'image/jpeg')
sct = None
try:
sct = mss.mss()
monitors = getattr(sct, 'monitors', [])
if not monitors:
logger.debug("V2 no monitors reported by mss; skipping frame")
return None
safe_index = monitor_index
if safe_index < 0 or safe_index >= len(monitors):
logger.warning(f"V2 configured monitor_index {monitor_index} out of range (0..{len(monitors)-1}); using 0")
safe_index = 0
monitor = monitors[safe_index]
try:
i = sct.grab(monitor)
except Exception as grab_err:
logger.debug(f"V2 screen grab failed: {grab_err}")
return None
try:
image_bytes = mss.tools.to_png(i.rgb, i.size)
img = PIL.Image.open(io.BytesIO(image_bytes))
image_io = io.BytesIO()
img.save(image_io, format=image_format)
image_io.seek(0)
image_bytes = image_io.read()
return {"mime_type": mime_type, "data": base64.b64encode(image_bytes).decode()}
except Exception as enc_err:
logger.debug(f"V2 screen encode failed: {enc_err}")
return None
finally:
try:
if sct is not None:
sct.close()
except Exception:
pass
async def get_screen(self):
"""Screen capture loop for V2 mode."""
# Get screen configuration
screen_config = self.video_config.get('screen', {})
frame_delay = screen_config.get('frame_delay', 1.0)
while True:
frame = await asyncio.to_thread(self._get_screen)
if frame is None:
# Transient capture failure; short backoff and continue
await asyncio.sleep(min(frame_delay, 0.2))
continue
await asyncio.sleep(frame_delay)
await self.out_queue.put(frame)
async def send_realtime(self):
"""Send real-time data to the session."""
while True:
msg = await self.out_queue.get()
await self.session.send(input=msg)
async def listen_audio(self):
"""Audio input capture for V2 mode."""
mic_info = pya.get_default_input_device_info()
self.audio_stream = await asyncio.to_thread(
pya.open,
format=FORMAT,
channels=CHANNELS,
rate=SEND_SAMPLE_RATE,
input=True,
input_device_index=mic_info["index"],
frames_per_buffer=CHUNK_SIZE,
)
# Use debug configuration