File size: 68,503 Bytes
41687a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41687a3
 
 
 
 
15fbc37
41687a3
 
 
 
 
15fbc37
41687a3
 
 
 
 
 
 
 
 
 
 
 
15fbc37
41687a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15fbc37
 
 
41687a3
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41687a3
 
 
 
 
15fbc37
 
41687a3
15fbc37
 
 
 
 
 
41687a3
15fbc37
41687a3
 
 
 
 
15fbc37
 
41687a3
 
 
 
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41687a3
15fbc37
41687a3
 
 
 
 
15fbc37
 
 
 
 
41687a3
15fbc37
 
41687a3
15fbc37
 
 
 
 
 
 
41687a3
15fbc37
41687a3
 
15fbc37
41687a3
 
 
 
 
 
 
 
 
 
15fbc37
41687a3
 
15fbc37
41687a3
 
 
 
 
 
 
 
 
 
15fbc37
 
 
41687a3
 
 
 
 
15fbc37
41687a3
 
 
 
 
 
 
 
15fbc37
 
41687a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15fbc37
41687a3
 
15fbc37
41687a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15fbc37
41687a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15fbc37
41687a3
 
 
 
 
 
 
 
 
 
 
15fbc37
41687a3
 
 
 
 
 
 
 
 
 
 
 
 
 
15fbc37
41687a3
15fbc37
41687a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d029b9
41687a3
 
 
15fbc37
 
41687a3
15fbc37
 
 
 
41687a3
15fbc37
 
 
 
41687a3
15fbc37
 
 
 
41687a3
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41687a3
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41687a3
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41687a3
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41687a3
 
15fbc37
 
 
41687a3
 
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9490797
41687a3
cea0f89
41687a3
15fbc37
41687a3
 
15fbc37
41687a3
15fbc37
41687a3
15fbc37
 
 
 
 
 
41687a3
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41687a3
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41687a3
15fbc37
 
 
 
 
 
 
41687a3
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41687a3
15fbc37
 
 
41687a3
15fbc37
41687a3
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41687a3
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41687a3
 
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d029b9
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
0d029b9
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41687a3
 
15fbc37
41687a3
 
15fbc37
 
 
 
41687a3
15fbc37
 
41687a3
 
15fbc37
 
41687a3
 
15fbc37
 
 
 
 
41687a3
 
 
 
 
 
 
15fbc37
41687a3
 
 
15fbc37
41687a3
15fbc37
41687a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15fbc37
41687a3
 
 
15fbc37
41687a3
 
 
15fbc37
41687a3
15fbc37
 
 
 
 
 
 
41687a3
 
15fbc37
41687a3
 
 
 
 
 
 
 
 
 
15fbc37
41687a3
 
 
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41687a3
15fbc37
41687a3
 
15fbc37
41687a3
15fbc37
41687a3
 
 
 
 
 
 
 
 
 
15fbc37
41687a3
 
 
 
 
 
 
 
15fbc37
41687a3
 
 
15fbc37
 
41687a3
 
 
 
 
 
 
 
 
15fbc37
41687a3
 
 
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41687a3
 
15fbc37
41687a3
 
 
 
 
15fbc37
41687a3
15fbc37
41687a3
 
 
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41687a3
 
15fbc37
41687a3
 
 
 
 
15fbc37
 
41687a3
 
 
15fbc37
 
 
 
 
41687a3
15fbc37
 
 
 
 
 
 
 
 
41687a3
15fbc37
 
 
 
 
 
 
 
 
41687a3
15fbc37
41687a3
 
15fbc37
 
41687a3
15fbc37
41687a3
15fbc37
41687a3
15fbc37
 
 
41687a3
 
 
15fbc37
41687a3
15fbc37
41687a3
 
 
15fbc37
41687a3
15fbc37
41687a3
 
 
15fbc37
 
41687a3
 
 
 
15fbc37
41687a3
 
 
 
 
15fbc37
41687a3
15fbc37
41687a3
 
15fbc37
 
41687a3
15fbc37
41687a3
 
15fbc37
 
 
 
 
41687a3
15fbc37
 
 
 
 
 
 
 
 
 
 
41687a3
 
 
 
15fbc37
 
41687a3
 
 
15fbc37
 
41687a3
 
 
15fbc37
41687a3
 
 
 
 
15fbc37
41687a3
 
 
 
 
 
 
 
15fbc37
 
 
 
 
41687a3
 
 
15fbc37
 
 
 
 
41687a3
 
 
15fbc37
41687a3
 
 
15fbc37
41687a3
15fbc37
 
 
41687a3
 
 
 
 
 
 
15fbc37
 
 
 
 
41687a3
 
 
 
15fbc37
41687a3
 
 
 
 
 
 
 
 
 
 
 
 
 
15fbc37
41687a3
 
15fbc37
41687a3
15fbc37
41687a3
 
15fbc37
 
41687a3
 
15fbc37
41687a3
 
15fbc37
 
41687a3
 
 
 
 
15fbc37
 
 
 
 
 
 
 
 
 
 
41687a3
 
15fbc37
 
41687a3
 
 
15fbc37
 
 
 
 
 
 
 
 
 
 
 
41687a3
 
15fbc37
41687a3
 
15fbc37
 
41687a3
 
 
 
15fbc37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41687a3
 
 
15fbc37
 
 
 
 
41687a3
 
 
 
 
 
 
 
 
15fbc37
41687a3
 
 
 
 
 
 
 
15fbc37
41687a3
 
 
 
 
 
 
15fbc37
41687a3
 
 
15fbc37
41687a3
 
 
 
 
84385af
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
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
import gradio as gr
import os
import json
import requests
from datetime import datetime
import time
from typing import List, Dict, Any, Generator, Tuple
import logging
import re

# 로깅 설정
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 추가 임포트
from bs4 import BeautifulSoup
from urllib.parse import urlparse
import urllib.request

# 환경 변수에서 토큰 가져오기
FRIENDLI_TOKEN = os.getenv("FRIENDLI_TOKEN", "YOUR_FRIENDLI_TOKEN")
BAPI_TOKEN = os.getenv("BAPI_TOKEN", "YOUR_BRAVE_API_TOKEN")
API_URL = "https://api.friendli.ai/dedicated/v1/chat/completions"
BRAVE_SEARCH_URL = "https://api.search.brave.com/res/v1/web/search"
MODEL_ID = "dep89a2fld32mcm"
TEST_MODE = os.getenv("TEST_MODE", "false").lower() == "true"

# 전역 변수
conversation_history = []

class LLMCollaborativeSystem:
    def __init__(self):
        self.token = FRIENDLI_TOKEN
        self.bapi_token = BAPI_TOKEN
        self.api_url = API_URL
        self.brave_url = BRAVE_SEARCH_URL
        self.model_id = MODEL_ID
        self.test_mode = TEST_MODE or (self.token == "YOUR_FRIENDLI_TOKEN")
        
        if self.test_mode:
            logger.warning("테스트 모드로 실행됩니다.")
        if self.bapi_token == "YOUR_BRAVE_API_TOKEN":
            logger.warning("Brave API 토큰이 설정되지 않았습니다.")
        
    def create_headers(self):
        """API 헤더 생성"""
        return {
            "Authorization": f"Bearer {self.token}",
            "Content-Type": "application/json"
        }
    
    def create_brave_headers(self):
        """Brave API 헤더 생성"""
        return {
            "Accept": "application/json",
            "Accept-Encoding": "gzip",
            "X-Subscription-Token": self.bapi_token
        }
    
    def create_supervisor_initial_prompt(self, user_query: str) -> str:
        """감독자 AI 초기 프롬프트 생성"""
        return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.

사용자 질문: {user_query}

이 질문에 대해:
1. 문제의 본질과 핵심 요구사항을 파악하세요
2. 해결을 위한 전략적 프레임워크를 수립하세요
3. 창조자 AI가 혁신적인 아이디어를 낼 수 있도록 문제의 맥락과 제약사항을 명확히 정의하세요
4. 성공 기준과 목표를 구체적으로 제시하세요"""
    
    def create_creator_prompt(self, user_query: str, supervisor_guidance: str) -> str:
        """창조자 AI 프롬프트 생성"""
        return f"""당신은 혁신적이고 창의적인 아이디어를 생성하는 창조자 AI입니다.

사용자 질문: {user_query}

감독자 AI의 분석:
{supervisor_guidance}

