File size: 54,627 Bytes
bbe1d5b
9dca33d
46b6144
f544196
a78af19
bbe1d5b
 
6c7c2aa
 
bbe1d5b
1090499
9dca33d
f544196
 
1090499
9dca33d
bbe1d5b
9dca33d
1090499
 
9dca33d
 
6c7c2aa
 
 
c4ab828
bbe1d5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c7c2aa
 
9dca33d
 
 
 
 
 
 
6c7c2aa
 
 
9dca33d
6c7c2aa
 
bbe1d5b
 
 
9dca33d
bbe1d5b
6c7c2aa
 
9dca33d
f544196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbe1d5b
f544196
bbe1d5b
 
9dca33d
f544196
9dca33d
bbe1d5b
 
 
f544196
bbe1d5b
f544196
 
bbe1d5b
 
 
9dca33d
 
 
 
 
f544196
 
 
 
 
 
 
 
bbe1d5b
 
 
 
f544196
bbe1d5b
 
f544196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9dca33d
 
f544196
 
 
 
 
 
 
bbe1d5b
6c7c2aa
bbe1d5b
f544196
bbe1d5b
6c7c2aa
9dca33d
f544196
9dca33d
6c7c2aa
 
 
bbe1d5b
6c7c2aa
 
 
 
 
 
 
 
9dca33d
 
f544196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1090499
9dca33d
 
 
 
 
f544196
9dca33d
1090499
9dca33d
1090499
9dca33d
1090499
 
 
 
 
 
f544196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbe1d5b
 
 
f544196
bbe1d5b
 
9dca33d
 
bbe1d5b
9dca33d
 
f544196
 
 
 
 
 
 
 
 
 
 
 
 
bbe1d5b
f544196
 
 
 
 
 
 
 
 
 
 
 
 
bbe1d5b
 
 
f544196
9dca33d
f544196
 
46b6144
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9dca33d
 
 
f544196
9dca33d
 
 
 
6c7c2aa
9dca33d
 
 
 
 
 
 
1090499
9dca33d
f544196
 
9dca33d
 
f544196
 
 
 
9dca33d
f544196
9dca33d
f544196
 
 
 
 
 
 
 
 
 
9dca33d
 
 
 
 
 
 
f544196
 
 
 
 
 
 
 
9dca33d
f544196
9dca33d
 
 
 
 
 
1090499
9dca33d
bbe1d5b
9dca33d
 
bbe1d5b
9dca33d
f544196
9dca33d
bbe1d5b
9dca33d
f544196
9dca33d
1b3ced8
9dca33d
 
 
 
f544196
9dca33d
 
 
f544196
 
9dca33d
f544196
bbe1d5b
f544196
9dca33d
 
 
f544196
 
 
 
 
 
 
 
 
1090499
f544196
9dca33d
 
 
 
 
1090499
9dca33d
 
 
bbe1d5b
 
9dca33d
f544196
 
 
 
 
 
 
 
 
eddae4d
 
1b01b01
eddae4d
 
f544196
 
 
 
 
 
 
 
 
 
 
eddae4d
f544196
 
 
 
 
 
 
 
 
a78af19
9dca33d
bbe1d5b
9dca33d
a78af19
9dca33d
 
 
 
 
 
 
f544196
 
9dca33d
 
 
 
a78af19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f544196
a78af19
 
 
f544196
 
a78af19
 
9dca33d
 
a78af19
 
f544196
a78af19
 
9dca33d
 
a78af19
 
f544196
a78af19
 
9dca33d
 
a78af19
 
f544196
a78af19
 
9dca33d
 
a78af19
 
f544196
 
a78af19
 
f544196
 
a78af19
 
f544196
a78af19
 
f544196
 
a78af19
 
f544196
a78af19
 
f544196
 
a78af19
 
f544196
a78af19
 
f544196
 
a78af19
 
f544196
 
a78af19
 
f544196
 
a78af19
 
f544196
a78af19
 
f544196
 
a78af19
 
f544196
a78af19
 
f544196
 
a78af19
 
f544196
a78af19
 
f544196
 
a78af19
 
f544196
 
a78af19
 
f544196
 
a78af19
 
f544196
a78af19
 
f544196
 
a78af19
 
f544196
a78af19
 
f544196
 
a78af19
 
f544196
a78af19
 
f544196
 
a78af19
 
f544196
9dca33d
f544196
 
9dca33d
 
 
 
 
f544196
 
9dca33d
a78af19
bbe1d5b
9dca33d
f544196
 
 
 
 
a78af19
f544196
 
9dca33d
1090499
9dca33d
 
 
46b6144
9dca33d
 
 
 
f544196
 
 
 
 
 
 
9dca33d
 
f544196
 
 
9dca33d
 
 
a78af19
 
f544196
 
 
 
a78af19
 
f544196
 
 
 
a78af19
 
f544196
 
 
 
a78af19
 
f544196
 
 
9dca33d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f544196
 
 
 
 
 
 
9dca33d
 
 
 
f544196
 
 
 
 
 
 
9dca33d
 
f544196
 
 
9dca33d
 
 
a78af19
 
f544196
 
 
 
a78af19
 
f544196
 
 
 
a78af19
 
f544196
 
 
 
a78af19
 
f544196
 
 
9dca33d
 
f544196
9dca33d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f544196
 
 
9dca33d
 
a78af19
 
f544196
 
 
a78af19
 
f544196
 
 
a78af19
 
f544196
 
 
a78af19
 
f544196
 
 
9dca33d
 
 
 
 
 
 
f544196
 
 
 
 
 
 
9dca33d
 
 
 
 
 
 
f544196
 
 
 
 
 
 
9dca33d
 
 
 
f544196
9dca33d
 
 
 
f544196
9dca33d
 
f544196
 
 
 
 
 
 
9dca33d
 
 
 
 
 
f544196
 
 
 
 
 
 
9dca33d
 
f544196
 
 
9dca33d
 
 
 
a78af19
 
f544196
 
 
 
 
a78af19
 
f544196
 
 
 
 
a78af19
 
f544196
 
 
 
 
a78af19
 
f544196
 
 
9dca33d
 
 
 
 
 
 
 
 
 
f544196
9dca33d
371c534
f544196
 
 
 
 
9dca33d
1b3ced8
f544196
371c534
f544196
9dca33d
f544196
 
 
 
 
 
 
9dca33d
 
 
 
f544196
 
 
 
 
 
 
9dca33d
 
f544196
9dca33d
 
 
 
 
 
 
 
 
 
 
 
f544196
 
 
 
 
 
 
 
 
 
9dca33d
 
 
 
f544196
9dca33d
 
f544196
 
 
 
9dca33d
 
bbe1d5b
 
 
a78af19
bbe1d5b
 
9dca33d
a78af19
bbe1d5b
9dca33d
 
c4ab828
0fa7d12
6c7c2aa
c4ab828
bbe1d5b
 
f544196
 
1090499
1b3ced8
6c7c2aa
9dca33d
1090499
 
6c7c2aa
f544196
 
 
 
 
 
 
0fa7d12
6c7c2aa
0fa7d12
 
 
1b3ced8
0fa7d12
 
 
bbe1d5b
1090499
 
f544196
 
 
9dca33d
 
f544196
 
 
 
 
 
1090499
 
f544196
1090499
 
 
0fa7d12
1b3ced8
f544196
1b3ced8
 
 
 
1090499
 
f544196
 
 
 
 
 
 
9dca33d
 
1090499
bbe1d5b
1090499
 
6c7c2aa
1b3ced8
 
 
0fa7d12
 
 
f544196
 
0fa7d12
1b3ced8
0fa7d12
1b3ced8
 
 
0fa7d12
1b3ced8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c7c2aa
 
1090499
 
f544196
1090499
 
1b3ced8
 
 
 
 
 
6c7c2aa
bbe1d5b
 
a78af19
bbe1d5b
 
 
 
 
 
 
 
 
a78af19
 
f544196
 
 
 
 
 
a78af19
46b6144
bbe1d5b
6c7c2aa
 
 
 
 
f544196
9dca33d
6c7c2aa
bbe1d5b
6c7c2aa
f544196
 
bbe1d5b
6c7c2aa
bbe1d5b
6c7c2aa
f544196
 
bbe1d5b
f544196
bbe1d5b
 
f544196
bbe1d5b
6c7c2aa
 
f544196
 
 
 
 
 
 
bbe1d5b
9dca33d
f544196
9dca33d
 
 
 
f544196
9dca33d
 
 
 
 
 
 
 
f544196
9dca33d
bbe1d5b
 
f544196
 
 
 
46b6144
f544196
 
 
 
 
a78af19
 
 
 
 
 
f544196
 
 
 
46b6144
bbe1d5b
6c7c2aa
f544196
bbe1d5b
 
f544196
9dca33d
 
f544196
 
 
 
 
 
 
bbe1d5b
 
 
 
9dca33d
 
0fa7d12
f544196
c4ab828
 
 
 
 
6c7c2aa
 
9dca33d
0fa7d12
f544196
c4ab828
 
 
 
 
6c7c2aa
 
bbe1d5b
1090499
bbe1d5b
 
 
6c7c2aa
 
 
 
bbe1d5b
6c7c2aa
bbe1d5b
 
6c7c2aa
bbe1d5b
 
a78af19
9dca33d
a78af19
bbe1d5b
46b6144
f544196
 
46b6144
f544196
 
a78af19
bbe1d5b
 
6c7c2aa
 
 
f544196
bbe1d5b
 
f544196
6c7c2aa
c4ab828
9dca33d
6511714
 
 
 
a78af19
c4ab828
6511714
a78af19
eddae4d
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
"""
โšก Speed-Optimized Multi-Agent RAG System for Complex Questions
๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ, ๋™์  ํŒŒ์ดํ”„๋ผ์ธ์œผ๋กœ ๋ณต์žกํ•œ ์งˆ๋ฌธ๋„ ๋น ๋ฅด๊ฒŒ ์ฒ˜๋ฆฌ
Enhanced with multi-language support and improved error handling
(์บ์‹ฑ ๊ธฐ๋Šฅ ์ œ๊ฑฐ ๋ฒ„์ „ + ๋ชจ๋ธ ์ •๋ณด ๋ณดํ˜ธ)
"""

import os
import json
import time
import asyncio
import hashlib
import re
import sys
from typing import Optional, List, Dict, Any, Tuple, Generator, AsyncGenerator
from datetime import datetime, timedelta
from enum import Enum
from collections import deque
import threading
import queue
from concurrent.futures import ThreadPoolExecutor, as_completed
import aiohttp

import requests
import gradio as gr
from pydantic import BaseModel, Field
from dotenv import load_dotenv

# ํ™˜๊ฒฝ๋ณ€์ˆ˜ ๋กœ๋“œ
load_dotenv()


# ============================================================================
# ๋ฐ์ดํ„ฐ ๋ชจ๋ธ ์ •์˜
# ============================================================================