위 분석을 바탕으로:
1. 기존 방식을 뛰어넘는 혁신적인 해결 방안 5-7개를 제시하세요
2. 각 아이디어의 독창성과 잠재적 영향력을 설명하세요
3. 실현 가능성과 함께 필요한 리소스를 개략적으로 제시하세요
4. 아이디어 간의 시너지 효과나 결합 가능성을 탐색하세요
5. 미래 지향적이고 파괴적인 혁신 요소를 포함하세요"""
    
    def create_supervisor_ideation_review_prompt(self, user_query: str, creator_ideas: str) -> str:
        """감독자 AI의 아이디어 검토 및 조사 지시 프롬프트"""
        return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.

사용자 질문: {user_query}

창조자 AI가 제시한 혁신적 아이디어들:
{creator_ideas}

이 아이디어들을 검토하고:
1. 각 아이디어의 전략적 가치와 실현 가능성을 평가하세요
2. 가장 유망한 3-4개 아이디어를 선별하고 그 이유를 설명하세요
3. 선별된 아이디어에 대해 조사가 필요한 구체적인 키워드나 검색어를 제시하세요
4. 조사 시 중점적으로 확인해야 할 사항들을 명시하세요

키워드는 다음 형식으로 제시하세요:
[검색 키워드]: 키워드1, 키워드2, 키워드3, 키워드4, 키워드5"""
    
    def create_researcher_prompt(self, user_query: str, supervisor_guidance: str, search_results: Dict[str, List[Dict]]) -> str:
        """조사자 AI 프롬프트 생성 (기존 코드 재사용)"""
        search_summary = ""
        all_results = []
        
        for keyword, results in search_results.items():
            search_summary += f"\n\n**{keyword}에 대한 검색 결과:**\n"
            for i, result in enumerate(results[:10], 1):
                search_summary += f"{i}. {result.get('title', 'N/A')} (신뢰도: {result.get('credibility_score', 0):.2f})\n"
                search_summary += f"   - {result.get('description', 'N/A')}\n"
                search_summary += f"   - 출처: {result.get('url', 'N/A')}\n"
                if result.get('published'):
                    search_summary += f"   - 게시일: {result.get('published')}\n"
                
                all_results.extend(results)
        
        contradictions = self.detect_contradictions(all_results)
        contradiction_text = ""
        if contradictions:
            contradiction_text = "\n\n**발견된 정보 모순:**\n"
            for cont in contradictions[:3]:
                contradiction_text += f"- {cont['type']}: {cont['source1']} vs {cont['source2']}\n"
        
        return f"""당신은 정보를 조사하고 정리하는 조사자 AI입니다.

사용자 질문: {user_query}

감독자 AI의 지침:
{supervisor_guidance}

브레이브 검색 결과 (신뢰도 점수 포함):
{search_summary}
{contradiction_text}

위 검색 결과를 바탕으로:
1. 각 키워드별로 중요한 정보를 정리하세요
2. 신뢰할 수 있는 출처(신뢰도 0.7 이상)를 우선적으로 참고하세요
3. 실제 구현 사례나 성공 사례를 중점적으로 찾아 정리하세요
4. 기술적 실현 가능성과 필요한 리소스 정보를 포함하세요
5. 최신 트렌드와 미래 전망을 강조하세요"""
    
    def create_evaluator_research_prompt(self, user_query: str, creator_ideas: str, research_summary: str) -> str:
        """평가자 AI의 조사 결과 평가 프롬프트"""
        return f"""당신은 객관적이고 비판적인 시각으로 평가하는 평가자 AI입니다.

사용자 질문: {user_query}

창조자 AI의 아이디어:
{creator_ideas}

조사자 AI의 조사 결과:
{research_summary}

위 내용을 종합적으로 평가하여:
1. 각 아이디어의 실현 가능성을 1-10점으로 평가하고 근거를 제시하세요
2. 예상되는 리스크와 장애물을 구체적으로 분석하세요
3. ROI(투자 대비 효과)를 예측하고 우선순위를 제안하세요
4. 조사 결과의 신뢰성과 충분성을 평가하세요
5. 추가로 필요한 정보나 검증 사항을 제시하세요
6. 최종적으로 가장 실행 가능한 2-3개 방안을 추천하세요"""
    
    def create_supervisor_execution_prompt(self, user_query: str, evaluator_assessment: str) -> str:
        """감독자 AI의 실행 지시 프롬프트"""
        return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.

사용자 질문: {user_query}

평가자 AI의 종합 평가:
{evaluator_assessment}

평가 결과를 바탕으로 실행자 AI에게 구체적인 지시를 내려주세요:
1. 평가자가 추천한 방안들을 어떻게 구현할지 단계별로 명시하세요
2. 각 단계의 구체적인 작업 내용과 예상 소요 시간을 제시하세요
3. 리스크 대응 방안을 각 단계별로 준비하세요
4. 성과 측정 지표와 마일스톤을 명확히 정의하세요
5. 필요한 리소스와 협력 체계를 구체화하세요"""
    
    def create_executor_prompt(self, user_query: str, supervisor_guidance: str, full_context: str) -> str:
        """실행자 AI 프롬프트 생성"""
        return f"""당신은 세부적인 내용을 구현하는 실행자 AI입니다.

사용자 질문: {user_query}

전체 맥락 (아이디어, 조사, 평가):
{full_context}

감독자 AI의 구체적인 지시:
{supervisor_guidance}

위 모든 정보를 바탕으로:
1. 즉시 실행 가능한 구체적인 행동 계획을 작성하세요
2. 각 작업의 상세한 실행 방법과 필요 도구를 명시하세요
3. 예상되는 결과물과 산출물을 구체적으로 설명하세요
4. 단계별 체크리스트와 검증 방법을 포함하세요
5. 실제 코드, 템플릿, 프로세스 등 즉시 사용 가능한 자료를 제공하세요"""
    
    def create_evaluator_execution_prompt(self, user_query: str, executor_plan: str) -> str:
        """평가자 AI의 실행 계획 평가 프롬프트"""
        return f"""당신은 객관적이고 비판적인 시각으로 평가하는 평가자 AI입니다.

사용자 질문: {user_query}

실행자 AI의 실행 계획:
{executor_plan}

이 실행 계획을 평가하여:
1. 계획의 완성도와 실행 가능성을 평가하세요 (1-10점)
2. 누락된 요소나 개선이 필요한 부분을 구체적으로 지적하세요
3. 예상되는 실행 상의 문제점과 해결 방안을 제시하세요
4. 성공 가능성을 높이기 위한 추가 제안을 하세요
5. 최종 점검 사항과 품질 기준을 제시하세요"""
    
    def create_supervisor_final_prompt(self, user_query: str, evaluator_feedback: str) -> str:
        """감독자 AI의 최종 지시 프롬프트"""
        return f"""당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.

사용자 질문: {user_query}

평가자 AI의 실행 계획 평가:
{evaluator_feedback}

평가 내용을 바탕으로:
1. 실행자 AI가 반드시 보완해야 할 핵심 사항을 명확히 지시하세요
2. 최종 품질 기준과 완성도 요구사항을 제시하세요
3. 즉시 실행 가능한 형태로 만들기 위한 구체적인 개선 방향을 제시하세요
4. 성공적인 실행을 위한 핵심 성공 요인을 강조하세요"""
    
    def create_executor_final_prompt(self, user_query: str, initial_plan: str, supervisor_final_guidance: str, full_context: str) -> str:
        """실행자 AI 최종 보고서 프롬프트"""
        return f"""당신은 세부적인 내용을 구현하는 실행자 AI입니다.

사용자 질문: {user_query}

전체 협업 맥락:
{full_context}

당신의 초기 실행 계획:
{initial_plan}

감독자 AI의 최종 지시사항:
{supervisor_final_guidance}

모든 피드백을 완전히 반영하여 즉시 실행 가능한 최종 솔루션을 작성하세요:
1. 모든 개선사항을 반영한 완성된 실행 계획
2. 구체적인 실행 도구, 코드, 템플릿 제공
3. 단계별 실행 가이드와 체크리스트
4. 예상 결과와 성과 측정 방법
5. 리스크 대응 계획과 문제 해결 가이드
6. 지속적 개선을 위한 모니터링 체계

**반드시 실용적이고 즉시 적용 가능한 형태로 작성하세요.**"""
    
    def extract_keywords(self, supervisor_response: str) -> List[str]:
        """감독자 응답에서 키워드 추출 (기존 코드 재사용)"""
        keywords = []
        
        keyword_match = re.search(r'\[검색 키워드\]:\s*(.+)', supervisor_response, re.IGNORECASE)
        if keyword_match:
            keyword_str = keyword_match.group(1)
            keywords = [k.strip() for k in keyword_str.split(',') if k.strip()]
        
        if not keywords:
            keywords = ["best practices", "implementation guide", "case studies", "latest trends", "success factors"]
        
        return keywords[:7]
    
    def generate_synonyms(self, keyword: str) -> List[str]:
        """키워드의 동의어/유사어 생성 (기존 코드 재사용)"""
        synonyms = {
            "optimization": ["improvement", "enhancement", "efficiency", "tuning"],
            "performance": ["speed", "efficiency", "throughput", "latency"],
            "strategy": ["approach", "method", "technique", "plan"],
            "implementation": ["deployment", "execution", "development", "integration"],
            "analysis": ["evaluation", "assessment", "study", "research"],
            "management": ["administration", "governance", "control", "supervision"],
            "best practices": ["proven methods", "industry standards", "guidelines", "recommendations"],
            "trends": ["developments", "innovations", "emerging", "future"],
            "machine learning": ["ML", "AI", "deep learning", "neural networks"],
            "프로젝트": ["project", "사업", "업무", "작업"],
            "innovation": ["disruption", "breakthrough", "transformation", "revolution"],
            "solution": ["approach", "method", "system", "framework"]
        }
        
        keyword_lower = keyword.lower()
        
        if keyword_lower in synonyms:
            return synonyms[keyword_lower][:2]
        
        for key, values in synonyms.items():
            if key in keyword_lower or keyword_lower in key:
                return values[:2]
        
        return []
    
    def calculate_credibility_score(self, result: Dict) -> float:
        """검색 결과의 신뢰도 점수 계산 (기존 코드 재사용)"""
        score = 0.5
        
        url = result.get('url', '')
        title = result.get('title', '')
        description = result.get('description', '')
        
        trusted_domains = [
            '.edu', '.gov', '.org', 'wikipedia.org', 'nature.com', 
            'sciencedirect.com', 'ieee.org', 'acm.org', 'springer.com',
            'harvard.edu', 'mit.edu', 'stanford.edu', 'github.com'
        ]
        
        for domain in trusted_domains:
            if domain in url:
                score += 0.2
                break
        
        if url.startswith('https://'):
            score += 0.1
        
        if len(title) > 20:
            score += 0.05
        if len(description) > 50:
            score += 0.05
        
        spam_keywords = ['buy now', 'sale', 'discount', 'click here', '100% free']
        if any(spam in (title + description).lower() for spam in spam_keywords):
            score -= 0.3
        
        if any(year in description for year in ['2024', '2023', '2022']):
            score += 0.1
        
        return max(0, min(1, score))
    
    def fetch_url_content(self, url: str, max_length: int = 2000) -> str:
        """URL에서 콘텐츠 추출 (기존 코드 재사용)"""
        try:
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
            
            req = urllib.request.Request(url, headers=headers)
            
            with urllib.request.urlopen(req, timeout=5) as response:
                html = response.read().decode('utf-8', errors='ignore')
                
            soup = BeautifulSoup(html, 'html.parser')
            
            for script in soup(["script", "style"]):
                script.decompose()
            
            text = soup.get_text()
            
            lines = (line.strip() for line in text.splitlines())
            chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
            text = ' '.join(chunk for chunk in chunks if chunk)
            
            if len(text) > max_length:
                text = text[:max_length] + "..."
            
            return text
            
        except Exception as e:
            logger.error(f"URL 콘텐츠 가져오기 실패 {url}: {str(e)}")
            return ""
    
    def detect_contradictions(self, results: List[Dict]) -> List[Dict]:
        """검색 결과 간 모순 감지 (기존 코드 재사용)"""
        contradictions = []
        
        opposite_pairs = [
            ("increase", "decrease"),
            ("improve", "worsen"),
            ("effective", "ineffective"),
            ("success", "failure"),
            ("benefit", "harm"),
            ("positive", "negative"),
            ("growth", "decline")
        ]
        
        for i in range(len(results)):
            for j in range(i + 1, len(results)):
                desc1 = results[i].get('description', '').lower()
                desc2 = results[j].get('description', '').lower()
                
                for word1, word2 in opposite_pairs:
                    if (word1 in desc1 and word2 in desc2) or (word2 in desc1 and word1 in desc2):
                        common_words = set(desc1.split()) & set(desc2.split())
                        if len(common_words) > 5:
                            contradictions.append({
                                'source1': results[i]['url'],
                                'source2': results[j]['url'],
                                'type': f"{word1} vs {word2}",
                                'desc1': results[i]['description'][:100],
                                'desc2': results[j]['description'][:100]
                            })
        
        return contradictions
    
    def brave_search(self, query: str) -> List[Dict]:
        """Brave Search API 호출 (기존 코드 재사용)"""
        if self.test_mode or self.bapi_token == "YOUR_BRAVE_API_TOKEN":
            test_results = []
            for i in range(5):
                test_results.append({
                    "title": f"Best Practices for {query} - Source {i+1}",
                    "description": f"Comprehensive guide on implementing {query} with proven methodologies and real-world examples from industry leaders.",
                    "url": f"https://example{i+1}.com/{query.replace(' ', '-')}",
                    "credibility_score": 0.7 + (i * 0.05)
                })
            return test_results
        
        try:
            params = {
                "q": query,
                "count": 20,
                "safesearch": "moderate",
                "freshness": "pw"
            }
            
            response = requests.get(
                self.brave_url,
                headers=self.create_brave_headers(),
                params=params,
                timeout=10
            )
            
            if response.status_code == 200:
                data = response.json()
                results = []
                for item in data.get("web", {}).get("results", [])[:20]:
                    result = {
                        "title": item.get("title", ""),
                        "description": item.get("description", ""),
                        "url": item.get("url", ""),
                        "published": item.get("published", "")
                    }
                    result["credibility_score"] = self.calculate_credibility_score(result)
                    results.append(result)
                
                results.sort(key=lambda x: x['credibility_score'], reverse=True)
                return results
            else:
                logger.error(f"Brave API 오류: {response.status_code}")
                return []
                
        except Exception as e:
            logger.error(f"Brave 검색 중 오류: {str(e)}")
            return []
    
    def simulate_streaming(self, text: str, role: str) -> Generator[str, None, None]:
        """테스트 모드에서 스트리밍 시뮬레이션"""
        words = text.split()
        for i in range(0, len(words), 3):
            chunk = " ".join(words[i:i+3])
            yield chunk + " "
            time.sleep(0.05)
    
    def call_llm_streaming(self, messages: List[Dict[str, str]], role: str) -> Generator[str, None, None]:
        """스트리밍 LLM API 호출"""
        
        if self.test_mode:
            logger.info(f"테스트 모드 스트리밍 - Role: {role}")
            # test_responses 딕셔너리를 메서드 내부에 정의
            test_responses = {
                "supervisor_initial": """이 질문에 대한 거시적 분석을 제시하겠습니다.

**1. 문제의 본질 파악**
사용자는 실용적이고 즉시 적용 가능한 해결책을 원하고 있습니다. 단순한 이론이나 개념이 아닌, 실제로 구현 가능한 구체적인 방안이 필요합니다.

**2. 전략적 프레임워크**
- 단기 목표: 즉시 실행 가능한 quick win 솔루션 도출
- 중기 목표: 지속 가능한 개선 체계 구축
- 장기 목표: 혁신적 변화를 통한 경쟁 우위 확보

**3. 제약사항 및 맥락**
- 기존 리소스와 인프라 활용 극대화
- 최소한의 투자로 최대 효과 달성
- 실무진이 바로 이해하고 실행할 수 있는 수준

**4. 성공 기준**
- 측정 가능한 개선 지표 (30% 이상 향상)
- 3개월 내 가시적 성과 달성
- ROI 200% 이상 달성""",
                
                "creator": """혁신적인 아이디어를 제시하겠습니다.

**🚀 아이디어 1: AI 기반 자동 최적화 시스템**
- 독창성: 머신러닝이 스스로 시스템을 개선하는 자가 진화 시스템
- 영향력: 인간 개입 없이 24/7 성능 향상, 90% 효율성 증가 가능
- 필요 리소스: 클라우드 컴퓨팅, ML 엔지니어 1명
- 실현 가능성: 8/10

**💡 아이디어 2: 크라우드소싱 혁신 플랫폼**
- 독창성: 전 직원이 참여하는 실시간 개선 아이디어 시장
- 영향력: 집단 지성 활용으로 혁신 속도 10배 가속
- 필요 리소스: 웹 플랫폼, 인센티브 예산
- 실현 가능성: 9/10

**🔄 아이디어 3: 디지털 트윈 시뮬레이션**
- 독창성: 가상 환경에서 모든 시나리오를 사전 테스트
- 영향력: 리스크 80% 감소, 실패 비용 제로화
- 필요 리소스: 시뮬레이션 소프트웨어, 데이터 분석가
- 실현 가능성: 7/10

**🌐 아이디어 4: 블록체인 기반 프로세스 자동화**
- 독창성: 신뢰 기반 자동 실행 스마트 컨트랙트
- 영향력: 중개 비용 제거, 처리 시간 95% 단축
- 필요 리소스: 블록체인 개발자, 네트워크 인프라
- 실현 가능성: 6/10

**🧬 아이디어 5: 생체모방 알고리즘 적용**
- 독창성: 자연의 최적화 원리를 비즈니스에 적용
- 영향력: 예측 불가능한 환경에서도 적응력 극대화
- 필요 리소스: R&D 팀, 실험 환경
- 실현 가능성: 5/10

**시너지 효과**
아이디어 1+2 결합: AI가 크라우드소싱 아이디어를 자동 평가하고 구현
아이디어 3+4 결합: 블록체인으로 검증된 디지털 트윈 결과 자동 실행""",
                
                "supervisor_ideation_review": """창조자 AI의 아이디어를 검토한 결과입니다.