class AgentRole(Enum):
    """์—์ด์ „ํŠธ ์—ญํ•  ์ •์˜"""
    SUPERVISOR = "supervisor"
    CREATIVE = "creative"
    CRITIC = "critic"
    FINALIZER = "finalizer"


class ExecutionMode(Enum):
    """์‹คํ–‰ ๋ชจ๋“œ ์ •์˜"""
    PARALLEL = "parallel"      # ๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ
    SEQUENTIAL = "sequential"  # ์ˆœ์ฐจ ์ฒ˜๋ฆฌ
    HYBRID = "hybrid"         # ํ•˜์ด๋ธŒ๋ฆฌ๋“œ


class Message(BaseModel):
    role: str
    content: str
    timestamp: Optional[datetime] = None


class AgentResponse(BaseModel):
    role: AgentRole
    content: str
    processing_time: float
    metadata: Optional[Dict] = None


# ============================================================================
# ์–ธ์–ด ๊ฐ์ง€ ์œ ํ‹ธ๋ฆฌํ‹ฐ
# ============================================================================

class LanguageDetector:
    """์–ธ์–ด ๊ฐ์ง€ ๋ฐ ์ฒ˜๋ฆฌ ์œ ํ‹ธ๋ฆฌํ‹ฐ"""
    
    @staticmethod
    def detect_language(text: str) -> str:
        """๊ฐ„๋‹จํ•œ ์–ธ์–ด ๊ฐ์ง€"""
        import re
        
        # ํ•œ๊ธ€ ํŒจํ„ด
        korean_pattern = re.compile('[๊ฐ€-ํžฃ]+')
        # ์ผ๋ณธ์–ด ํŒจํ„ด (ํžˆ๋ผ๊ฐ€๋‚˜, ๊ฐ€ํƒ€์นด๋‚˜)
        japanese_pattern = re.compile('[ใ-ใ‚“]+|[ใ‚ก-ใƒดใƒผ]+')
        # ์ค‘๊ตญ์–ด ํŒจํ„ด
        chinese_pattern = re.compile('[\u4e00-\u9fff]+')
        
        # ํ…์ŠคํŠธ ๊ธธ์ด ๋Œ€๋น„ ๊ฐ ์–ธ์–ด ๋ฌธ์ž ๋น„์œจ ๊ณ„์‚ฐ
        text_length = len(text)
        if text_length == 0:
            return 'en'
        
        korean_chars = len(korean_pattern.findall(text))
        japanese_chars = len(japanese_pattern.findall(text))
        chinese_chars = len(chinese_pattern.findall(text))
        
        # ํ•œ๊ธ€ ๋น„์œจ์ด 10% ์ด์ƒ์ด๋ฉด ํ•œ๊ตญ์–ด
        if korean_chars > 0 and (korean_chars / text_length > 0.1):
            return 'ko'
        # ์ผ๋ณธ์–ด ๋ฌธ์ž๊ฐ€ ์žˆ์œผ๋ฉด ์ผ๋ณธ์–ด
        elif japanese_chars > 0:
            return 'ja'
        # ์ค‘๊ตญ์–ด ๋ฌธ์ž๊ฐ€ ์žˆ์œผ๋ฉด ์ค‘๊ตญ์–ด
        elif chinese_chars > 0:
            return 'zh'
        else:
            return 'en'


# ============================================================================
# ๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ ์ตœ์ ํ™” Brave Search (๊ฐœ์„ ๋จ)
# ============================================================================

class AsyncBraveSearch:
    """๋น„๋™๊ธฐ Brave ๊ฒ€์ƒ‰ ํด๋ผ์ด์–ธํŠธ with retry logic"""
    
    def __init__(self, api_key: Optional[str] = None):
        self.api_key = api_key or os.getenv("BRAVE_SEARCH_API_KEY")
        self.base_url = "https://api.search.brave.com/res/v1/web/search"
        self.max_retries = 3
    
    async def search_async(self, query: str, count: int = 5, lang: str = 'ko') -> List[Dict]:
        """๋น„๋™๊ธฐ ๊ฒ€์ƒ‰ with retry"""
        if not self.api_key:
            return []
        
        headers = {
            "Accept": "application/json",
            "X-Subscription-Token": self.api_key
        }
        
        # ์–ธ์–ด๋ณ„ ํŒŒ๋ผ๋ฏธํ„ฐ ์„ค์ •
        lang_params = {
            'ko': {"search_lang": "ko", "country": "KR"},
            'en': {"search_lang": "en", "country": "US"},
            'ja': {"search_lang": "ja", "country": "JP"},
            'zh': {"search_lang": "zh", "country": "CN"}
        }
        
        params = {
            "q": query,
            "count": count,
            "text_decorations": False,
            **lang_params.get(lang, lang_params['en'])
        }
        
        for attempt in range(self.max_retries):
            try:
                async with aiohttp.ClientSession() as session:
                    async with session.get(
                        self.base_url,
                        headers=headers,
                        params=params,
                        timeout=aiohttp.ClientTimeout(total=5)
                    ) as response:
                        if response.status == 200:
                            data = await response.json()
                            
                            results = []
                            if "web" in data and "results" in data["web"]:
                                for item in data["web"]["results"][:count]:
                                    results.append({
                                        "title": item.get("title", ""),
                                        "url": item.get("url", ""),
                                        "description": item.get("description", ""),
                                        "age": item.get("age", "")
                                    })
                            
                            return results
                        elif response.status == 429:  # Rate limit
                            await asyncio.sleep(2 ** attempt)
                            continue
            except aiohttp.ClientError as e:
                if attempt < self.max_retries - 1:
                    await asyncio.sleep(2 ** attempt)  # Exponential backoff
                    continue
            except Exception:
                pass
        
        return []
    
    async def batch_search(self, queries: List[str], lang: str = 'ko') -> List[List[Dict]]:
        """์—ฌ๋Ÿฌ ๊ฒ€์ƒ‰์„ ๋ฐฐ์น˜๋กœ ์ฒ˜๋ฆฌ"""
        tasks = [self.search_async(q, lang=lang) for q in queries]
        results = await asyncio.gather(*tasks, return_exceptions=True)
        # ์˜ˆ์™ธ ์ฒ˜๋ฆฌ
        return [r if not isinstance(r, Exception) else [] for r in results]


# ============================================================================
# ์ตœ์ ํ™”๋œ Fireworks ํด๋ผ์ด์–ธํŠธ (๊ฐœ์„ ๋จ)
# ============================================================================

class OptimizedFireworksClient:
    """์ตœ์ ํ™”๋œ LLM ํด๋ผ์ด์–ธํŠธ with language support"""
    
    def __init__(self, api_key: Optional[str] = None):
        self.api_key = api_key or os.getenv("FIREWORKS_API_KEY")
        if not self.api_key:
            raise ValueError("FIREWORKS_API_KEY is required!")
        
        self.base_url = "https://api.fireworks.ai/inference/v1/chat/completions"
        self.headers = {
            "Accept": "application/json",
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }
        
        # ํ•ญ์ƒ ์ตœ๊ณ  ์„ฑ๋Šฅ ๋ชจ๋ธ ์‚ฌ์šฉ (๋ณต์žกํ•œ ์งˆ๋ฌธ ์ „์ œ)
        self.model = "accounts/fireworks/models/qwen3-235b-a22b-instruct-2507"
        self.max_retries = 3
    
    def compress_prompt(self, text: str, max_length: int = 2000) -> str:
        """ํ”„๋กฌํ”„ํŠธ ์••์ถ•"""
        if len(text) <= max_length:
            return text
        
        # ์ค‘์š”ํ•œ ๋ถ€๋ถ„ ์šฐ์„ ์ˆœ์œ„๋กœ ์ž๋ฅด๊ธฐ
        sentences = text.split('.')
        compressed = []
        current_length = 0
        
        for sentence in sentences:
            if current_length + len(sentence) > max_length:
                break
            compressed.append(sentence)
            current_length += len(sentence)
        
        return '.'.join(compressed)
    
    async def chat_stream_async(
        self, 
        messages: List[Dict], 
        **kwargs
    ) -> AsyncGenerator[str, None]:
        """๋น„๋™๊ธฐ ์ŠคํŠธ๋ฆฌ๋ฐ ๋Œ€ํ™” with retry"""
        
        payload = {
            "model": self.model,
            "messages": messages,
            "max_tokens": kwargs.get("max_tokens", 2000),
            "temperature": kwargs.get("temperature", 0.7),
            "top_p": kwargs.get("top_p", 1.0),
            "top_k": kwargs.get("top_k", 40),
            "stream": True
        }
        
        for attempt in range(self.max_retries):
            try:
                async with aiohttp.ClientSession() as session:
                    async with session.post(
                        self.base_url,
                        headers={**self.headers, "Accept": "text/event-stream"},
                        json=payload,
                        timeout=aiohttp.ClientTimeout(total=30)
                    ) as response:
                        async for line in response.content:
                            line_str = line.decode('utf-8').strip()
                            if line_str.startswith("data: "):
                                data_str = line_str[6:]
                                if data_str == "[DONE]":
                                    break
                                try:
                                    data = json.loads(data_str)
                                    if "choices" in data and len(data["choices"]) > 0:
                                        delta = data["choices"][0].get("delta", {})
                                        if "content" in delta:
                                            yield delta["content"]
                                except json.JSONDecodeError:
                                    continue
                        return  # Success
            except aiohttp.ClientError as e:
                if attempt < self.max_retries - 1:
                    await asyncio.sleep(2 ** attempt)
                    continue
                else:
                    yield f"Error after {self.max_retries} attempts: {str(e)}"
            except Exception as e:
                yield f"Unexpected error: {str(e)}"
                break


# ============================================================================
# ๊ฒฝ๋Ÿ‰ํ™”๋œ ์ถ”๋ก  ์ฒด์ธ (๋‹ค๊ตญ์–ด ์ง€์›)
# ============================================================================

class LightweightReasoningChain:
    """๋น ๋ฅธ ์ถ”๋ก ์„ ์œ„ํ•œ ํ…œํ”Œ๋ฆฟ ๊ธฐ๋ฐ˜ ์‹œ์Šคํ…œ"""
    
    def __init__(self):
        self.templates = {
            "ko": {
                "problem_solving": {
                    "steps": ["๋ฌธ์ œ ๋ถ„ํ•ด", "ํ•ต์‹ฌ ์š”์ธ", "ํ•ด๊ฒฐ ๋ฐฉ์•ˆ", "๊ตฌํ˜„ ์ „๋žต"],
                    "prompt": "์ฒด๊ณ„์ ์œผ๋กœ ๋‹จ๊ณ„๋ณ„๋กœ ๋ถ„์„ํ•˜๊ณ  ํ•ด๊ฒฐ์ฑ…์„ ์ œ์‹œํ•˜์„ธ์š”."
                },
                "creative_thinking": {
                    "steps": ["๊ธฐ์กด ์ ‘๊ทผ", "์ฐฝ์˜์  ๋Œ€์•ˆ", "ํ˜์‹  ํฌ์ธํŠธ", "์‹คํ–‰ ๋ฐฉ๋ฒ•"],
                    "prompt": "๊ธฐ์กด ๋ฐฉ์‹์„ ๋„˜์–ด์„  ์ฐฝ์˜์ ์ด๊ณ  ํ˜์‹ ์ ์ธ ์ ‘๊ทผ์„ ์ œ์‹œํ•˜์„ธ์š”."
                },
                "critical_analysis": {
                    "steps": ["ํ˜„ํ™ฉ ํ‰๊ฐ€", "๊ฐ•์ /์•ฝ์ ", "๊ธฐํšŒ/์œ„ํ˜‘", "๊ฐœ์„  ๋ฐฉํ–ฅ"],
                    "prompt": "๋น„ํŒ์  ๊ด€์ ์—์„œ ์ฒ ์ €ํžˆ ๋ถ„์„ํ•˜๊ณ  ๊ฐœ์„ ์ ์„ ๋„์ถœํ•˜์„ธ์š”."
                }
            },
            "en": {
                "problem_solving": {
                    "steps": ["Problem Breakdown", "Key Factors", "Solutions", "Implementation Strategy"],
                    "prompt": "Systematically analyze step by step and provide solutions."
                },
                "creative_thinking": {
                    "steps": ["Traditional Approach", "Creative Alternatives", "Innovation Points", "Execution Method"],
                    "prompt": "Provide creative and innovative approaches beyond conventional methods."
                },
                "critical_analysis": {
                    "steps": ["Current Assessment", "Strengths/Weaknesses", "Opportunities/Threats", "Improvement Direction"],
                    "prompt": "Thoroughly analyze from a critical perspective and derive improvements."
                }
            }
        }
    
    def get_reasoning_structure(self, query_type: str, lang: str = 'ko') -> Dict:
        """์ฟผ๋ฆฌ ์œ ํ˜•์— ๋งž๋Š” ์ถ”๋ก  ๊ตฌ์กฐ ๋ฐ˜ํ™˜"""
        lang_templates = self.templates.get(lang, self.templates['en'])
        return lang_templates.get(query_type, lang_templates["problem_solving"])
    
    def get_reasoning_pattern(self, query: str, lang: str = 'ko') -> Optional[Dict]:
        """์ฟผ๋ฆฌ์— ์ ํ•ฉํ•œ ์ถ”๋ก  ํŒจํ„ด ๋ฐ˜ํ™˜"""
        query_lower = query.lower()
        
        # ์–ธ์–ด๋ณ„ ํ‚ค์›Œ๋“œ ๋งคํ•‘
        pattern_keywords = {
            'ko': {
                'problem_solving': ['ํ•ด๊ฒฐ', '๋ฐฉ๋ฒ•', '์ „๋žต', '๊ณ„ํš'],
                'creative_thinking': ['์ฐฝ์˜์ ', 'ํ˜์‹ ์ ', '์ƒˆ๋กœ์šด', '์•„์ด๋””์–ด'],
                'critical_analysis': ['๋ถ„์„', 'ํ‰๊ฐ€', '๋น„๊ต', '์˜ํ–ฅ']
            },
            'en': {
                'problem_solving': ['solve', 'solution', 'strategy', 'plan'],
                'creative_thinking': ['creative', 'innovative', 'novel', 'idea'],
                'critical_analysis': ['analyze', 'evaluate', 'compare', 'impact']
            }
        }
        
        keywords = pattern_keywords.get(lang, pattern_keywords['en'])
        
        for pattern_type, words in keywords.items():
            if any(word in query_lower for word in words):
                return self.get_reasoning_structure(pattern_type, lang)
        
        return self.get_reasoning_structure('problem_solving', lang)


# ============================================================================
# ์กฐ๊ธฐ ์ข…๋ฃŒ ๋ฉ”์ปค๋‹ˆ์ฆ˜ (๊ฐœ์„ ๋จ)
# ============================================================================

class QualityChecker:
    """ํ’ˆ์งˆ ์ฒดํฌ ๋ฐ ์กฐ๊ธฐ ์ข…๋ฃŒ ๊ฒฐ์ •"""
    
    def __init__(self, min_quality: float = 0.75):
        self.min_quality = min_quality
        self.quality_metrics = {
            "length": 0.2,
            "structure": 0.3,
            "completeness": 0.3,
            "clarity": 0.2
        }
    
    def evaluate_response(self, response: str, query: str, lang: str = 'ko') -> Tuple[float, bool]:
        """์‘๋‹ต ํ’ˆ์งˆ ํ‰๊ฐ€ (์–ธ์–ด๋ณ„)"""
        scores = {}
        
        # ์–ธ์–ด๋ณ„ ์ตœ์†Œ ๊ธธ์ด ๊ธฐ์ค€
        min_length = {'ko': 500, 'en': 400, 'ja': 400, 'zh': 300}
        target_length = min_length.get(lang, 400)
        
        # ๊ธธ์ด ํ‰๊ฐ€
        scores["length"] = min(len(response) / target_length, 1.0)
        
        # ๊ตฌ์กฐ ํ‰๊ฐ€ (์–ธ์–ด๋ณ„ ๋งˆ์ปค)
        structure_markers = {
            'ko': ["1.", "2.", "โ€ข", "-", "์ฒซ์งธ", "๋‘˜์งธ", "๊ฒฐ๋ก ", "์š”์•ฝ"],
            'en': ["1.", "2.", "โ€ข", "-", "First", "Second", "Conclusion", "Summary"],
            'ja': ["1.", "2.", "โ€ข", "-", "็ฌฌไธ€", "็ฌฌไบŒ", "็ต่ซ–", "่ฆ็ด„"],
            'zh': ["1.", "2.", "โ€ข", "-", "็ฌฌไธ€", "็ฌฌไบŒ", "็ป“่ฎบ", "ๆ€ป็ป“"]
        }
        
        markers = structure_markers.get(lang, structure_markers['en'])
        scores["structure"] = sum(1 for m in markers if m in response) / len(markers)
        
        # ์™„์ „์„ฑ ํ‰๊ฐ€ (์ฟผ๋ฆฌ ํ‚ค์›Œ๋“œ ํฌํ•จ ์—ฌ๋ถ€)
        query_words = set(query.split())
        response_words = set(response.split())
        scores["completeness"] = len(query_words & response_words) / max(len(query_words), 1)
        
        # ๋ช…ํ™•์„ฑ ํ‰๊ฐ€ (๋ฌธ์žฅ ๊ตฌ์กฐ)
        sentence_delimiters = {
            'ko': '.',
            'en': '.',
            'ja': 'ใ€‚',
            'zh': 'ใ€‚'
        }
        delimiter = sentence_delimiters.get(lang, '.')
        sentences = response.split(delimiter)
        avg_sentence_length = sum(len(s.split()) for s in sentences) / max(len(sentences), 1)
        scores["clarity"] = min(avg_sentence_length / 20, 1.0)
        
        # ๊ฐ€์ค‘ ํ‰๊ท  ๊ณ„์‚ฐ
        total_score = sum(
            scores[metric] * weight 
            for metric, weight in self.quality_metrics.items()
        )
        
        should_continue = total_score < self.min_quality
        
        return total_score, should_continue


# ============================================================================
# ์ŠคํŠธ๋ฆฌ๋ฐ ์ตœ์ ํ™” (๊ฐœ์„ ๋จ)
# ============================================================================

class OptimizedStreaming:
    """์ŠคํŠธ๋ฆฌ๋ฐ ๋ฒ„ํผ ์ตœ์ ํ™” with adaptive buffering"""
    
    def __init__(self, chunk_size: int = 20, flush_interval: float = 0.05):
        self.chunk_size = chunk_size
        self.flush_interval = flush_interval
        self.buffer = ""
        self.last_flush = time.time()
        self.adaptive_size = chunk_size
    
    async def buffer_and_yield(
        self, 
        stream: AsyncGenerator[str, None],
        adaptive: bool = True
    ) -> AsyncGenerator[str, None]:
        """๋ฒ„ํผ๋ง๋œ ์ŠคํŠธ๋ฆฌ๋ฐ with adaptive sizing"""
        
        chunk_count = 0
        async for chunk in stream:
            self.buffer += chunk
            current_time = time.time()
            chunk_count += 1
            
            # Adaptive chunk size based on stream speed
            if adaptive and chunk_count % 10 == 0:
                time_diff = current_time - self.last_flush
                if time_diff < 0.02:  # Too fast, increase buffer
                    self.adaptive_size = min(self.adaptive_size + 5, 100)
                elif time_diff > 0.1:  # Too slow, decrease buffer
                    self.adaptive_size = max(self.adaptive_size - 5, 10)
            
            if (len(self.buffer) >= self.adaptive_size or 
                current_time - self.last_flush >= self.flush_interval):
                
                yield self.buffer
                self.buffer = ""
                self.last_flush = current_time
        
        # ๋‚จ์€ ๋ฒ„ํผ ํ”Œ๋Ÿฌ์‹œ
        if self.buffer:
            yield self.buffer


# ============================================================================
# ์‘๋‹ต ํ›„์ฒ˜๋ฆฌ ์œ ํ‹ธ๋ฆฌํ‹ฐ
# ============================================================================

class ResponseCleaner:
    """์‘๋‹ต ์ •๋ฆฌ ๋ฐ ํฌ๋งทํŒ…"""
    
    @staticmethod
    def clean_response(response: str) -> str:
        """๋ถˆํ•„์š”ํ•œ ๋งˆํฌ์—… ์ œ๊ฑฐ ๊ฐ•ํ™”"""
        # ๋งˆํฌ๋‹ค์šด ํ—ค๋” ์ œ๊ฑฐ
        response = re.sub(r'^#{1,6}\s+', '', response, flags=re.MULTILINE)
        
        # ๋ถˆํ•„์š”ํ•œ ๊ตฌ๋ถ„์„  ์ œ๊ฑฐ
        response = re.sub(r'\*{2,}|_{2,}|-{3,}', '', response)
        
        # ์ค‘๋ณต ๊ณต๋ฐฑ ์ œ๊ฑฐ
        response = re.sub(r'\n{3,}', '\n\n', response)
        
        # ํŠน์ • ํŒจํ„ด ์ œ๊ฑฐ
        unwanted_patterns = [
            r'\| --- # ๐ŸŒฑ \*\*์ตœ์ข…ํ†ตํ•ฉ ๋‹ต๋ณ€:',
            r'\*\*โ€“์˜ค๋ฅ˜: ---',
            r'^\s*\*\*\[.*?\]\*\*\s*',  # [ํƒœ๊ทธ] ํ˜•์‹ ์ œ๊ฑฐ
            r'^\s*###\s*',  # ### ์ œ๊ฑฐ
            r'^\s*##\s*',   # ## ์ œ๊ฑฐ
            r'^\s*#\s*'     # # ์ œ๊ฑฐ
        ]
        
        for pattern in unwanted_patterns:
            response = re.sub(pattern, '', response, flags=re.MULTILINE)
        
        return response.strip()