**전략적 평가**
1. AI 기반 자동 최적화 시스템 - ⭐⭐⭐⭐⭐
   - 즉시 실행 가능하고 ROI가 명확함
   - 기존 인프라 활용 가능

2. 크라우드소싱 혁신 플랫폼 - ⭐⭐⭐⭐⭐
   - 조직 문화 개선과 혁신 동시 달성
   - 빠른 구현과 낮은 리스크

3. 디지털 트윈 시뮬레이션 - ⭐⭐⭐⭐
   - 중장기적 가치가 높음
   - 초기 투자 대비 효과 검증 필요

**선별된 아이디어**
1, 2, 3번 아이디어를 중심으로 진행 권장

**조사 필요 사항**
- 성공 사례와 구현 방법론
- 필요 기술 스택과 도구
- 예상 비용과 ROI 데이터
- 산업별 적용 사례

[검색 키워드]: AI automation implementation case studies, crowdsourcing innovation platform examples, digital twin ROI analysis, machine learning optimization tools, employee innovation engagement systems""",
                
                "researcher": """조사 결과를 종합하여 보고합니다.

**1. AI 자동 최적화 시스템 구현 사례 (신뢰도 0.92)**
- Google: AutoML로 모델 성능 40% 개선, 개발 시간 90% 단축
- Netflix: 실시간 최적화로 스트리밍 품질 35% 향상
- 구현 도구: TensorFlow Extended, AutoKeras, H2O.ai
- 평균 ROI: 6개월 내 250%
- 출처: Google AI Blog, Netflix Tech Blog

**2. 크라우드소싱 혁신 플랫폼 성공 사례 (신뢰도 0.88)**
- P&G Connect+Develop: 외부 혁신으로 R&D 생산성 60% 향상
- Lego Ideas: 고객 아이디어로 신제품 출시 주기 50% 단축
- 플랫폼: IdeaScale, Brightidea, Spigit
- 평균 참여율: 직원의 75%
- 출처: Harvard Business Review, MIT Sloan Review

**3. 디지털 트윈 ROI 분석 (신뢰도 0.85)**
- GE: 예측 정비로 다운타임 20% 감소, 연간 $1.6B 절감
- Siemens: 제품 개발 주기 50% 단축
- 필요 기술: Azure Digital Twins, AWS IoT TwinMaker
- 초기 투자 회수: 평균 18개월
- 출처: Gartner Report 2024, IDC Research

**4. 실제 구현 가이드 (신뢰도 0.90)**
- 단계별 구현 로드맵 확보
- 오픈소스 도구 목록 및 비용 분석
- 필요 인력: 프로젝트당 3-5명
- 구현 기간: 3-6개월

**5. 최신 트렌드 (신뢰도 0.87)**
- 2024년 AI 자동화가 주류로 부상
- Low-code/No-code 플랫폼으로 진입 장벽 낮아짐
- Edge AI로 실시간 최적화 가능
- 출처: McKinsey Digital Report 2024

**핵심 인사이트**
- 세 가지 아이디어 모두 검증된 성공 사례 존재
- 투자 대비 효과가 명확히 입증됨
- 기술적 구현 장벽이 낮아지고 있음
- 빠른 실행이 경쟁 우위의 핵심""",
                
                "evaluator_research": """조사 결과를 객관적으로 평가합니다.

**실현 가능성 평가**
1. AI 자동 최적화 시스템: 9/10
   - 근거: 다수의 성공 사례, 명확한 ROI, 기술 성숙도 높음
   - 리스크: 초기 데이터 품질, 내부 저항
   - ROI 예측: 6개월 내 250% (조사 결과 검증됨)

2. 크라우드소싱 혁신 플랫폼: 9/10
   - 근거: 즉시 구현 가능, 낮은 기술 장벽
   - 리스크: 참여도 저하, 아이디어 품질 관리
   - ROI 예측: 1년 내 180%

3. 디지털 트윈: 7/10
   - 근거: 높은 잠재력, 장기적 가치
   - 리스크: 초기 투자 규모, 기술 복잡도
   - ROI 예측: 18개월 내 200%

**조사 신뢰성 평가**
- 출처 신뢰도: 평균 0.88 (매우 높음)
- 정보 충분성: 85% (실행에 충분)
- 추가 필요 정보: 산업별 세부 사례, 실패 요인 분석

**최종 추천**
1순위: AI 자동 최적화 + 크라우드소싱 통합 접근
- 두 방안을 결합하여 시너지 극대화
- 단계적 구현으로 리스크 최소화
- 3개월 내 가시적 성과 가능

2순위: 디지털 트윈 (중장기 프로젝트로 병행)""",
                
                "supervisor_execution": """평가 결과를 바탕으로 구체적인 실행 지시를 내립니다.

**통합 실행 전략**
AI 자동 최적화와 크라우드소싱을 결합한 "지능형 혁신 시스템" 구축

**1단계: 기반 구축 (1-2주차)**
- AI 자동 최적화 파일럿 프로젝트 선정
- 크라우드소싱 플랫폼 도구 선정 (IdeaScale 추천)
- 프로젝트팀 구성: PM 1명, ML 엔지니어 2명, 플랫폼 관리자 1명
- 초기 예산: $50,000

**2단계: 파일럿 실행 (3-6주차)**
- 선정 부서에서 AI 최적화 테스트
- 전사 아이디어 공모 시작
- 주간 성과 측정 및 조정
- 리스크: 데이터 품질 → 대응: 데이터 정제 자동화

**3단계: 통합 및 확장 (7-12주차)**
- AI가 크라우드소싱 아이디어 자동 평가
- 최우수 아이디어 자동 시뮬레이션
- 단계적 전사 확대
- 성과 지표: 효율성 30% 향상, 혁신 아이디어 100개/월

**리스크 대응 계획**
- 기술적 문제: 24/7 모니터링, 롤백 계획
- 참여 저조: 게임화, 인센티브 강화
- 품질 이슈: AI 기반 품질 검증

**성과 측정**
- 주간: 시스템 성능, 참여율
- 월간: ROI, 혁신 지표
- 분기: 전략적 영향 평가""",
                
                "executor": """즉시 실행 가능한 구체적 계획을 제시합니다.

**🚀 1주차: 킥오프 및 환경 구축**

월요일-화요일: 프로젝트팀 구성 및 환경 설정
```python
# AI 최적화 환경 설정 스크립트
import tensorflow as tf
from tensorflow import keras
import autokeras as ak

# 자동 최적화 파이프라인 설정
class AutoOptimizer:
    def __init__(self):
        self.model = ak.AutoModel(
            project_name='auto_optimization',
            max_trials=100
        )
    
    def optimize(self, data):
        # 자동 하이퍼파라미터 튜닝
        self.model.fit(data['X'], data['y'])
        return self.model.evaluate(data['X_test'], data['y_test'])
```

수요일-금요일: 크라우드소싱 플랫폼 구축
- IdeaScale 계정 설정 및 커스터마이징
- 직원 온보딩 자료 작성
- 평가 기준 및 보상 체계 수립

**📊 2-3주차: 파일럿 프로그램 실행**

데이터 수집 및 AI 모델 훈련:
```python
# 실시간 성능 모니터링 대시보드
import dash
import plotly.graph_objs as go

app = dash.Dash(__name__)
app.layout = html.Div([
    dcc.Graph(id='live-performance'),
    dcc.Interval(id='graph-update', interval=1000)
])

@app.callback(Output('live-performance', 'figure'),
              [Input('graph-update', 'n_intervals')])
def update_metrics(n):
    # 실시간 성능 지표 업데이트
    return create_performance_dashboard()
```

크라우드소싱 캠페인 런칭:
- 첫 주 챌린지: "효율성 10% 개선 아이디어"
- 일일 리더보드 및 포인트 시스템
- AI 자동 아이디어 분류 및 초기 평가

**🔧 4-6주차: 통합 시스템 구현**

AI-크라우드소싱 통합 모듈:
```python
class InnovationEngine:
    def __init__(self):
        self.ai_evaluator = AIIdeaEvaluator()
        self.crowd_platform = CrowdsourcingPlatform()
    
    def process_idea(self, idea):
        # 1. AI 초기 평가
        score = self.ai_evaluator.evaluate(idea)
        
        # 2. 유망 아이디어 자동 시뮬레이션
        if score > 0.7:
            simulation_result = self.run_simulation(idea)
            
        # 3. 실행 우선순위 자동 배정
        return self.prioritize_execution(idea, score, simulation_result)
```

**📈 예상 산출물**
1. 구동 가능한 AI 최적화 시스템
2. 활성화된 크라우드소싱 플랫폼  
3. 통합 대시보드 및 분석 도구
4. 첫 달 목표: 50개 아이디어, 5개 구현, 15% 효율성 개선""",
                
                "evaluator_execution": """실행 계획을 평가합니다.

**계획 완성도: 8.5/10**

**강점**
- 즉시 실행 가능한 코드와 구체적 일정 제공
- 단계별 명확한 목표와 산출물 정의
- 기술 스택이 검증되고 실용적임

**개선 필요사항**
1. 데이터 보안 및 프라이버시 대책 미흡
   - 추가 필요: GDPR 준수 체크리스트, 데이터 암호화 방안

2. 변화 관리 계획 부족
   - 추가 필요: 직원 교육 프로그램, 저항 관리 전략

3. 백업 및 복구 계획 누락
   - 추가 필요: 시스템 장애 시 BCP, 데이터 백업 주기

**실행 상 예상 문제점**
1. 초기 데이터 부족 → 해결: 합성 데이터 생성 또는 전이학습
2. 직원 참여 저조 → 해결: 챔피언 그룹 육성, 조기 성공 사례 홍보
3. 기술 통합 복잡도 → 해결: 마이크로서비스 아키텍처 채택

**추가 제안**
- A/B 테스트 프레임워크 구축
- 실패 시 빠른 피벗을 위한 의사결정 체계
- 외부 전문가 자문단 구성
- 경쟁사 벤치마킹 정기 실시

**품질 기준**
- 코드 커버리지 80% 이상
- 응답 시간 200ms 이하
- 시스템 가용성 99.9%
- 사용자 만족도 4.5/5 이상""",
                
                "supervisor_final": """평가를 바탕으로 최종 개선 지시를 내립니다.

**필수 보완 사항**

1. **보안 및 컴플라이언스 강화**
   - GDPR/CCPA 준수 체크리스트 즉시 작성
   - 전체 데이터 플로우 암호화 구현
   - 접근 권한 관리 시스템 구축

2. **변화 관리 프로그램 추가**
   - 1주차에 전직원 타운홀 미팅 실시
   - 부서별 챔피언 선정 및 인센티브 제공
   - 주간 성공 사례 공유 세션 운영

3. **리스크 관리 체계 구축**
   - 24/7 모니터링 대시보드 구현
   - 자동 롤백 시스템 구축
   - 핫라인 및 긴급 대응팀 구성

**품질 보증 요구사항**
- 모든 코드는 peer review 필수
- 자동화된 테스트 커버리지 85% 이상
- 일일 스탠드업으로 진행상황 체크

**성공을 위한 핵심 요소**
1. 경영진의 visible한 지원과 참여
2. Quick win 사례를 통한 모멘텀 구축
3. 지속적인 개선과 빠른 피드백 루프
4. 투명한 성과 공유와 보상

**최종 목표**
- 3개월 내 ROI 150% 달성
- 직원 참여율 80% 이상
- 시스템 안정성 99.9% 유지""",
                
                "executor_final": """모든 피드백을 완전히 반영하여 최종 실행 가능 솔루션입니다.

# 🎯 지능형 혁신 시스템 구축 - 최종 실행 가이드

## 📋 Executive Summary
AI 자동 최적화와 크라우드소싱을 통합한 혁신 시스템으로 3개월 내 효율성 30% 향상, ROI 150% 달성을 목표로 합니다.

## 🚀 1주차: 보안 강화된 프로젝트 시작

### Day 1-2: 킥오프 및 보안 체계 구축
```python
# 보안 강화된 데이터 처리 파이프라인
from cryptography.fernet import Fernet
import hashlib
from datetime import datetime

class SecureDataPipeline:
    def __init__(self):
        self.key = Fernet.generate_key()
        self.cipher = Fernet(self.key)
        self.audit_log = []
    
    def process_data(self, data, user_id):
        # GDPR 준수 암호화
        encrypted = self.cipher.encrypt(data.encode())
        
        # 감사 로그
        self.audit_log.append({
            'user': user_id,
            'action': 'data_process',
            'timestamp': datetime.now(),
            'data_hash': hashlib.sha256(data.encode()).hexdigest()
        })
        
        return self.run_optimization(encrypted)
    
    def run_optimization(self, encrypted_data):
        # 암호화된 상태에서 처리
        decrypted = self.cipher.decrypt(encrypted_data)
        # AI 최적화 로직
        return optimized_result
```

### Day 3: 전직원 타운홀 미팅
**어젠다 (1시간)**
1. 비전 공유: CEO 발표 (10분)
2. 시스템 소개: 프로젝트 리더 (20분)
3. 혜택 설명: 직원 관점에서 (15분)
4. Q&A 및 피드백 (15분)

**변화 관리 자료**
```markdown
# 직원을 위한 혁신 시스템 가이드

## 당신에게 주는 혜택
✅ 아이디어가 즉시 실행됩니다
✅ 기여도에 따른 명확한 보상
✅ 반복 업무 자동화로 창의적 업무 집중
✅ 실시간 성과 확인 가능

## 참여 방법 (3단계)
1. 플랫폼 로그인 → 아이디어 제출
2. AI가 자동 평가 → 24시간 내 피드백
3. 실행 및 보상 → 포인트/보너스 지급
```

### Day 4-5: 기술 인프라 구축
```python
# 통합 모니터링 대시보드
import dash
import plotly.graph_objs as go
from dash import dcc, html, Input, Output
import pandas as pd

class MonitoringDashboard:
    def __init__(self):
        self.app = dash.Dash(__name__)
        self.setup_layout()
        self.setup_callbacks()
    
    def setup_layout(self):
        self.app.layout = html.Div([
            html.H1("지능형 혁신 시스템 대시보드"),
            
            # 실시간 KPI
            html.Div([
                dcc.Graph(id='efficiency-gauge'),
                dcc.Graph(id='participation-rate'),
                dcc.Graph(id='roi-tracker'),
                dcc.Graph(id='system-health')
            ], style={'display': 'flex'}),
            
            # 알림 시스템
            html.Div(id='alerts', className='alert-box'),
            
            # 자동 업데이트
            dcc.Interval(id='interval', interval=5000)
        ])
    
    def setup_callbacks(self):
        @self.app.callback(
            [Output('efficiency-gauge', 'figure'),
             Output('alerts', 'children')],
            [Input('interval', 'n_intervals')]
        )
        def update_dashboard(n):
            # 실시간 메트릭 수집
            metrics = self.collect_metrics()
            
            # 임계값 체크 및 알림
            alerts = self.check_thresholds(metrics)
            
            return self.create_gauge(metrics['efficiency']), alerts
```

## 📊 2-3주차: 스마트 파일럿 프로그램

### 크라우드소싱 게임화 시스템
```python
class GamificationEngine:
    def __init__(self):
        self.levels = {
            'Novice': 0,
            'Contributor': 100,
            'Innovator': 500,
            'Champion': 1000,
            'Legend': 5000
        }
        self.badges = {
            'first_idea': '첫 아이디어',
            'week_streak': '주간 연속 참여',
            'top_rated': '최고 평점',
            'implemented': '아이디어 실행됨'
        }
    
    def process_contribution(self, user_id, idea):
        points = self.calculate_points(idea)
        badges = self.check_badges(user_id, idea)
        level_up = self.check_level_up(user_id, points)
        
        # 실시간 알림
        if level_up:
            self.notify_achievement(user_id, level_up)
        
        return {
            'points': points,
            'badges': badges,
            'level': self.get_user_level(user_id),
            'ranking': self.get_ranking(user_id)
        }
```

### AI 평가 및 시뮬레이션 엔진
```python
class AIInnovationEvaluator:
    def __init__(self):
        self.models = {
            'feasibility': self.load_model('feasibility_model.h5'),
            'impact': self.load_model('impact_model.h5'),
            'cost': self.load_model('cost_model.h5')
        }
    
    def evaluate_idea(self, idea_text, metadata):
        # NLP 처리
        features = self.extract_features(idea_text)
        
        # 다차원 평가
        scores = {
            'feasibility': self.models['feasibility'].predict(features),
            'impact': self.models['impact'].predict(features),
            'cost_efficiency': self.models['cost'].predict(features),
            'innovation_index': self.calculate_innovation(features)
        }
        
        # 자동 시뮬레이션 트리거
        if scores['feasibility'] > 0.7 and scores['impact'] > 0.8:
            simulation_result = self.run_simulation(idea_text, metadata)
            scores['simulation'] = simulation_result
        
        return self.generate_report(scores, idea_text)
```

## 🔧 4-6주차: 고급 통합 및 최적화

### 자동 실행 파이프라인
```python
class AutoExecutionPipeline:
    def __init__(self):
        self.executor = TaskExecutor()
        self.validator = ResultValidator()
        self.rollback = RollbackManager()
    
    def execute_approved_idea(self, idea_id):
        try:
            # 실행 계획 생성
            plan = self.create_execution_plan(idea_id)
            
            # 단계별 실행 with 체크포인트
            for step in plan.steps:
                result = self.executor.execute(step)
                
                if not self.validator.validate(result):
                    self.rollback.restore_checkpoint(step.checkpoint)
                    return self.handle_failure(step, result)
                
                # 실시간 진행상황 업데이트
                self.update_progress(idea_id, step.completion_rate)
            
            return self.finalize_execution(idea_id)
            
        except Exception as e:
            self.emergency_rollback(idea_id)
            self.alert_team(e)
```