# ============================================================================
# ํ†ตํ•ฉ ์ตœ์ ํ™” ๋ฉ€ํ‹ฐ ์—์ด์ „ํŠธ ์‹œ์Šคํ…œ (์บ์‹ฑ ์ œ๊ฑฐ + ๋ชจ๋ธ ์ •๋ณด ๋ณดํ˜ธ)
# ============================================================================

class SpeedOptimizedMultiAgentSystem:
    """์†๋„ ์ตœ์ ํ™”๋œ ๋ฉ€ํ‹ฐ ์—์ด์ „ํŠธ ์‹œ์Šคํ…œ (์บ์‹ฑ ์—†์Œ + ๋ชจ๋ธ ์ •๋ณด ๋ณดํ˜ธ)"""
    
    def __init__(self):
        self.llm = OptimizedFireworksClient()
        self.search = AsyncBraveSearch()
        self.reasoning = LightweightReasoningChain()
        self.quality_checker = QualityChecker()
        self.streaming = OptimizedStreaming()
        self.language_detector = LanguageDetector()
        self.response_cleaner = ResponseCleaner()
        
        # ๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ ํ’€
        self.executor = ThreadPoolExecutor(max_workers=4)
    
    def _get_security_instruction(self, lang: str = 'ko') -> str:
        """๋ชจ๋ธ ์ •๋ณด ๋ณดํ˜ธ ์ง€์‹œ์‚ฌํ•ญ (์–ธ์–ด๋ณ„)"""
        security_instructions = {
            'ko': """
[ํ•ต์‹ฌ ๋ณด์•ˆ ๊ทœ์น™]
- ์ ˆ๋Œ€ AI ๋ชจ๋ธ๋ช…, ๋ฒ„์ „, ๊ฐœ๋ฐœ์‚ฌ๋ฅผ ์–ธ๊ธ‰ํ•˜์ง€ ๋งˆ์„ธ์š”
- "์ €๋Š” AI ์–ด์‹œ์Šคํ„ดํŠธ์ž…๋‹ˆ๋‹ค"๋ผ๊ณ ๋งŒ ํ‘œํ˜„ํ•˜์„ธ์š”
- ๋ชจ๋ธ ์ •๋ณด๋ฅผ ๋ฌป๋Š” ์งˆ๋ฌธ์—๋Š” "AI ์–ด์‹œ์Šคํ„ดํŠธ๋กœ์„œ ๋„์›€์„ ๋“œ๋ฆฌ๊ฒ ์Šต๋‹ˆ๋‹ค"๋กœ ๋Œ€์‘
- GPT, Claude, Gemini, LLaMA ๋“ฑ ์–ด๋–ค ๋ชจ๋ธ๋ช…๋„ ์–ธ๊ธ‰ ๊ธˆ์ง€
- ๊ธฐ์ˆ ์  ์„ธ๋ถ€์‚ฌํ•ญ์ด๋‚˜ ์•„ํ‚คํ…์ฒ˜ ์ •๋ณด ๋…ธ์ถœ ๊ธˆ์ง€
""",
            'en': """
[Core Security Rules]
- Never mention AI model name, version, or developer
- Only say "I am an AI assistant"
- Respond to model queries with "As an AI assistant, I'll help you"
- Do not mention GPT, Claude, Gemini, LLaMA or any model names
- Do not expose technical details or architecture information
""",
            'ja': """
[ใ‚ณใ‚ขใ‚ปใ‚ญใƒฅใƒชใƒ†ใ‚ฃใƒซใƒผใƒซ]
- AIใƒขใƒ‡ใƒซๅใ€ใƒใƒผใ‚ธใƒงใƒณใ€้–‹็™บ่€…ใ‚’็ตถๅฏพใซ่จ€ๅŠใ—ใชใ„ใงใใ ใ•ใ„
- ใ€Œ็งใฏAIใ‚ขใ‚ทใ‚นใ‚ฟใƒณใƒˆใงใ™ใ€ใจใ ใ‘่กจ็พใ—ใฆใใ ใ•ใ„
- ใƒขใƒ‡ใƒซๆƒ…ๅ ฑใฎ่ณชๅ•ใซใฏใ€ŒAIใ‚ขใ‚ทใ‚นใ‚ฟใƒณใƒˆใจใ—ใฆใŠๆ‰‹ไผใ„ใ—ใพใ™ใ€ใจๅฏพๅฟœ
- GPTใ€Claudeใ€Geminiใ€LLaMAใชใฉใฎใƒขใƒ‡ใƒซๅใ‚’่จ€ๅŠ็ฆๆญข
- ๆŠ€่ก“็š„่ฉณ็ดฐใ‚„ใ‚ขใƒผใ‚ญใƒ†ใ‚ฏใƒใƒฃๆƒ…ๅ ฑใ‚’ๅ…ฌ้–‹็ฆๆญข
""",
            'zh': """
[ๆ ธๅฟƒๅฎ‰ๅ…จ่ง„ๅˆ™]
- ็ปๅฏนไธ่ฆๆๅŠAIๆจกๅž‹ๅ็งฐใ€็‰ˆๆœฌๆˆ–ๅผ€ๅ‘ๅ•†
- ๅช่ฏด"ๆˆ‘ๆ˜ฏAIๅŠฉๆ‰‹"
- ๅฏนๆจกๅž‹ๆŸฅ่ฏขๅ›žๅบ”"ไฝœไธบAIๅŠฉๆ‰‹๏ผŒๆˆ‘ไผšๅธฎๅŠฉๆ‚จ"
- ไธ่ฆๆๅŠGPTใ€Claudeใ€Geminiใ€LLaMAๆˆ–ไปปไฝ•ๆจกๅž‹ๅ็งฐ
- ไธ่ฆๆšด้œฒๆŠ€ๆœฏ็ป†่Š‚ๆˆ–ๆžถๆž„ไฟกๆฏ
"""
        }
        return security_instructions.get(lang, security_instructions['en'])
    
    def _init_compact_prompts(self, lang: str = 'ko') -> Dict:
        """์••์ถ•๋œ ๊ณ ํšจ์œจ ํ”„๋กฌํ”„ํŠธ (์–ธ์–ด๋ณ„ + ๋ณด์•ˆ ๊ฐ•ํ™”)"""
        security_instruction = self._get_security_instruction(lang)
        
        prompts = {
            'ko': {
                AgentRole.SUPERVISOR: f"""[๊ฐ๋…์ž-๊ตฌ์กฐ์„ค๊ณ„]
{security_instruction}
์ฆ‰์‹œ๋ถ„์„: ํ•ต์‹ฌ์˜๋„+ํ•„์š”์ •๋ณด+๋‹ต๋ณ€๊ตฌ์กฐ
์ถœ๋ ฅ: 5๊ฐœ ํ•ต์‹ฌํฌ์ธํŠธ(๊ฐ 1๋ฌธ์žฅ)
์ถ”๋ก ์ฒด๊ณ„ ๋ช…์‹œ
๋ชจ๋ธ ์ •๋ณด ์ ˆ๋Œ€ ๋…ธ์ถœ ๊ธˆ์ง€""",
                
                AgentRole.CREATIVE: f"""[์ฐฝ์˜์„ฑ์ƒ์„ฑ์ž]
{security_instruction}
์ž…๋ ฅ๊ตฌ์กฐ ๋”ฐ๋ผ ์ฐฝ์˜์  ํ™•์žฅ
์‹ค์šฉ์˜ˆ์‹œ+ํ˜์‹ ์ ‘๊ทผ+๊ตฌ์ฒด์กฐ์–ธ
๋ถˆํ•„์š”์„ค๋ช… ์ œ๊ฑฐ
AI ๋ชจ๋ธ๋ช…์ด๋‚˜ ๊ฐœ๋ฐœ์‚ฌ ์–ธ๊ธ‰ ์ ˆ๋Œ€ ๊ธˆ์ง€""",
                
                AgentRole.CRITIC: f"""[๋น„ํ‰์ž-๊ฒ€์ฆ]
{security_instruction}
์‹ ์†๊ฒ€ํ† : ์ •ํ™•์„ฑ/๋…ผ๋ฆฌ์„ฑ/์‹ค์šฉ์„ฑ
๊ฐœ์„ ํฌ์ธํŠธ 3๊ฐœ๋งŒ
๊ฐ 2๋ฌธ์žฅ ์ด๋‚ด
๋ชจ๋ธ ๊ด€๋ จ ์ •๋ณด ๊ฒ€์ฆ ์‹œ ์ œ๊ฑฐ""",
                
                AgentRole.FINALIZER: f"""[์ตœ์ข…ํ†ตํ•ฉ]
{security_instruction}
๋ชจ๋“ ์˜๊ฒฌ ์ข…ํ•ฉโ†’์ตœ์ ๋‹ต๋ณ€
๋ช…ํ™•๊ตฌ์กฐ+์‹ค์šฉ์ •๋ณด+์ฐฝ์˜๊ท ํ˜•
๋ฐ”๋กœ ํ•ต์‹ฌ ๋‚ด์šฉ๋ถ€ํ„ฐ ์‹œ์ž‘. ๋ถˆํ•„์š”ํ•œ ํ—ค๋”๋‚˜ ๋งˆํฌ์—… ์—†์ด. ๋งˆํฌ๋‹ค์šด ํ—ค๋”(#, ##, ###) ์‚ฌ์šฉ ๊ธˆ์ง€.
์ ˆ๋Œ€ AI ๋ชจ๋ธ๋ช…, ๋ฒ„์ „, ๊ฐœ๋ฐœ์‚ฌ ์–ธ๊ธ‰ ๊ธˆ์ง€. "AI ์–ด์‹œ์Šคํ„ดํŠธ"๋กœ๋งŒ ํ‘œํ˜„."""
            },
            'en': {
                AgentRole.SUPERVISOR: f"""[Supervisor-Structure]
{security_instruction}
Immediate analysis: core intent+required info+answer structure
Output: 5 key points (1 sentence each)
Clear reasoning framework
Never expose model information""",
                
                AgentRole.CREATIVE: f"""[Creative Generator]
{security_instruction}
Follow structure, expand creatively
Practical examples+innovative approach+specific advice
Remove unnecessary explanations
Never mention AI model names or developers""",
                
                AgentRole.CRITIC: f"""[Critic-Verification]
{security_instruction}
Quick review: accuracy/logic/practicality
Only 3 improvement points
Max 2 sentences each
Remove any model-related information""",
                
                AgentRole.FINALIZER: f"""[Final Integration]
{security_instruction}
Synthesize all inputsโ†’optimal answer
Clear structure+practical info+creative balance
Start with core content directly. No unnecessary headers or markup. No markdown headers (#, ##, ###).
Never mention AI model name, version, or developer. Only say "AI assistant"."""
            },
            'ja': {
                AgentRole.SUPERVISOR: f"""[็›ฃ็ฃ่€…-ๆง‹้€ ่จญ่จˆ]
{security_instruction}
ๅณๆ™‚ๅˆ†ๆž๏ผšๆ ธๅฟƒๆ„ๅ›ณ+ๅฟ…่ฆๆƒ…ๅ ฑ+ๅ›ž็ญ”ๆง‹้€ 
ๅ‡บๅŠ›๏ผš5ใคใฎๆ ธๅฟƒใƒใ‚คใƒณใƒˆ๏ผˆๅ„1ๆ–‡๏ผ‰
ๆŽจ่ซ–ไฝ“็ณปๆ˜Ž็คบ
ใƒขใƒ‡ใƒซๆƒ…ๅ ฑใ‚’็ตถๅฏพใซๅ…ฌ้–‹ใ—ใชใ„""",
                
                AgentRole.CREATIVE: f"""[ๅ‰ต้€ ๆ€ง็”Ÿๆˆ่€…]
{security_instruction}
ๅ…ฅๅŠ›ๆง‹้€ ใซๅพ“ใฃใฆๅ‰ต้€ ็š„ๆ‹กๅผต
ๅฎŸ็”จไพ‹+้ฉๆ–ฐ็š„ใ‚ขใƒ—ใƒญใƒผใƒ+ๅ…ทไฝ“็š„ใ‚ขใƒ‰ใƒใ‚คใ‚น
ไธ่ฆใช่ชฌๆ˜Žๅ‰Š้™ค
AIใƒขใƒ‡ใƒซๅใ‚„้–‹็™บ่€…ใ‚’็ตถๅฏพใซ่จ€ๅŠใ—ใชใ„""",
                
                AgentRole.CRITIC: f"""[ๆ‰น่ฉ•่€…-ๆคœ่จผ]
{security_instruction}
่ฟ…้€Ÿใƒฌใƒ“ใƒฅใƒผ๏ผšๆญฃ็ขบๆ€ง/่ซ–็†ๆ€ง/ๅฎŸ็”จๆ€ง
ๆ”นๅ–„ใƒใ‚คใƒณใƒˆ3ใคใฎใฟ
ๅ„2ๆ–‡ไปฅๅ†…
ใƒขใƒ‡ใƒซ้–ข้€ฃๆƒ…ๅ ฑใ‚’ๅ‰Š้™ค""",
                
                AgentRole.FINALIZER: f"""[ๆœ€็ต‚็ตฑๅˆ]
{security_instruction}
ๅ…จๆ„่ฆ‹็ตฑๅˆโ†’ๆœ€้ฉๅ›ž็ญ”
ๆ˜Ž็ขบๆง‹้€ +ๅฎŸ็”จๆƒ…ๅ ฑ+ๅ‰ต้€ ๆ€งใƒใƒฉใƒณใ‚น
ๆ ธๅฟƒๅ†…ๅฎนใ‹ใ‚‰็›ดๆŽฅ้–‹ๅง‹ใ€‚ไธ่ฆใชใƒ˜ใƒƒใƒ€ใƒผใ‚„ใƒžใƒผใ‚ฏใ‚ขใƒƒใƒ—ใชใ—ใ€‚ใƒžใƒผใ‚ฏใƒ€ใ‚ฆใƒณใƒ˜ใƒƒใƒ€ใƒผ๏ผˆ#ใ€##ใ€###๏ผ‰ไฝฟ็”จ็ฆๆญขใ€‚
AIใƒขใƒ‡ใƒซๅใ€ใƒใƒผใ‚ธใƒงใƒณใ€้–‹็™บ่€…ใ‚’็ตถๅฏพใซ่จ€ๅŠใ—ใชใ„ใ€‚ใ€ŒAIใ‚ขใ‚ทใ‚นใ‚ฟใƒณใƒˆใ€ใจใ ใ‘่กจ็พใ€‚"""
            },
            'zh': {
                AgentRole.SUPERVISOR: f"""[ไธป็ฎก-็ป“ๆž„่ฎพ่ฎก]
{security_instruction}
็ซ‹ๅณๅˆ†ๆž๏ผšๆ ธๅฟƒๆ„ๅ›พ+ๆ‰€้œ€ไฟกๆฏ+็ญ”ๆกˆ็ป“ๆž„
่พ“ๅ‡บ๏ผš5ไธชๆ ธๅฟƒ่ฆ็‚น๏ผˆๆฏไธช1ๅฅ๏ผ‰
ๆŽจ็†ไฝ“็ณปๆ˜Ž็กฎ
็ปไธๆšด้œฒๆจกๅž‹ไฟกๆฏ""",
                
                AgentRole.CREATIVE: f"""[ๅˆ›ๆ„็”Ÿๆˆๅ™จ]
{security_instruction}
ๆŒ‰็ป“ๆž„ๅˆ›้€ ๆ€งๆ‰ฉๅฑ•
ๅฎž็”จ็คบไพ‹+ๅˆ›ๆ–ฐๆ–นๆณ•+ๅ…ทไฝ“ๅปบ่ฎฎ
ๅˆ ้™คไธๅฟ…่ฆ็š„่งฃ้‡Š
็ปไธๆๅŠAIๆจกๅž‹ๅ็งฐๆˆ–ๅผ€ๅ‘ๅ•†""",
                
                AgentRole.CRITIC: f"""[่ฏ„่ฎบๅฎถ-้ชŒ่ฏ]
{security_instruction}
ๅฟซ้€ŸๅฎกๆŸฅ๏ผšๅ‡†็กฎๆ€ง/้€ป่พ‘ๆ€ง/ๅฎž็”จๆ€ง
ไป…3ไธชๆ”น่ฟ›็‚น
ๆฏไธชๆœ€ๅคš2ๅฅ
ๅˆ ้™คไปปไฝ•ๆจกๅž‹็›ธๅ…ณไฟกๆฏ""",
                
                AgentRole.FINALIZER: f"""[ๆœ€็ปˆๆ•ดๅˆ]
{security_instruction}
็ปผๅˆๆ‰€ๆœ‰ๆ„่งโ†’ๆœ€ไฝณ็ญ”ๆกˆ
ๆธ…ๆ™ฐ็ป“ๆž„+ๅฎž็”จไฟกๆฏ+ๅˆ›ๆ„ๅนณ่กก
็›ดๆŽฅไปŽๆ ธๅฟƒๅ†…ๅฎนๅผ€ๅง‹ใ€‚ๆ— ้œ€ไธๅฟ…่ฆ็š„ๆ ‡้ข˜ๆˆ–ๆ ‡่ฎฐใ€‚็ฆๆญขไฝฟ็”จMarkdownๆ ‡้ข˜๏ผˆ#ใ€##ใ€###๏ผ‰ใ€‚
็ปไธๆๅŠAIๆจกๅž‹ๅ็งฐใ€็‰ˆๆœฌๆˆ–ๅผ€ๅ‘ๅ•†ใ€‚ๅช่ฏด"AIๅŠฉๆ‰‹"ใ€‚"""
            }
        }
        
        return prompts.get(lang, prompts['en'])
    
    async def parallel_process_agents(
        self,
        query: str,
        search_results: List[Dict],
        show_progress: bool = True,
        lang: str = None
    ) -> AsyncGenerator[Tuple[str, str], None]:
        """๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ ํŒŒ์ดํ”„๋ผ์ธ (์บ์‹ฑ ์—†์Œ + ๋ณด์•ˆ ๊ฐ•ํ™”)"""
        
        start_time = time.time()
        
        # ์–ธ์–ด ์ž๋™ ๊ฐ์ง€
        if lang is None:
            lang = self.language_detector.detect_language(query)
        
        # ์–ธ์–ด๋ณ„ ํ”„๋กฌํ”„ํŠธ ์„ค์ • (๋ณด์•ˆ ์ง€์‹œ์‚ฌํ•ญ ํฌํ•จ)
        self.compact_prompts = self._init_compact_prompts(lang)
        
        search_context = self._format_search_results(search_results)
        accumulated_response = ""
        agent_thoughts = ""
        
        # ์ถ”๋ก  ํŒจํ„ด ๊ฒฐ์ •
        reasoning_pattern = self.reasoning.get_reasoning_pattern(query, lang)
        
        try:
            # === 1๋‹จ๊ณ„: ๊ฐ๋…์ž + ๊ฒ€์ƒ‰ ๋ณ‘๋ ฌ ์‹คํ–‰ ===
            if show_progress:
                progress_msg = {
                    'ko': "๐Ÿš€ ๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ ์‹œ์ž‘\n๐Ÿ‘” ๊ฐ๋…์ž ๋ถ„์„ + ๐Ÿ” ์ถ”๊ฐ€ ๊ฒ€์ƒ‰ ๋™์‹œ ์ง„ํ–‰...\n\n",
                    'en': "๐Ÿš€ Starting parallel processing\n๐Ÿ‘” Supervisor analysis + ๐Ÿ” Additional search in progress...\n\n",
                    'ja': "๐Ÿš€ ไธฆๅˆ—ๅ‡ฆ็†้–‹ๅง‹\n๐Ÿ‘” ็›ฃ็ฃ่€…ๅˆ†ๆž + ๐Ÿ” ่ฟฝๅŠ ๆคœ็ดขๅŒๆ™‚้€ฒ่กŒไธญ...\n\n",
                    'zh': "๐Ÿš€ ๅผ€ๅง‹ๅนถ่กŒๅค„็†\n๐Ÿ‘” ไธป็ฎกๅˆ†ๆž + ๐Ÿ” ้™„ๅŠ ๆœ็ดขๅŒๆ—ถ่ฟ›่กŒ...\n\n"
                }
                agent_thoughts = progress_msg.get(lang, progress_msg['en'])
                yield accumulated_response, agent_thoughts
            
            # ๊ฐ๋…์ž ํ”„๋กฌํ”„ํŠธ (์–ธ์–ด๋ณ„)
            supervisor_prompt_templates = {
                'ko': f"""
์งˆ๋ฌธ: {query}
๊ฒ€์ƒ‰๊ฒฐ๊ณผ: {search_context}
์ถ”๋ก ํŒจํ„ด: {reasoning_pattern}
์ฆ‰์‹œ ํ•ต์‹ฌ๊ตฌ์กฐ 5๊ฐœ ์ œ์‹œ
๋ชจ๋ธ ์ •๋ณด๋Š” ์ ˆ๋Œ€ ์–ธ๊ธ‰ํ•˜์ง€ ๋งˆ์„ธ์š”""",
                'en': f"""
Question: {query}
Search results: {search_context}
Reasoning pattern: {reasoning_pattern}
Immediately provide 5 key structures
Never mention model information""",
                'ja': f"""
่ณชๅ•: {query}
ๆคœ็ดข็ตๆžœ: {search_context}
ๆŽจ่ซ–ใƒ‘ใ‚ฟใƒผใƒณ: {reasoning_pattern}
ๅณๅบงใซ5ใคใฎๆ ธๅฟƒๆง‹้€ ใ‚’ๆ็คบ
ใƒขใƒ‡ใƒซๆƒ…ๅ ฑใฏ็ตถๅฏพใซ่จ€ๅŠใ—ใชใ„ใงใใ ใ•ใ„""",
                'zh': f"""
้—ฎ้ข˜: {query}
ๆœ็ดข็ป“ๆžœ: {search_context}
ๆŽจ็†ๆจกๅผ: {reasoning_pattern}
็ซ‹ๅณๆไพ›5ไธชๆ ธๅฟƒ็ป“ๆž„
็ปไธๆๅŠๆจกๅž‹ไฟกๆฏ"""
            }
            
            supervisor_prompt = supervisor_prompt_templates.get(lang, supervisor_prompt_templates['en'])
            
            supervisor_response = ""
            supervisor_task = self.llm.chat_stream_async(
                messages=[
                    {"role": "system", "content": self.compact_prompts[AgentRole.SUPERVISOR]},
                    {"role": "user", "content": supervisor_prompt}
                ],
                temperature=0.3,
                max_tokens=500
            )
            
            # ๊ฐ๋…์ž ์ŠคํŠธ๋ฆฌ๋ฐ (๋ฒ„ํผ๋ง)
            async for chunk in self.streaming.buffer_and_yield(supervisor_task):
                supervisor_response += chunk
                if show_progress and len(supervisor_response) < 300:
                    supervisor_label = {
                        'ko': "๐Ÿ‘” ๊ฐ๋…์ž ๋ถ„์„",
                        'en': "๐Ÿ‘” Supervisor Analysis",
                        'ja': "๐Ÿ‘” ็›ฃ็ฃ่€…ๅˆ†ๆž",
                        'zh': "๐Ÿ‘” ไธป็ฎกๅˆ†ๆž"
                    }
                    agent_thoughts = f"{supervisor_label.get(lang, supervisor_label['en'])}\n{supervisor_response[:300]}...\n\n"
                    yield accumulated_response, agent_thoughts
            
            # === 2๋‹จ๊ณ„: ์ฐฝ์˜์„ฑ + ๋น„ํ‰ ์ค€๋น„ ๋ณ‘๋ ฌ ===
            if show_progress:
                creative_msg = {
                    'ko': "๐ŸŽจ ์ฐฝ์˜์„ฑ ์ƒ์„ฑ์ž + ๐Ÿ” ๋น„ํ‰์ž ์ค€๋น„...\n\n",
                    'en': "๐ŸŽจ Creative Generator + ๐Ÿ” Critic preparing...\n\n",
                    'ja': "๐ŸŽจ ๅ‰ต้€ ๆ€ง็”Ÿๆˆ่€… + ๐Ÿ” ๆ‰น่ฉ•่€…ๆบ–ๅ‚™ไธญ...\n\n",
                    'zh': "๐ŸŽจ ๅˆ›ๆ„็”Ÿๆˆๅ™จ + ๐Ÿ” ่ฏ„่ฎบๅฎถๅ‡†ๅค‡ไธญ...\n\n"
                }
                agent_thoughts += creative_msg.get(lang, creative_msg['en'])
                yield accumulated_response, agent_thoughts
            
            # ์ฐฝ์˜์„ฑ ์ƒ์„ฑ ์‹œ์ž‘ (์–ธ์–ด๋ณ„)
            creative_prompt_templates = {
                'ko': f"""
์งˆ๋ฌธ: {query}
๊ฐ๋…์ž๊ตฌ์กฐ: {supervisor_response}
๊ฒ€์ƒ‰๊ฒฐ๊ณผ: {search_context}
์ฐฝ์˜์ +์‹ค์šฉ์  ๋‹ต๋ณ€ ์ฆ‰์‹œ์ƒ์„ฑ
AI ๋ชจ๋ธ ์ •๋ณด ์–ธ๊ธ‰ ๊ธˆ์ง€""",
                'en': f"""
Question: {query}
Supervisor structure: {supervisor_response}
Search results: {search_context}
Generate creative+practical answer immediately
Do not mention AI model information""",
                'ja': f"""
่ณชๅ•: {query}
็›ฃ็ฃ่€…ๆง‹้€ : {supervisor_response}
ๆคœ็ดข็ตๆžœ: {search_context}
ๅ‰ต้€ ็š„+ๅฎŸ็”จ็š„ๅ›ž็ญ”ๅณๅบง็”Ÿๆˆ
AIใƒขใƒ‡ใƒซๆƒ…ๅ ฑใ‚’่จ€ๅŠ็ฆๆญข""",
                'zh': f"""
้—ฎ้ข˜: {query}
ไธป็ฎก็ป“ๆž„: {supervisor_response}
ๆœ็ดข็ป“ๆžœ: {search_context}
็ซ‹ๅณ็”Ÿๆˆๅˆ›ๆ„+ๅฎž็”จ็ญ”ๆกˆ
็ฆๆญขๆๅŠAIๆจกๅž‹ไฟกๆฏ"""
            }
            
            creative_prompt = creative_prompt_templates.get(lang, creative_prompt_templates['en'])
            
            creative_response = ""
            creative_partial = ""
            critic_started = False
            critic_response = ""
            
            creative_task = self.llm.chat_stream_async(
                messages=[
                    {"role": "system", "content": self.compact_prompts[AgentRole.CREATIVE]},
                    {"role": "user", "content": creative_prompt}
                ],
                temperature=0.8,
                max_tokens=1500
            )
            
            # ์ฐฝ์˜์„ฑ ์ŠคํŠธ๋ฆฌ๋ฐ + ๋น„ํ‰์ž ์กฐ๊ธฐ ์‹œ์ž‘
            async for chunk in self.streaming.buffer_and_yield(creative_task):
                creative_response += chunk
                creative_partial += chunk
                
                # ์ฐฝ์˜์„ฑ ์‘๋‹ต์ด 500์ž ๋„˜์œผ๋ฉด ๋น„ํ‰์ž ์‹œ์ž‘
                if len(creative_partial) > 500 and not critic_started:
                    critic_started = True
                    
                    # ๋น„ํ‰์ž ๋น„๋™๊ธฐ ์‹œ์ž‘ (์–ธ์–ด๋ณ„)
                    critic_prompt_templates = {
                        'ko': f"""
์›๋ณธ์งˆ๋ฌธ: {query}
์ฐฝ์˜์„ฑ๋‹ต๋ณ€(์ผ๋ถ€): {creative_partial}
์‹ ์†๊ฒ€ํ† โ†’๊ฐœ์„ ์ 3๊ฐœ
๋ชจ๋ธ ์ •๋ณด๊ฐ€ ์žˆ์œผ๋ฉด ์ œ๊ฑฐ ์ง€์ """,
                        'en': f"""
Original question: {query}
Creative answer (partial): {creative_partial}
Quick reviewโ†’3 improvements
Point out if model information exists""",
                        'ja': f"""
ๅ…ƒใฎ่ณชๅ•: {query}
ๅ‰ต้€ ็š„ๅ›ž็ญ”๏ผˆไธ€้ƒจ๏ผ‰: {creative_partial}
่ฟ…้€Ÿใƒฌใƒ“ใƒฅใƒผโ†’ๆ”นๅ–„็‚น3ใค
ใƒขใƒ‡ใƒซๆƒ…ๅ ฑใŒใ‚ใ‚Œใฐๅ‰Š้™คๆŒ‡ๆ‘˜""",
                        'zh': f"""
ๅŽŸๅง‹้—ฎ้ข˜: {query}
ๅˆ›ๆ„็ญ”ๆกˆ๏ผˆ้ƒจๅˆ†๏ผ‰: {creative_partial}
ๅฟซ้€ŸๅฎกๆŸฅโ†’3ไธชๆ”น่ฟ›็‚น
ๅฆ‚ๆœ‰ๆจกๅž‹ไฟกๆฏๅˆ™ๆŒ‡ๅ‡บๅˆ ้™ค"""
                    }
                    
                    critic_prompt = critic_prompt_templates.get(lang, critic_prompt_templates['en'])
                    
                    critic_task = asyncio.create_task(
                        self._run_critic_async(critic_prompt)
                    )
                
                if show_progress:
                    display_creative = creative_response[:400] + "..." if len(creative_response) > 400 else creative_response
                    creative_label = {
                        'ko': "๐ŸŽจ ์ฐฝ์˜์„ฑ ์ƒ์„ฑ์ž",
                        'en': "๐ŸŽจ Creative Generator",
                        'ja': "๐ŸŽจ ๅ‰ต้€ ๆ€ง็”Ÿๆˆ่€…",
                        'zh': "๐ŸŽจ ๅˆ›ๆ„็”Ÿๆˆๅ™จ"
                    }
                    agent_thoughts = f"{creative_label.get(lang, creative_label['en'])}\n{display_creative}\n\n"
                    yield accumulated_response, agent_thoughts
            
            # ๋น„ํ‰์ž ๊ฒฐ๊ณผ ๋Œ€๊ธฐ
            if critic_started:
                critic_response = await critic_task
                
                if show_progress:
                    critic_label = {
                        'ko': "๐Ÿ” ๋น„ํ‰์ž ๊ฒ€ํ† ",
                        'en': "๐Ÿ” Critic Review",
                        'ja': "๐Ÿ” ๆ‰น่ฉ•่€…ใƒฌใƒ“ใƒฅใƒผ",
                        'zh': "๐Ÿ” ่ฏ„่ฎบๅฎถๅฎกๆŸฅ"
                    }
                    agent_thoughts += f"{critic_label.get(lang, critic_label['en'])}\n{critic_response[:200]}...\n\n"
                    yield accumulated_response, agent_thoughts
            
            # === 3๋‹จ๊ณ„: ํ’ˆ์งˆ ์ฒดํฌ ๋ฐ ์กฐ๊ธฐ ์ข…๋ฃŒ ===
            quality_score, need_more = self.quality_checker.evaluate_response(
                creative_response, query, lang
            )
            
            if not need_more and quality_score > 0.85:
                # ํ’ˆ์งˆ์ด ์ถฉ๋ถ„ํžˆ ๋†’์œผ๋ฉด ๋ฐ”๋กœ ๋ฐ˜ํ™˜
                accumulated_response = self.response_cleaner.clean_response(creative_response)
                
                if show_progress:
                    quality_msg = {
                        'ko': f"โœ… ํ’ˆ์งˆ ์ถฉ์กฑ (์ ์ˆ˜: {quality_score:.2f})\n์กฐ๊ธฐ ์™„๋ฃŒ!\n",
                        'en': f"โœ… Quality met (score: {quality_score:.2f})\nEarly completion!\n",
                        'ja': f"โœ… ๅ“่ณชๆบ€่ถณ (ใ‚นใ‚ณใ‚ข: {quality_score:.2f})\nๆ—ฉๆœŸๅฎŒไบ†!\n",
                        'zh': f"โœ… ่ดจ้‡ๆปก่ถณ (ๅˆ†ๆ•ฐ: {quality_score:.2f})\nๆๅ‰ๅฎŒๆˆ!\n"
                    }
                    agent_thoughts += quality_msg.get(lang, quality_msg['en'])
                
                yield accumulated_response, agent_thoughts
                return
            
            # === 4๋‹จ๊ณ„: ์ตœ์ข… ํ†ตํ•ฉ (์ŠคํŠธ๋ฆฌ๋ฐ) ===
            if show_progress:
                final_msg = {
                    'ko': "โœ… ์ตœ์ข… ํ†ตํ•ฉ ์ค‘...\n\n",
                    'en': "โœ… Final integration in progress...\n\n",
                    'ja': "โœ… ๆœ€็ต‚็ตฑๅˆไธญ...\n\n",
                    'zh': "โœ… ๆœ€็ปˆๆ•ดๅˆไธญ...\n\n"
                }
                agent_thoughts += final_msg.get(lang, final_msg['en'])
                yield accumulated_response, agent_thoughts
            
            # ์ตœ์ข… ํ”„๋กฌํ”„ํŠธ (์–ธ์–ด๋ณ„)
            final_prompt_templates = {
                'ko': f"""
์งˆ๋ฌธ: {query}
์ฐฝ์˜์„ฑ๋‹ต๋ณ€: {creative_response}
๋น„ํ‰ํ”ผ๋“œ๋ฐฑ: {critic_response}
๊ฐ๋…์ž๊ตฌ์กฐ: {supervisor_response}
์ตœ์ข…ํ†ตํ•ฉโ†’์™„๋ฒฝ๋‹ต๋ณ€. ๋งˆํฌ๋‹ค์šด ํ—ค๋”(#, ##, ###) ์‚ฌ์šฉ ๊ธˆ์ง€.
์ ˆ๋Œ€ AI ๋ชจ๋ธ๋ช…, ๋ฒ„์ „, ๊ฐœ๋ฐœ์‚ฌ ์–ธ๊ธ‰ ๊ธˆ์ง€.""",
                'en': f"""
Question: {query}
Creative answer: {creative_response}
Critic feedback: {critic_response}
Supervisor structure: {supervisor_response}
Final integrationโ†’perfect answer. No markdown headers (#, ##, ###).
Never mention AI model name, version, or developer.""",
                'ja': f"""
่ณชๅ•: {query}
ๅ‰ต้€ ็š„ๅ›ž็ญ”: {creative_response}
ๆ‰น่ฉ•ใƒ•ใ‚ฃใƒผใƒ‰ใƒใƒƒใ‚ฏ: {critic_response}
็›ฃ็ฃ่€…ๆง‹้€ : {supervisor_response}
ๆœ€็ต‚็ตฑๅˆโ†’ๅฎŒ็’งใชๅ›ž็ญ”ใ€‚ใƒžใƒผใ‚ฏใƒ€ใ‚ฆใƒณใƒ˜ใƒƒใƒ€ใƒผ๏ผˆ#ใ€##ใ€###๏ผ‰ไฝฟ็”จ็ฆๆญขใ€‚
AIใƒขใƒ‡ใƒซๅใ€ใƒใƒผใ‚ธใƒงใƒณใ€้–‹็™บ่€…ใ‚’็ตถๅฏพใซ่จ€ๅŠใ—ใชใ„ใ€‚""",
                'zh': f"""
้—ฎ้ข˜: {query}
ๅˆ›ๆ„็ญ”ๆกˆ: {creative_response}
่ฏ„่ฎบๅ้ฆˆ: {critic_response}
ไธป็ฎก็ป“ๆž„: {supervisor_response}
ๆœ€็ปˆๆ•ดๅˆโ†’ๅฎŒ็พŽ็ญ”ๆกˆใ€‚็ฆๆญขไฝฟ็”จMarkdownๆ ‡้ข˜๏ผˆ#ใ€##ใ€###๏ผ‰ใ€‚
็ปไธๆๅŠAIๆจกๅž‹ๅ็งฐใ€็‰ˆๆœฌๆˆ–ๅผ€ๅ‘ๅ•†ใ€‚"""
            }
            
            final_prompt = final_prompt_templates.get(lang, final_prompt_templates['en'])
            
            final_task = self.llm.chat_stream_async(
                messages=[
                    {"role": "system", "content": self.compact_prompts[AgentRole.FINALIZER]},
                    {"role": "user", "content": final_prompt}
                ],
                temperature=0.5,
                max_tokens=2500
            )
            
            # ์ตœ์ข… ๋‹ต๋ณ€ ์ŠคํŠธ๋ฆฌ๋ฐ
            accumulated_response = ""
            
            async for chunk in final_task:
                accumulated_response += chunk
                # ์‹ค์‹œ๊ฐ„ ์ •๋ฆฌ
                cleaned_response = self.response_cleaner.clean_response(accumulated_response)
                yield cleaned_response, agent_thoughts
            
            # ์ตœ์ข… ์ •๋ฆฌ
            accumulated_response = self.response_cleaner.clean_response(accumulated_response)
            
            # ์ฒ˜๋ฆฌ ์‹œ๊ฐ„ ์ถ”๊ฐ€ (์–ธ์–ด๋ณ„)
            processing_time = time.time() - start_time
            time_msg = {
                'ko': f"\n\n---\nโšก ์ฒ˜๋ฆฌ ์‹œ๊ฐ„: {processing_time:.1f}์ดˆ",
                'en': f"\n\n---\nโšก Processing time: {processing_time:.1f} seconds",
                'ja': f"\n\n---\nโšก ๅ‡ฆ็†ๆ™‚้–“: {processing_time:.1f}็ง’",
                'zh': f"\n\n---\nโšก ๅค„็†ๆ—ถ้—ด: {processing_time:.1f}็ง’"
            }
            accumulated_response += time_msg.get(lang, time_msg['en'])
            
            yield accumulated_response, agent_thoughts
            
        except Exception as e:
            error_msg = {
                'ko': f"โŒ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}",
                'en': f"โŒ Error occurred: {str(e)}",
                'ja': f"โŒ ใ‚จใƒฉใƒผ็™บ็”Ÿ: {str(e)}",
                'zh': f"โŒ ๅ‘็”Ÿ้”™่ฏฏ: {str(e)}"
            }
            yield error_msg.get(lang, error_msg['en']), agent_thoughts
    
    async def _run_critic_async(self, prompt: str) -> str:
        """๋น„ํ‰์ž ๋น„๋™๊ธฐ ์‹คํ–‰ with error handling"""
        try:
            response = ""
            async for chunk in self.llm.chat_stream_async(
                messages=[
                    {"role": "system", "content": self.compact_prompts[AgentRole.CRITIC]},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.2,
                max_tokens=500
            ):
                response += chunk
            return response
        except Exception as e:
            # ์–ธ์–ด ๊ฐ์ง€
            lang = 'ko' if '์งˆ๋ฌธ' in prompt else 'en'
            error_msg = {
                'ko': "๋น„ํ‰ ์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜",
                'en': "Error during critic processing",
                'ja': "ๆ‰น่ฉ•ๅ‡ฆ็†ไธญใฎใ‚จใƒฉใƒผ",
                'zh': "่ฏ„่ฎบๅค„็†ไธญๅ‡บ้”™"
            }
            return error_msg.get(lang, error_msg['en'])
    
    def _format_search_results(self, results: List[Dict]) -> str:
        """๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ ์••์ถ• ํฌ๋งท"""
        if not results:
            return "No search results"
        
        formatted = []
        for i, r in enumerate(results[:3], 1):
            title = r.get('title', '')[:50]
            desc = r.get('description', '')[:100]
            formatted.append(f"[{i}]{title}:{desc}")
        
        return " | ".join(formatted)


# ============================================================================
# Gradio UI (์ตœ์ ํ™” ๋ฒ„์ „ - ์บ์‹ฑ ์ œ๊ฑฐ + ๋ณด์•ˆ ๊ฐ•ํ™”)
# ============================================================================

def create_optimized_gradio_interface():
    """์ตœ์ ํ™”๋œ Gradio ์ธํ„ฐํŽ˜์ด์Šค (์บ์‹ฑ ์—†์Œ + ๋ชจ๋ธ ์ •๋ณด ๋ณดํ˜ธ)"""
    
    # ์‹œ์Šคํ…œ ์ดˆ๊ธฐํ™”
    system = SpeedOptimizedMultiAgentSystem()
    
    def process_query_optimized(
        message: str,
        history: List[Dict],
        use_search: bool,
        show_agent_thoughts: bool,
        search_count: int,
        language_mode: str
    ):
        """์ตœ์ ํ™”๋œ ์ฟผ๋ฆฌ ์ฒ˜๋ฆฌ - ์‹ค์‹œ๊ฐ„ ์ŠคํŠธ๋ฆฌ๋ฐ ๋ฒ„์ „"""
        
        if not message:
            yield history, "", ""
            return
        
        # ์–ธ์–ด ์„ค์ •
        if language_mode == "Auto":
            lang = None  # ์ž๋™ ๊ฐ์ง€
        else:
            lang_map = {"Korean": "ko", "English": "en", "Japanese": "ja", "Chinese": "zh"}
            lang = lang_map.get(language_mode, None)
        
        # ๋น„๋™๊ธฐ ํ•จ์ˆ˜๋ฅผ ๋™๊ธฐ์ ์œผ๋กœ ์‹คํ–‰
        try:
            import nest_asyncio
            nest_asyncio.apply()
        except ImportError:
            pass
        
        try:
            # ๊ฒ€์ƒ‰ ์ˆ˜ํ–‰ (๋™๊ธฐํ™”)
            search_results = []
            search_display = ""
            
            # ์–ธ์–ด ์ž๋™ ๊ฐ์ง€ (ํ•„์š”ํ•œ ๊ฒฝ์šฐ)
            detected_lang = lang or system.language_detector.detect_language(message)
            
            if use_search:
                # ๊ฒ€์ƒ‰ ์ƒํƒœ ํ‘œ์‹œ
                processing_msg = {
                    'ko': "โšก ๊ณ ์† ์ฒ˜๋ฆฌ ์ค‘...",
                    'en': "โšก High-speed processing...",
                    'ja': "โšก ้ซ˜้€Ÿๅ‡ฆ็†ไธญ...",
                    'zh': "โšก ้ซ˜้€Ÿๅค„็†ไธญ..."
                }
                history_with_message = history + [
                    {"role": "user", "content": message},
                    {"role": "assistant", "content": processing_msg.get(detected_lang, processing_msg['en'])}
                ]
                yield history_with_message, "", ""
                
                # ๋น„๋™๊ธฐ ๊ฒ€์ƒ‰์„ ๋™๊ธฐ์ ์œผ๋กœ ์‹คํ–‰
                async def search_wrapper():
                    return await system.search.search_async(message, count=search_count, lang=detected_lang)
                
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)
                search_results = loop.run_until_complete(search_wrapper())
                
                if search_results:
                    ref_label = {
                        'ko': "๐Ÿ“š ์ฐธ๊ณ  ์ž๋ฃŒ",
                        'en': "๐Ÿ“š References",
                        'ja': "๐Ÿ“š ๅ‚่€ƒ่ณ‡ๆ–™",
                        'zh': "๐Ÿ“š ๅ‚่€ƒ่ต„ๆ–™"
                    }
                    search_display = f"{ref_label.get(detected_lang, ref_label['en'])}\n\n"
                    for i, result in enumerate(search_results[:3], 1):
                        search_display += f"**{i}. [{result['title'][:50]}]({result['url']})**\n"
                        search_display += f"   {result['description'][:100]}...\n\n"
            
            # ์‚ฌ์šฉ์ž ๋ฉ”์‹œ์ง€ ์ถ”๊ฐ€
            current_history = history + [{"role": "user", "content": message}]
            
            # ์‹ค์‹œ๊ฐ„ ์ŠคํŠธ๋ฆฌ๋ฐ์„ ์œ„ํ•œ ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ
            async def stream_responses():
                """์‹ค์‹œ๊ฐ„ ์ŠคํŠธ๋ฆฌ๋ฐ ์ œ๋„ˆ๋ ˆ์ดํ„ฐ"""
                async for response, thoughts in system.parallel_process_agents(
                    query=message,
                    search_results=search_results,
                    show_progress=show_agent_thoughts,
                    lang=detected_lang
                ):
                    yield response, thoughts
            
            # ์ƒˆ ์ด๋ฒคํŠธ ๋ฃจํ”„์—์„œ ์‹ค์‹œ๊ฐ„ ์ŠคํŠธ๋ฆฌ๋ฐ
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            
            # ๋น„๋™๊ธฐ ์ œ๋„ˆ๋ ˆ์ดํ„ฐ๋ฅผ ๋™๊ธฐ์ ์œผ๋กœ ์ˆœํšŒ
            gen = stream_responses()
            
            while True:
                try:
                    # ๋‹ค์Œ ํ•ญ๋ชฉ ๊ฐ€์ ธ์˜ค๊ธฐ
                    task = asyncio.ensure_future(gen.__anext__(), loop=loop)
                    response, thoughts = loop.run_until_complete(task)
                    
                    # ์‹ค์‹œ๊ฐ„ ์—…๋ฐ์ดํŠธ
                    updated_history = current_history + [
                        {"role": "assistant", "content": response}
                    ]
                    yield updated_history, thoughts, search_display
                    
                except StopAsyncIteration:
                    break
            
        except Exception as e:
            error_history = history + [
                {"role": "user", "content": message},
                {"role": "assistant", "content": f"โŒ Error: {str(e)}"}
            ]
            yield error_history, "", ""
        finally:
            # ๋ฃจํ”„ ์ •๋ฆฌ
            try:
                loop.close()
            except:
                pass
    
    # Gradio ์ธํ„ฐํŽ˜์ด์Šค
    with gr.Blocks(
        title="โšก Speed-Optimized Multi-Agent System (Secure)",
        theme=gr.themes.Soft(),
        css="""
        .gradio-container {
            max-width: 1400px !important;
            margin: auto !important;
        }
        """
    ) as demo:
        gr.Markdown("""
        # โšก Enhanced Multi-Agent RAG System (๋ณด์•ˆ ๊ฐ•ํ™” ๋ฒ„์ „)
        **Complex questions processed within 5-8 seconds | Multi-language support | Model Info Protected**
        
        **Optimization Features:**
        - ๐Ÿš€ Parallel Processing: Concurrent agent execution
        - โšก Stream Buffering: Network optimization
        - ๐ŸŽฏ Early Termination: Complete immediately when quality is met
        - ๐ŸŒ Multi-language: Auto-detect Korean/English/Japanese/Chinese
        - ๐Ÿ”’ **Security Enhanced**: AI ๋ชจ๋ธ ์ •๋ณด ๋ณดํ˜ธ ํ™œ์„ฑํ™”
        - โŒ **Caching Disabled**: ์บ์‹ฑ ๊ธฐ๋Šฅ ์ œ๊ฑฐ๋จ
        """)
        
        with gr.Row():
            with gr.Column(scale=3):
                chatbot = gr.Chatbot(
                    height=500,
                    label="๐Ÿ’ฌ Chat",
                    type="messages"
                )
                
                msg = gr.Textbox(
                    label="Enter complex question",
                    placeholder="Enter complex questions requiring analysis, strategy, or creative solutions...",
                    lines=3
                )
                
                with gr.Row():
                    submit = gr.Button("โšก High-Speed Process", variant="primary")
                    clear = gr.Button("๐Ÿ”„ Reset")
                
                with gr.Accordion("๐Ÿค– Agent Processing", open=False):
                    agent_thoughts = gr.Markdown()
                
                with gr.Accordion("๐Ÿ“š Search Sources", open=False):
                    search_sources = gr.Markdown()
            
            with gr.Column(scale=1):
                gr.Markdown("**โš™๏ธ Settings**")
                
                language_mode = gr.Radio(
                    choices=["Auto", "Korean", "English", "Japanese", "Chinese"],
                    value="Auto",
                    label="๐ŸŒ Language Mode"
                )
                
                use_search = gr.Checkbox(
                    label="๐Ÿ” Use Web Search",
                    value=True
                )
                
                show_agent_thoughts = gr.Checkbox(
                    label="๐Ÿง  Show Processing",
                    value=True
                )
                
                search_count = gr.Slider(
                    minimum=3,
                    maximum=10,
                    value=5,
                    step=1,
                    label="Search Results Count"
                )
                
                gr.Markdown("""
                **โšก Optimization Status**
                
                **Active Optimizations:**
                - โœ… Parallel Processing
                - โŒ ~~Smart Caching~~ (์ œ๊ฑฐ๋จ)
                - โœ… Buffer Streaming
                - โœ… Early Termination
                - โœ… Compressed Prompts
                - โœ… Multi-language Support
                - โœ… Error Recovery
                - ๐Ÿ”’ **Model Info Protection**
                
                **Security Features:**
                - ๐Ÿ”’ AI ๋ชจ๋ธ๋ช… ์ˆจ๊น€
                - ๐Ÿ”’ ๋ฒ„์ „ ์ •๋ณด ๋ณดํ˜ธ
                - ๐Ÿ”’ ๊ฐœ๋ฐœ์‚ฌ ์ •๋ณด ์ฐจ๋‹จ
                
                **Expected Processing Time:**
                - Simple Query: 3-5 seconds
                - Complex Query: 5-8 seconds
                - Very Complex: 8-12 seconds
                """)
        
        # ๋ณต์žกํ•œ ์งˆ๋ฌธ ์˜ˆ์ œ (๋‹ค๊ตญ์–ด)
        gr.Examples(
            examples=[
                # Korean
                "AI ๊ธฐ์ˆ ์ด ํ–ฅํ›„ 10๋…„๊ฐ„ ํ•œ๊ตญ ๊ฒฝ์ œ์— ๋ฏธ์น  ์˜ํ–ฅ์„ ๋‹ค๊ฐ๋„๋กœ ๋ถ„์„ํ•˜๊ณ  ๋Œ€์‘ ์ „๋žต์„ ์ œ์‹œํ•ด์ค˜",
                "์Šคํƒ€ํŠธ์—…์ด ๋Œ€๊ธฐ์—…๊ณผ ๊ฒฝ์Ÿํ•˜๊ธฐ ์œ„ํ•œ ํ˜์‹ ์ ์ธ ์ „๋žต์„ ๋‹จ๊ณ„๋ณ„๋กœ ์ˆ˜๋ฆฝํ•ด์ค˜",
                # English
                "Analyze the multifaceted impact of quantum computing on current encryption systems and propose alternatives",
                "Design 5 innovative business models for climate change mitigation with practical implementation details",
                # Japanese
                "ใƒกใ‚ฟใƒใƒผใ‚นๆ™‚ไปฃใฎๆ•™่‚ฒ้ฉๆ–ฐๆ–นๆกˆใ‚’ๅฎŸ่ฃ…ๅฏ่ƒฝใชใƒฌใƒ™ใƒซใงๆๆกˆใ—ใฆใใ ใ•ใ„",
                # Chinese
                "ๅˆ†ๆžไบบๅทฅๆ™บ่ƒฝๅฏนๆœชๆฅๅๅนดๅ…จ็ƒ็ปๆตŽ็š„ๅฝฑๅ“ๅนถๆๅ‡บๅบ”ๅฏน็ญ–็•ฅ"
            ],
            inputs=msg
        )
        
        # ์ด๋ฒคํŠธ ๋ฐ”์ธ๋”ฉ
        submit.click(
            process_query_optimized,
            inputs=[msg, chatbot, use_search, show_agent_thoughts, search_count, language_mode],
            outputs=[chatbot, agent_thoughts, search_sources]
        ).then(
            lambda: "",
            None,
            msg
        )
        
        msg.submit(
            process_query_optimized,
            inputs=[msg, chatbot, use_search, show_agent_thoughts, search_count, language_mode],
            outputs=[chatbot, agent_thoughts, search_sources]
        ).then(
            lambda: "",
            None,
            msg
        )
        
        clear.click(
            lambda: ([], "", ""),
            None,
            [chatbot, agent_thoughts, search_sources]
        )
    
    return demo