### 지속적 개선 시스템
```python
class ContinuousImprovement:
    def __init__(self):
        self.ml_pipeline = MLPipeline()
        self.feedback_loop = FeedbackLoop()
        
    def daily_optimization(self):
        # 매일 자정 실행
        performance_data = self.collect_daily_metrics()
        
        # 모델 재훈련
        self.ml_pipeline.retrain(performance_data)
        
        # A/B 테스트 자동 설정
        experiments = self.design_experiments(performance_data)
        
        for exp in experiments:
            self.run_ab_test(exp)
        
        # 인사이트 생성
        insights = self.generate_insights(performance_data)
        self.distribute_report(insights)
```

## 📈 성과 측정 및 보고 체계

### 실시간 KPI 대시보드
```python
kpi_metrics = {
    'efficiency_gain': {
        'current': 0,
        'target': 30,
        'unit': '%'
    },
    'participation_rate': {
        'current': 0,
        'target': 80,
        'unit': '%'
    },
    'ideas_per_month': {
        'current': 0,
        'target': 100,
        'unit': 'count'
    },
    'roi': {
        'current': 0,
        'target': 150,
        'unit': '%'
    },
    'system_uptime': {
        'current': 0,
        'target': 99.9,
        'unit': '%'
    }
}

# 자동 보고서 생성
def generate_weekly_report():
    report = f\"\"\"
    # 주간 성과 보고서 - {datetime.now().strftime('%Y-%m-%d')}
    
    ## 핵심 성과
    - 효율성 향상: {kpi_metrics['efficiency_gain']['current']}%
    - 직원 참여율: {kpi_metrics['participation_rate']['current']}%
    - 제출된 아이디어: {kpi_metrics['ideas_per_month']['current']}개
    - ROI: {kpi_metrics['roi']['current']}%
    
    ## 주요 성공 사례
    {get_success_stories()}
    
    ## 다음 주 계획
    {get_next_week_plan()}
    \"\"\"
    return report
```

## 🛡️ 리스크 관리 및 비상 계획

### 자동 백업 및 복구
```bash
#!/bin/bash
# 시간별 자동 백업 스크립트
BACKUP_DIR="/secure/backups/$(date +%Y%m%d)"
mkdir -p $BACKUP_DIR

# 데이터베이스 백업
pg_dump -U postgres innovation_db > $BACKUP_DIR/db_backup_$(date +%H%M).sql

# 애플리케이션 상태 백업
kubectl get all --all-namespaces -o yaml > $BACKUP_DIR/k8s_state_$(date +%H%M).yaml

# S3 업로드 (암호화)
aws s3 cp $BACKUP_DIR s3://innovation-backups/ --recursive --sse
```

### 24/7 모니터링 및 알림
```python
class AlertingSystem:
    def __init__(self):
        self.thresholds = {
            'response_time': 200,  # ms
            'error_rate': 0.01,    # 1%
            'cpu_usage': 80,       # %
            'participation_drop': 20  # %
        }
        
    def monitor(self):
        while True:
            metrics = self.collect_metrics()
            
            for metric, value in metrics.items():
                if self.is_threshold_breached(metric, value):
                    self.trigger_alert(metric, value)
                    self.auto_remediate(metric)
            
            time.sleep(60)  # 1분마다 체크
```

## 🎯 최종 체크리스트

### Week 1 완료 사항
- [ ] 보안 인프라 구축 완료
- [ ] 전직원 타운홀 미팅 실시
- [ ] 챔피언 그룹 선정
- [ ] 기본 시스템 배포

### Week 2-3 완료 사항
- [ ] 파일럿 부서 선정 및 시작
- [ ] 첫 아이디어 캠페인 런칭
- [ ] AI 평가 시스템 가동
- [ ] 첫 quick win 달성

### Week 4-6 완료 사항
- [ ] 전사 확대 시작
- [ ] 자동화 파이프라인 완성
- [ ] KPI 목표 50% 달성
- [ ] 첫 ROI 리포트 작성

## 💡 성공을 위한 팁
1. 매일 아침 5분 스탠드업 미팅
2. 주간 성공 사례 전사 공유
3. 월간 혁신 어워드 시상
4. 분기별 해커톤 개최

---
*이 시스템은 지속적으로 진화합니다. 피드백은 [email protected]으로!*"""
            }
            
            # 역할과 프롬프트에 따라 적절한 응답 선택
            if role == "supervisor" and "창조자 AI가 제시한" in messages[0]["content"]:
                response = test_responses["supervisor_ideation_review"]
            elif role == "supervisor" and "평가자 AI의 종합 평가" in messages[0]["content"]:
                response = test_responses["supervisor_execution"]
            elif role == "supervisor" and "평가자 AI의 실행 계획 평가" in messages[0]["content"]:
                response = test_responses["supervisor_final"]
            elif role == "supervisor":
                response = test_responses["supervisor_initial"]
            elif role == "creator":
                response = test_responses["creator"]
            elif role == "researcher":
                response = test_responses["researcher"]
            elif role == "evaluator" and "조사자 AI의 조사 결과" in messages[0]["content"]:
                response = test_responses["evaluator_research"]
            elif role == "evaluator":
                response = test_responses["evaluator_execution"]
            elif role == "executor" and "최종 솔루션" in messages[0]["content"]:
                response = test_responses["executor_final"]
            else:
                response = test_responses["executor"]
            
            yield from self.simulate_streaming(response, role)
            return
        
        # 실제 API 호출 (기존 코드와 동일)
        try:
            system_prompts = {
                "supervisor": "당신은 거시적 관점에서 분석하고 지도하는 감독자 AI입니다.",
                "creator": "당신은 혁신적이고 창의적인 아이디어를 생성하는 창조자 AI입니다.",
                "researcher": "당신은 정보를 조사하고 체계적으로 정리하는 조사자 AI입니다.",
                "evaluator": "당신은 객관적이고 비판적인 시각으로 평가하는 평가자 AI입니다.",
                "executor": "당신은 세부적인 내용을 구현하는 실행자 AI입니다."
            }
            
            full_messages = [
                {"role": "system", "content": system_prompts.get(role, "")},
                *messages
            ]
            
            payload = {
                "model": self.model_id,
                "messages": full_messages,
                "max_tokens": 2048,
                "temperature": 0.7,
                "top_p": 0.8,
                "stream": True,
                "stream_options": {"include_usage": True}
            }
            
            logger.info(f"API 스트리밍 호출 시작 - Role: {role}")
            
            response = requests.post(
                self.api_url,
                headers=self.create_headers(),
                json=payload,
                stream=True,
                timeout=10
            )
            
            if response.status_code != 200:
                logger.error(f"API 오류: {response.status_code}")
                yield f"❌ API 오류 ({response.status_code}): {response.text[:200]}"
                return
            
            for line in response.iter_lines():
                if line:
                    line = line.decode('utf-8')
                    if line.startswith("data: "):
                        data = line[6:]
                        if data == "[DONE]":
                            break
                        try:
                            chunk = json.loads(data)
                            if "choices" in chunk and chunk["choices"]:
                                content = chunk["choices"][0].get("delta", {}).get("content", "")
                                if content:
                                    yield content
                        except json.JSONDecodeError:
                            continue
                            
        except requests.exceptions.Timeout:
            yield "⏱️ API 호출 시간이 초과되었습니다. 다시 시도해주세요."
        except requests.exceptions.ConnectionError:
            yield "🔌 API 서버에 연결할 수 없습니다. 인터넷 연결을 확인해주세요."
        except Exception as e:
            logger.error(f"스트리밍 중 오류: {str(e)}")
            yield f"❌ 오류 발생: {str(e)}"

# 시스템 인스턴스 생성
llm_system = LLMCollaborativeSystem()

# 내부 히스토리 관리
internal_history = []

def process_query_streaming(user_query: str):
    """향상된 협업 프로세스를 통한 쿼리 처리"""
    global internal_history
    
    if not user_query:
        return "", "", "", "", "", "❌ 질문을 입력해주세요."
    
    all_responses = {
        "supervisor": [],
        "creator": [],
        "researcher": [],
        "evaluator": [],
        "executor": []
    }
    
    try:
        # 1단계: 감독자 AI 초기 분석
        supervisor_prompt = llm_system.create_supervisor_initial_prompt(user_query)
        supervisor_initial_response = ""
        
        supervisor_text = "[초기 분석] 🔄 생성 중...\n"
        for chunk in llm_system.call_llm_streaming(
            [{"role": "user", "content": supervisor_prompt}], 
            "supervisor"
        ):
            supervisor_initial_response += chunk
            supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_initial_response}"
            yield supervisor_text, "", "", "", "", "🔄 감독자 AI가 분석 중..."
        
        all_responses["supervisor"].append(supervisor_initial_response)
        
        # 2단계: 창조자 AI 혁신적 아이디어 생성
        creator_prompt = llm_system.create_creator_prompt(user_query, supervisor_initial_response)
        creator_response = ""
        
        creator_text = "[혁신 아이디어] 🔄 생성 중...\n"
        for chunk in llm_system.call_llm_streaming(
            [{"role": "user", "content": creator_prompt}], 
            "creator"
        ):
            creator_response += chunk
            creator_text = f"[혁신 아이디어] - {datetime.now().strftime('%H:%M:%S')}\n{creator_response}"
            yield supervisor_text, creator_text, "", "", "", "💡 창조자 AI가 아이디어 생성 중..."
        
        all_responses["creator"].append(creator_response)
        
        # 3단계: 감독자 AI 아이디어 검토 및 조사 지시
        supervisor_review_prompt = llm_system.create_supervisor_ideation_review_prompt(user_query, creator_response)
        supervisor_review_response = ""
        
        supervisor_text += "\n\n---\n\n[아이디어 검토] 🔄 생성 중...\n"
        for chunk in llm_system.call_llm_streaming(
            [{"role": "user", "content": supervisor_review_prompt}], 
            "supervisor"
        ):
            supervisor_review_response += chunk
            temp_text = f"{all_responses['supervisor'][0]}\n\n---\n\n[아이디어 검토] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_review_response}"
            supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
            yield supervisor_text, creator_text, "", "", "", "🎯 감독자 AI가 검토 중..."
        
        all_responses["supervisor"].append(supervisor_review_response)
        
        # 키워드 추출
        keywords = llm_system.extract_keywords(supervisor_review_response)
        logger.info(f"추출된 키워드: {keywords}")
        
        # 4단계: 브레이브 검색 수행
        researcher_text = "[웹 검색] 🔍 검색 중...\n"
        yield supervisor_text, creator_text, researcher_text, "", "", "🔍 웹 검색 수행 중..."
        
        search_results = {}
        total_search_count = 0
        
        for keyword in keywords:
            results = llm_system.brave_search(keyword)
            if results:
                search_results[keyword] = results
                total_search_count += len(results)
                researcher_text += f"✓ '{keyword}' 검색 완료 ({len(results)}개 결과)\n"
                yield supervisor_text, creator_text, researcher_text, "", "", f"🔍 '{keyword}' 검색 중..."
            
            synonyms = llm_system.generate_synonyms(keyword)
            for synonym in synonyms:
                syn_results = llm_system.brave_search(f"{keyword} {synonym}")
                if syn_results:
                    search_results[f"{keyword} ({synonym})"] = syn_results
                    total_search_count += len(syn_results)
                    researcher_text += f"✓ 동의어 '{synonym}' 검색 완료 ({len(syn_results)}개 결과)\n"
                    yield supervisor_text, creator_text, researcher_text, "", "", f"🔍 동의어 '{synonym}' 검색 중..."
        
        researcher_text += f"\n📊 총 {total_search_count}개의 검색 결과 수집 완료\n"
        
        # 5단계: 조사자 AI가 검색 결과 정리
        researcher_prompt = llm_system.create_researcher_prompt(user_query, supervisor_review_response, search_results)
        researcher_response = ""
        
        researcher_text = "[조사 결과 정리] 🔄 생성 중...\n"
        for chunk in llm_system.call_llm_streaming(
            [{"role": "user", "content": researcher_prompt}], 
            "researcher"
        ):
            researcher_response += chunk
            researcher_text = f"[조사 결과 정리] - {datetime.now().strftime('%H:%M:%S')}\n{researcher_response}"
            yield supervisor_text, creator_text, researcher_text, "", "", "📝 조사자 AI가 정리 중..."
        
        all_responses["researcher"].append(researcher_response)
        
        # 6단계: 평가자 AI가 조사 결과 평가
        evaluator_research_prompt = llm_system.create_evaluator_research_prompt(
            user_query, creator_response, researcher_response
        )
        evaluator_research_response = ""
        
        evaluator_text = "[조사 결과 평가] 🔄 생성 중...\n"
        for chunk in llm_system.call_llm_streaming(
            [{"role": "user", "content": evaluator_research_prompt}], 
            "evaluator"
        ):
            evaluator_research_response += chunk
            evaluator_text = f"[조사 결과 평가] - {datetime.now().strftime('%H:%M:%S')}\n{evaluator_research_response}"
            yield supervisor_text, creator_text, researcher_text, evaluator_text, "", "⚖️ 평가자 AI가 평가 중..."
        
        all_responses["evaluator"].append(evaluator_research_response)
        
        # 7단계: 감독자 AI가 실행 지시
        supervisor_execution_prompt = llm_system.create_supervisor_execution_prompt(
            user_query, evaluator_research_response
        )
        supervisor_execution_response = ""
        
        supervisor_text = f"{all_responses['supervisor'][0]}\n\n---\n\n[아이디어 검토] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][1]}\n\n---\n\n[실행 지시] 🔄 생성 중...\n"
        for chunk in llm_system.call_llm_streaming(
            [{"role": "user", "content": supervisor_execution_prompt}], 
            "supervisor"
        ):
            supervisor_execution_response += chunk
            temp_text = f"{all_responses['supervisor'][0]}\n\n---\n\n[아이디어 검토] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][1]}\n\n---\n\n[실행 지시] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_execution_response}"
            supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
            yield supervisor_text, creator_text, researcher_text, evaluator_text, "", "🎯 감독자 AI가 지시 중..."
        
        all_responses["supervisor"].append(supervisor_execution_response)
        
        # 8단계: 실행자 AI가 초기 실행 계획 수립
        full_context = f"""
창조자 AI의 아이디어:
{creator_response}

조사자 AI의 조사 결과:
{researcher_response}

평가자 AI의 평가:
{evaluator_research_response}
"""
        
        executor_prompt = llm_system.create_executor_prompt(
            user_query, supervisor_execution_response, full_context
        )
        executor_response = ""
        
        executor_text = "[초기 실행 계획] 🔄 생성 중...\n"
        for chunk in llm_system.call_llm_streaming(
            [{"role": "user", "content": executor_prompt}], 
            "executor"
        ):
            executor_response += chunk
            executor_text = f"[초기 실행 계획] - {datetime.now().strftime('%H:%M:%S')}\n{executor_response}"
            yield supervisor_text, creator_text, researcher_text, evaluator_text, executor_text, "🔧 실행자 AI가 계획 중..."
        
        all_responses["executor"].append(executor_response)
        
        # 9단계: 평가자 AI가 실행 계획 평가
        evaluator_execution_prompt = llm_system.create_evaluator_execution_prompt(
            user_query, executor_response
        )
        evaluator_execution_response = ""
        
        evaluator_text += "\n\n---\n\n[실행 계획 평가] 🔄 생성 중...\n"
        for chunk in llm_system.call_llm_streaming(
            [{"role": "user", "content": evaluator_execution_prompt}], 
            "evaluator"
        ):
            evaluator_execution_response += chunk
            temp_text = f"{all_responses['evaluator'][0]}\n\n---\n\n[실행 계획 평가] - {datetime.now().strftime('%H:%M:%S')}\n{evaluator_execution_response}"
            evaluator_text = f"[조사 결과 평가] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
            yield supervisor_text, creator_text, researcher_text, evaluator_text, executor_text, "⚖️ 평가자 AI가 검증 중..."
        
        all_responses["evaluator"].append(evaluator_execution_response)
        
        # 10단계: 감독자 AI 최종 지시
        supervisor_final_prompt = llm_system.create_supervisor_final_prompt(
            user_query, evaluator_execution_response
        )
        supervisor_final_response = ""
        
        supervisor_text = f"{all_responses['supervisor'][0]}\n\n---\n\n[아이디어 검토] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][1]}\n\n---\n\n[실행 지시] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][2]}\n\n---\n\n[최종 지시] 🔄 생성 중...\n"
        for chunk in llm_system.call_llm_streaming(
            [{"role": "user", "content": supervisor_final_prompt}], 
            "supervisor"
        ):
            supervisor_final_response += chunk
            temp_text = f"{all_responses['supervisor'][0]}\n\n---\n\n[아이디어 검토] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][1]}\n\n---\n\n[실행 지시] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['supervisor'][2]}\n\n---\n\n[최종 지시] - {datetime.now().strftime('%H:%M:%S')}\n{supervisor_final_response}"
            supervisor_text = f"[초기 분석] - {datetime.now().strftime('%H:%M:%S')}\n{temp_text}"
            yield supervisor_text, creator_text, researcher_text, evaluator_text, executor_text, "🎯 감독자 AI가 최종 검토 중..."
        
        all_responses["supervisor"].append(supervisor_final_response)
        
        # 11단계: 실행자 AI 최종 솔루션
        executor_final_prompt = llm_system.create_executor_final_prompt(
            user_query, executor_response, supervisor_final_response, full_context
        )
        final_executor_response = ""
        
        executor_text += "\n\n---\n\n[최종 실행 솔루션] 🔄 작성 중...\n"
        for chunk in llm_system.call_llm_streaming(
            [{"role": "user", "content": executor_final_prompt}], 
            "executor"
        ):
            final_executor_response += chunk
            temp_text = f"[초기 실행 계획] - {datetime.now().strftime('%H:%M:%S')}\n{all_responses['executor'][0]}\n\n---\n\n[최종 실행 솔루션] - {datetime.now().strftime('%H:%M:%S')}\n{final_executor_response}"
            executor_text = temp_text
            yield supervisor_text, creator_text, researcher_text, evaluator_text, executor_text, "📄 최종 솔루션 작성 중..."
        
        all_responses["executor"].append(final_executor_response)
        
        # 최종 결과 생성
        final_summary = f"""## 🎯 최적화된 실용적 문제 해결 보고서