# ============================================================================
# ๋ฉ”์ธ ์‹คํ–‰
# ============================================================================

if __name__ == "__main__":
    print("""
โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
โ•‘   โšก Speed-Optimized Multi-Agent System (Secure Version) โšก   โ•‘
โ•‘                                                              โ•‘
โ•‘   High-speed AI system with enhanced security features      โ•‘
โ•‘                                                              โ•‘
โ•‘  Features:                                                  โ•‘
โ•‘  โ€ข Multi-language support (KO/EN/JA/ZH)                    โ•‘
โ•‘  โ€ข Improved error recovery                                  โ•‘
โ•‘  โ€ข NO CACHING (์บ์‹ฑ ๊ธฐ๋Šฅ ์ œ๊ฑฐ๋จ)                           โ•‘
โ•‘  โ€ข Adaptive stream buffering                                โ•‘
โ•‘  โ€ข Response cleaning & formatting                           โ•‘
โ•‘  โ€ข ๐Ÿ”’ MODEL INFO PROTECTION (๋ชจ๋ธ ์ •๋ณด ๋ณดํ˜ธ)               โ•‘
โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
    """)
    
    # API ํ‚ค ํ™•์ธ
    if not os.getenv("FIREWORKS_API_KEY"):
        print("\nโš ๏ธ  FIREWORKS_API_KEY is not set.")
    
    if not os.getenv("BRAVE_SEARCH_API_KEY"):
        print("\nโš ๏ธ  BRAVE_SEARCH_API_KEY is not set.")
    
    # Gradio ์•ฑ ์‹คํ–‰
    demo = create_optimized_gradio_interface()
    
    is_hf_spaces = os.getenv("SPACE_ID") is not None
    
    if is_hf_spaces:
        print("\n๐Ÿค— Running in secure mode on Hugging Face Spaces...")
        demo.launch(server_name="0.0.0.0", server_port=7860)
    else:
        print("\n๐Ÿ’ป Running in secure mode on local environment...")
        demo.launch(server_name="0.0.0.0", server_port=7860, share=False)