### 📌 사용자 질문
{user_query}

### 🚀 최종 실행 솔루션
{final_executor_response}

---

<details>
<summary>📋 전체 협력 프로세스 보기</summary>

#### 1️⃣ 거시적 분석 (감독자 AI)
{all_responses['supervisor'][0]}

#### 2️⃣ 혁신적 아이디어 (창조자 AI)
{all_responses['creator'][0]}

#### 3️⃣ 아이디어 검토 및 조사 지시 (감독자 AI)
{all_responses['supervisor'][1]}

#### 4️⃣ 조사 결과 (조사자 AI)
{all_responses['researcher'][0]}

#### 5️⃣ 조사 결과 평가 (평가자 AI)
{all_responses['evaluator'][0]}

#### 6️⃣ 실행 지시 (감독자 AI)
{all_responses['supervisor'][2]}

#### 7️⃣ 초기 실행 계획 (실행자 AI)
{all_responses['executor'][0]}

#### 8️⃣ 실행 계획 평가 (평가자 AI)
{all_responses['evaluator'][1]}

#### 9️⃣ 최종 지시 (감독자 AI)
{all_responses['supervisor'][3]}

</details>

---
*이 보고서는 5개 AI의 협력적 프로세스를 통해 최적화된 실용적 해결책을 제공합니다.*
*프로세스: 감독 → 창조 → 감독 → 조사 → 평가 → 감독 → 실행 → 평가 → 감독 → 실행*"""
        
        internal_history.append((user_query, final_summary))
        
        # 최종 마크다운 반환
        yield supervisor_text, creator_text, researcher_text, evaluator_text, executor_text, final_summary
        
    except Exception as e:
        error_msg = f"❌ 처리 중 오류: {str(e)}"
        yield "", "", "", "", "", error_msg

def clear_all():
    """모든 내용 초기화"""
    global internal_history
    internal_history = []
    return "", "", "", "", "", "🔄 초기화되었습니다."

# Gradio 인터페이스
css = """
.gradio-container {
    font-family: 'Arial', sans-serif;
}
.supervisor-box textarea {
    border-left: 4px solid #667eea !important;
    background-color: #f3f4f6 !important;
}
.creator-box textarea {
    border-left: 4px solid #f59e0b !important;
    background-color: #fffbeb !important;
}
.researcher-box textarea {
    border-left: 4px solid #10b981 !important;
    background-color: #ecfdf5 !important;
}
.evaluator-box textarea {
    border-left: 4px solid #ef4444 !important;
    background-color: #fef2f2 !important;
}
.executor-box textarea {
    border-left: 4px solid #764ba2 !important;
    background-color: #faf5ff !important;
}
"""

with gr.Blocks(title="최적화된 협력적 LLM 시스템", theme=gr.themes.Soft(), css=css) as app:
    gr.Markdown(
        """
        # 🚀 최적화된 최고의 실용적 문제 해결자
        ### 5개 AI의 협력적 프로세스: 감독 → 창조 → 감독 → 조사 → 평가 → 감독 → 실행 → 평가 → 감독 → 실행
        """
    )
    
    # 입력 섹션
    with gr.Row():
        with gr.Column():
            gr.Markdown("""
            ## 🎯 향상된 기능
            - **창조자 AI**: 혁신적이고 파괴적인 아이디어 생성
            - **평가자 AI**: 객관적이고 비판적인 검증 및 평가
            - **강화된 프로세스**: 11단계 협력적 문제 해결
            - **실용성 극대화**: 즉시 실행 가능한 솔루션 제공
            """)
            
            user_input = gr.Textbox(
                label="질문 입력",
                placeholder="예: 우리 회사의 고객 만족도를 획기적으로 향상시킬 수 있는 혁신적인 방법은?",
                lines=3
            )
            
            with gr.Row():
                submit_btn = gr.Button("🚀 분석 시작", variant="primary", scale=2)
                clear_btn = gr.Button("🗑️ 초기화", scale=1)
            
            status_text = gr.Textbox(
                label="상태",
                interactive=False,
                value="대기 중...",
                max_lines=1
            )
    
    # 최종 결과 (상단에 크게 표시)
    with gr.Row():
        with gr.Column():
            with gr.Accordion("📊 최종 실행 솔루션", open=True):
                final_output = gr.Markdown(
                    value="*질문을 입력하면 최종 솔루션이 여기에 표시됩니다.*"
                )
    
    # AI 출력들 - 2줄로 배치
    # 첫 번째 줄: 감독자, 창조자, 조사자
    with gr.Row():
        with gr.Column():
            gr.Markdown("### 🧠 감독자 AI (전략적 지휘)")
            supervisor_output = gr.Textbox(
                label="",
                lines=15,
                max_lines=20,
                interactive=False,
                elem_classes=["supervisor-box"]
            )
        
        with gr.Column():
            gr.Markdown("### 💡 창조자 AI (혁신적 아이디어)")
            creator_output = gr.Textbox(
                label="",
                lines=15,
                max_lines=20,
                interactive=False,
                elem_classes=["creator-box"]
            )
        
        with gr.Column():
            gr.Markdown("### 🔍 조사자 AI (정보 수집)")
            researcher_output = gr.Textbox(
                label="",
                lines=15,
                max_lines=20,
                interactive=False,
                elem_classes=["researcher-box"]
            )
    
    # 두 번째 줄: 평가자, 실행자
    with gr.Row():
        with gr.Column():
            gr.Markdown("### ⚖️ 평가자 AI (객관적 평가)")
            evaluator_output = gr.Textbox(
                label="",
                lines=15,
                max_lines=20,
                interactive=False,
                elem_classes=["evaluator-box"]
            )
        
        with gr.Column():
            gr.Markdown("### 🔧 실행자 AI (실용적 구현)")
            executor_output = gr.Textbox(
                label="",
                lines=15,
                max_lines=20,
                interactive=False,
                elem_classes=["executor-box"]
            )
    
    # 프로세스 다이어그램
    gr.Markdown("""
    ---
    ### 🔄 협업 프로세스 흐름도
    ```
    사용자 질문

    [1] 감독자 AI (초기 분석)

    [2] 창조자 AI (혁신 아이디어)

    [3] 감독자 AI (아이디어 검토)

    [4] 조사자 AI (웹 검색 & 정리)

    [5] 평가자 AI (조사 결과 평가)

    [6] 감독자 AI (실행 지시)

    [7] 실행자 AI (초기 계획)

    [8] 평가자 AI (계획 평가)

    [9] 감독자 AI (최종 지시)

    [10] 실행자 AI (최종 솔루션)

    최적화된 실용적 해결책
    ```
    """)
    
    # 예제
    gr.Examples(
        examples=[
            "우리 회사의 고객 만족도를 획기적으로 향상시킬 수 있는 혁신적인 방법은?",
            "원격 근무 환경에서 팀 생산성을 2배로 높이는 구체적인 전략은?",
            "스타트업이 6개월 내에 수익을 3배 늘릴 수 있는 실행 가능한 방법은?",
            "기존 제품을 완전히 혁신하여 시장을 선도할 수 있는 아이디어는?",
            "AI를 활용해 운영 비용을 50% 절감하는 실질적인 방안은?"
        ],
        inputs=user_input,
        label="💡 예제 질문"
    )
    
    # 이벤트 핸들러
    submit_btn.click(
        fn=process_query_streaming,
        inputs=[user_input],
        outputs=[supervisor_output, creator_output, researcher_output, evaluator_output, executor_output, final_output]
    ).then(
        fn=lambda: "",
        outputs=[user_input]
    )
    
    user_input.submit(
        fn=process_query_streaming,
        inputs=[user_input],
        outputs=[supervisor_output, creator_output, researcher_output, evaluator_output, executor_output, final_output]
    ).then(
        fn=lambda: "",
        outputs=[user_input]
    )
    
    clear_btn.click(
        fn=clear_all,
        outputs=[supervisor_output, creator_output, researcher_output, evaluator_output, executor_output, status_text]
    )

if __name__ == "__main__":
    app.queue()
    app.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True,
        show_error=True
    )