-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.py
1375 lines (1270 loc) · 79.1 KB
/
main.py
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
'''
整个流程
1. 初始化Character、Environment、阵营
2. 竞争阶段
3. 合作阶段
4. reflection阶段
5. 结算阶段
'''
import collections
import json
from character.all_character_class import AllCharacter
from environment.all_resource_class import AllResource
from environment.action_history_class import ActionHistory, Action
import os
from config import *
from logger_class import Logger
def verify_constrained_action(gpt_response, action_candidates:list)->bool:
action_candidates = [str(i) for i in action_candidates]
gpt_response = str(gpt_response)
if debug:
print('='*20+'DEBUG START'+'='*20)
print('='*19+'VERIFICATION'+'='*19)
print()
print(action_candidates)
print()
print('='*19+'GPT RESPONSE'+'='*19)
print()
print(gpt_response)
print()
print('='*15+'VERIFICATION RESULT'+'='*15)
print()
print(gpt_response in action_candidates)
print()
print('='*21+'DEBUG END'+'='*21)
if gpt_response not in action_candidates:
return False
else:
return True
def succession_winner(defender_id_number, character_vote_dict)->list:
defender_chosen_id_number = character_vote_dict[defender_id_number]
if defender_chosen_id_number != defender_id_number:
return defender_chosen_id_number
vote_list = []
for key, vote_for in character_vote_dict.items():
vote_list.append(vote_for)
vote_dict = collections.Counter(vote_list)
winner = []
winner_get_vote = -1
for character_id_number, get_vote in vote_dict.items():
if get_vote > winner_get_vote:
winner_get_vote = get_vote
winner = []
winner.append(character_id_number)
if type(winner) != list:
winner = [winner]
return winner
class AgentGroupChat:
def __init__(self,
all_round_number: int,
private_chat_round: int = 3,
meeting_chat_round: int = 3,
group_chat_round: int = 3,
save_folder=None,
test_folder=None,
human_input=None,
logger=None):
'''
初始化游戏环境
Input:
all_round_number: int, 游戏总轮数
private_chat_round: int, 每次对抗阶段对话总共有几轮
meeting_chat_round: int, 每次合作阶段对话总共有几轮
save_folder: str 存档地址
human_input: str 人类输入
logger: Logger 是否需要直接输入一个Logger
Output:
None
'''
self.all_round_number = all_round_number
self.private_chat_round = private_chat_round
self.meeting_chat_round = meeting_chat_round
self.group_chat_round = group_chat_round
if not logger:
self.logger = Logger()
else:
self.logger = logger
self.log_file_name = self.logger.log_file
self.save_folder = save_folder
self.test_folder = test_folder
if save_folder:
self.initialize(save_folder)
# 赋予NPC社会影响力
for index, resource in enumerate(self.resources.get_all_resource()):
owner_id_number = resource.owner
self.characters.get_character_by_id(owner_id_number).give_influence(resource.influence)
else:
self.characters = AllCharacter(logger=self.logger)
self.resources = AllResource()
self.rule_setting = ''
self.action_history = ActionHistory
def initialize(self, save_folder) -> None:
'''
初始化Logger、Character、Resources、RuleSetting、ActionHistory
Input:
save_folder: 存档数据存放的位置
Output:
None
'''
self.logger.gprint('### Initializing Directory Found: ', save_folder)
basic_setting = json.load(open(os.path.join(save_folder, 'basic_setting.json'), encoding='utf-8'))
self.rule_setting_file_name = basic_setting['rule_setting']
self.finished_states = basic_setting['finished_states']
if basic_setting['log_file_name']:
self.logger.read_save_file(basic_setting['log_file_name'], False)
self.characters = AllCharacter(os.path.join(save_folder, 'characters'), logger=self.logger)
self.resources = AllResource(os.path.join(save_folder, 'resources'))
self.rule_setting = open(self.rule_setting_file_name, encoding='utf-8').read()
self.action_history = ActionHistory(os.path.join(save_folder, 'action_history'), os.path.join(save_folder, 'basic_setting.json'))
self.logger.gprint('### Number of initialized roles: ', len(self.characters.get_all_characters()))
self.logger.gprint('### Number of main roles: ', len(self.characters.main_characters_id_number))
self.logger.gprint('### Number of initialized resources: ', len(self.resources.get_all_resource()))
self.logger.gprint('### Number of initialized action history: ',
len(self.action_history.get_all_action_history()))
def switch_state(self):
self.state_index = 0
all_state = ['']
def save(self, save_folder) -> None:
'''
保存环境
Input:
save_folder: 存放地址
Output:
None
'''
if not os.path.exists(save_folder):
os.makedirs(save_folder)
config_file = open('config.py', encoding='utf-8')
basic_setting = {}
for line in config_file:
line = line.split('#')[0]
if '=' in line:
key, value = [i.strip() for i in line.split('=')]
basic_setting['config_file_'+key] = value
basic_setting['rule_setting'] = self.rule_setting_file_name
basic_setting['finished_states'] = self.finished_states
basic_setting['log_file_name'] = self.log_file_name
save_characters_folder = os.path.join(save_folder, 'characters')
save_resources_folder = os.path.join(save_folder, 'resources')
save_action_history_folder = os.path.join(save_folder, 'action_history')
open(os.path.join(save_folder, 'basic_setting.json'), 'w', encoding='utf-8').write(json.dumps(basic_setting,
indent=4,
ensure_ascii=False))
self.logger.gprint('Save basic_setting.json to: ' + str(os.path.join(save_folder, 'basic_setting.json')))
for character in self.characters.get_all_characters(): character.save(save_characters_folder)
self.logger.gprint('Save self.character to: ' + str(save_characters_folder))
for resource in self.resources.get_all_resource(): resource.save(save_resources_folder)
self.action_history.save(save_action_history_folder)
self.logger.gprint('Save self.action_history to: ' + str(save_action_history_folder))
def new_character_insert(self):
'''
插入新角色
Input:
待定
Output:
待定
'''
pass
def new_resource_insert(self):
'''
插入新的资源
Input:
xxx
Output:
xxx
'''
pass
def new_action_insert(self, new_action: list, now_round_number: int):
'''
插入新的行为
Input:
new_action: list [source_character_id_number:str, target_character_id_number:str, action_type:str, action:str]
now_round_number: int
Output:
None
'''
action = Action(-1, new_action[0], new_action[1], new_action[2], new_action[3], now_round_number)
action_index = self.action_history.insert_action(action)
return action_index
def get_rule_setting(self):
'''
返回Rule Setting
Input:
None
Output:
None
'''
return self.rule_setting
def get_all_resource_description(self):
'''
返回所有资源的描述
Input:
None
Output:
None
'''
return self.resources.get_description()
def get_all_character_list(self):
'''
返回所有角色列表
Input:
None
Output:
None
'''
return self.characters.get_characters_description_except_some()
def get_round_description(self, now_round_number: int, private=False, simple=False) -> str:
'''
得到一些关于当前轮数和总轮数的描述信息
Input:
now_round_number: int, 当前游戏进行到哪一轮
private: bool, 当前轮是否处于对抗阶段
Output:
round_description: str
'''
round_description = ''
round_description += 'The game takes a total of %d rounds.\n' % self.all_round_number
round_description += 'The current game is played to round %d.\n' % (now_round_number + 1)
if simple:
return round_description
if private:
round_description += 'You are in the private chatting stage, the stage where you meet with anyone without anyone else knowing about it.\n'
else:
round_description += 'You are in the confidential meeting stage, the stage where what you meet with someone will be known to everyone, but they won\'t know what you talked about.\n'
round_description += 'You\'ll talk to your chosen character for %d rounds per round.\n' % (
self.private_chat_round if private else self.meeting_chat_round)
return round_description
def get_groupchat_round_description(self, now_round_number, now_chat_round):
round_description = self.get_round_description(now_round_number, simple=True)
round_description += 'You are in a group chat and what you say will be visible to all characters.\n'
round_description += 'A total of %d rounds of group chat are taking place, and you are currently in the %d round.'%(self.group_chat_round, now_chat_round)
return round_description
def group_chatting_stage(self, now_round_number:int)->None:
'''
进入宣言阶段
Input:
now_round_number: int,
Output:
None
'''
# 所有角色的介绍
candidates = ['%s: %s' % (character.get_id_number(), character.get_short_description()) for character in
self.characters.get_all_characters()]
candidates = '\n'.join(candidates)
# 一轮群聊的内容,下一轮才能给所有人看
round_action_history = collections.defaultdict(list)
# 设置多一轮循环,可以把所有action都插入action history
for now_chat_round in range(self.group_chat_round+1):
# 当前轮数介绍
round_description = self.get_groupchat_round_description(now_round_number,
now_chat_round=now_chat_round+1)
# 把上轮群聊的内容放入action history
if now_chat_round-1 in round_action_history:
for new_action, character in round_action_history[now_chat_round-1]:
state_UID = 'NOW_ROUND:%d+ACTION:%s+CHARACTER:%s' % (now_round_number, 'ANNOUNCEMENT', character.id_number)
if state_UID in self.finished_states: continue
action_index = self.new_action_insert(new_action, now_round_number)
self.finished_states[state_UID] = [action_index]
if self.test_folder:
self.save(self.test_folder)
# 多的循环终止掉
if now_chat_round >= self.group_chat_round: break
# 主要角色按照影响力大小依次行动
for character in self.characters.character_list:
action_history = self.action_history.get_description(character_id_number=character.id_number, max_num=ACTIONHISTORY_RETRIEVE_NUM_ANNOUNCEMENT)
# ======================================================================================= #
# 调用GPT
# 不需要校验
# ======================================================================================= #
speech, reasoning_process = character.groupchat(action_history,
candidates,
self.resources.get_description(),
round_description,
)
# ======================================================================================= #
# 打日志
speech = 'Game Round %d, Chat Round %d, group chat that character %s makes to all the other characters: %s' % (now_round_number+1, now_chat_round+1, character.id_number, speech)
self.logger.gprint(thought=reasoning_process,
important_log='important_log',
source_character=character.id_number,
target_character=character.id_number,
log_type='Open Speech In Round',
log_content=speech)
# 记录action
new_action = [character.id_number, character.id_number, '### SPEECH_NORMAL', speech]
round_action_history[now_chat_round].append((new_action, character))
def private_chatting_stage(self, now_round_number: int) -> None:
'''
对抗阶段——所有MC根据自身的影响力大小依次行动,选择一个不同阵营的character进行对话
Input:
now_round_number: int, 当前轮数
Output:
None
'''
round_description = self.get_round_description(now_round_number, private=True)
main_character_influence = self.characters.get_main_character_influence()
# 主要角色按照影响力大小依次行动
for main_character_id_number in main_character_influence:
state_UID = 'NOW_ROUND:%d+ACTION:%s+CHARACTER:%s'%(now_round_number, 'COMPETE', main_character_id_number)
if state_UID in self.finished_states: continue
action_index = []
# 获得行动的主要角色
main_character = self.characters.get_character_by_id(main_character_id_number)
self.logger.gprint(thought='',
important_log='important_log',
source_character=main_character.id_number,
target_character=main_character.id_number,
log_type='Action stage',
log_content='Confrontation stage'
)
main_character_action_history_description = self.action_history.get_description(main_character_id_number, max_num=ACTIONHISTORY_RETRIEVE_NUM_COMPETE)
# ======================================================================================= #
# 调用GPT
# 不需要校验
# ======================================================================================= #
# 让角色perceive环境,并生成总结
main_character_environment_summary = main_character.perceive(self.rule_setting,
self.resources.get_description(),
main_character_action_history_description,
self.all_round_number
)
# ======================================================================================= #
self.logger.gprint(thought='',
important_log='important_log',
source_character=main_character.id_number,
target_character=main_character.id_number,
log_type='Conclusion of environment',
log_content=main_character_environment_summary)
candidates_list = '\n'.join(['%s: %s' % (candidate.id_number, candidate.get_short_description())
for candidate in self.characters.get_all_characters() if
(candidate.id_number != main_character.id_number)]) # 剔除自己
# 如果没有候选人,则跳过
if not candidates_list: continue
# ======================================================================================= #
# 调用GPT
# 需要校验
# ======================================================================================= #
# 从候选人中,确定需要对话的具体角色
verify_result = ERROR_RETRY_TIMES
while verify_result > 0:
candidates = [candidate.id_number for candidate in self.characters.get_all_characters() if
candidate.id_number != main_character.id_number]
action_space, thought, plan, chosen_character_id_number = main_character.choose(main_character_environment_summary,
round_description,
main_character_action_history_description,
candidates_list,
self.private_chat_round,
requirement_list=candidates)
if verify_constrained_action(chosen_character_id_number, candidates):
verify_result = -10
else:
verify_result -= 1
self.logger.gprint('ERROR! Log does not meet the requirements: ', gpt_response=chosen_character_id_number, candidates=candidates)
if verify_result == 0:
raise Exception('Log does not meet the requirements.')
# 评估事件
evaluation_event = [main_character.id_number,
main_character.id_number,
'### EVALUATION ACTION SPACE',
'agent response: %s[SEP]ground truth: %s' % (str(action_space),
str(candidates))]
new_action_index = self.new_action_insert(evaluation_event, now_round_number)
action_index.append(new_action_index)
# ======================================================================================= #
chosen_character = self.characters.get_character_by_id(chosen_character_id_number)
chosen_character_action_history_description = self.action_history.get_description(chosen_character_id_number, max_num=ACTIONHISTORY_RETRIEVE_NUM_COMPETE)
chosen_character_environment_summary = chosen_character.perceive(self.rule_setting,
self.resources.get_description(),
chosen_character_action_history_description,
self.all_round_number)
self.logger.gprint(thought='',
important_log='important_log',
source_character=chosen_character.id_number,
target_character=chosen_character.id_number,
log_type='Conclusion of environment',
log_content=chosen_character_environment_summary)
self.logger.gprint(thought=thought,
important_log='important_log',
source_character=main_character.id_number,
target_character=chosen_character.id_number,
log_type='Select dialogue role',
log_content='')
# 生成对话事件,标记为### MEET,所有角色可见
# action_event = [main_character.id_number, chosen_character.id_number, '### MEET',
# "%s chat with %s in round %d, but others don't know what they are talking about." % (main_character.id_number, chosen_character.id_number, now_round_number)]
# meet_action_index = self.new_action_insert(action_event, now_round_number)
# action_index.append(meet_action_index)
# 选择对话轮数——目前是规则限制好,就对话这么些轮数
chat_round = private_chat_round
chat_history = ''
for now_chat_round in range(chat_round):
# ======================================================================================= #
# 调用GPT
# 不需要校验
# ======================================================================================= #
# 对话
number_of_action_history, thought, action_event = main_character.facechat(target_candidate_id_number=chosen_character.id_number,
target_character_description=chosen_character.get_short_description(),
environment_description=main_character_environment_summary,
action_history_description=main_character_action_history_description,
chat_history=chat_history,
plan=plan)
evaluation_event = [main_character.id_number,
main_character.id_number,
'### EVALUATION ACTION HISTORY',
'agent response: %s[SEP]ground truth: %s' % (str(number_of_action_history),
str(len([i for i in main_character_action_history_description.split('\n') if i])))]
new_action_index = self.new_action_insert(evaluation_event, now_round_number)
action_index.append(new_action_index)
# ======================================================================================= #
# 生成对话历史
chat_history += action_event[-1] + '\n'
new_action_index = self.new_action_insert(action_event, now_round_number)
action_index.append(new_action_index)
self.logger.gprint(thought=thought,
important_log='important_log',
source_character=main_character.id_number,
target_character=chosen_character.id_number,
log_type='Dialogue content',
log_content=action_event[-1])
# ======================================================================================= #
# 调用GPT
# 不需要校验
# ======================================================================================= #
# 对话
number_of_action_history, thought, action_event = chosen_character.facechat(target_candidate_id_number=main_character.id_number,
target_character_description=main_character.get_short_description(),
environment_description=chosen_character_environment_summary,
action_history_description=chosen_character_action_history_description,
chat_history=chat_history)
evaluation_event = [main_character.id_number,
main_character.id_number,
'### EVALUATION ACTION HISTORY',
'agent response: %s[SEP]ground truth: %s' % (str(number_of_action_history),
str(len([i for i in chosen_character_action_history_description.split('\n') if i])))]
new_action_index = self.new_action_insert(evaluation_event, now_round_number)
action_index.append(new_action_index)
# ======================================================================================= #
# 生成对话历史
chat_history += action_event[-1] + '\n'
new_action_index = self.new_action_insert(action_event, now_round_number)
action_index.append(new_action_index)
self.logger.gprint(thought=thought,
important_log='important_log',
source_character=chosen_character.id_number,
target_character=main_character.id_number,
log_type='Dialogue content',
log_content=action_event[-1])
# ======================================================================================= #
# 调用GPT
# 不需要校验
# ======================================================================================= #
# 双方各自总结对话内容
for index, character in enumerate([main_character, chosen_character]):
environment_summary = [main_character_environment_summary, chosen_character_environment_summary][index]
number_of_chat_round, thought, action_event = character.summarize(environment_description=environment_summary,
chat_history=chat_history)
evaluation_event = [character.id_number,
character.id_number,
'### EVALUATION CHAT ROUND',
'agent response: %s[SEP]ground truth: %s' %
(str(number_of_chat_round), str(chat_round))]
new_action_index = self.new_action_insert(evaluation_event, now_round_number)
action_index.append(new_action_index)
new_action_index = self.new_action_insert(action_event, now_round_number)
action_index.append(new_action_index)
self.logger.gprint(thought=thought,
important_log='important_log',
source_character=character.id_number,
target_character=[main_character, chosen_character][(index+1)%2].id_number,
log_type='Dialogue Summarization',
log_content=action_event[3])
self.finished_states[state_UID] = action_index
if self.test_folder:
self.save(self.test_folder)
def confidential_meeting_stage(self, now_round_number: int):
'''
合作阶段——所有MC根据自身的影响力大小依次行动,选择一个同阵营的character进行对话
如果没有同阵营的角色,则跳过该MC
Input:
now_round_number: int, 当前轮数
Output:
None
'''
round_description = self.get_round_description(now_round_number, private=False)
main_character_influence = self.characters.get_main_character_influence()
# 主要角色按照影响力大小依次行动
for main_character_id_number in main_character_influence:
state_UID = 'NOW_ROUND:%d+ACTION:%s+CHARACTER:%s'%(now_round_number, 'COLLABORATE', main_character_id_number)
if state_UID in self.finished_states: continue
action_index = []
# 获得行动的主要角色
main_character = self.characters.get_character_by_id(main_character_id_number)
main_character_action_history_description = self.action_history.get_description(main_character_id_number, max_num=ACTIONHISTORY_RETRIEVE_NUM_COLLABORATE)
self.logger.gprint(thought='',
important_log='important_log',
source_character=main_character.id_number,
target_character=main_character.id_number,
log_type='Action stage',
log_content='Cooperation stage'
)
# ======================================================================================= #
# 调用GPT
# 不需要校验
# ======================================================================================= #
# 让角色perceive环境,并生成总结
main_character_environment_summary = main_character.perceive(self.rule_setting,
self.resources.get_description(),
main_character_action_history_description,
self.all_round_number)
# ======================================================================================= #
self.logger.gprint(thought='',
important_log='important_log',
source_character=main_character.id_number,
target_character=main_character.id_number,
log_type='Conclusion of environment',
log_content=main_character_environment_summary)
# 确定可以对话的候选人
# candidates_list = '\n'.join(['%s: %s' % (candidate.id_number, candidate.get_short_description())
# for candidate in self.characters.get_all_characters() if
# (candidate.id_number != main_character.id_number and # 剔除自己
# candidate.get_support_character() == main_character.id_number)]) # 选择同阵营的人
candidates_list = '\n'.join(['%s: %s' % (candidate.id_number, candidate.get_short_description())
for candidate in self.characters.get_all_characters() if
(candidate.id_number != main_character.id_number)]) # 剔除自己
# candidates_list = '\n'.join(['%s: %s' % (candidate.id_number, candidate.get_short_description())
# for candidate in self.characters.get_all_characters()])
# 如果没有候选人,则跳过
if not candidates_list: continue
# ======================================================================================= #
# 调用GPT
# 需要校验
# ======================================================================================= #
# 从候选人中,确定需要对话的具体角色
verify_result = ERROR_RETRY_TIMES
while verify_result > 0:
candidates = [candidate.id_number for candidate in self.characters.get_all_characters() if
candidate.id_number != main_character.id_number]
action_space, thought, plan, chosen_character_id_number = main_character.choose(main_character_environment_summary,
round_description,
main_character_action_history_description,
candidates_list,
self.meeting_chat_round,
requirement_list=candidates)
if verify_constrained_action(chosen_character_id_number, candidates):
verify_result = -100
else:
verify_result -= 1
self.logger.gprint('ERROR! Log does not meet the requirements: ', gpt_response=chosen_character_id_number, candidates=candidates)
if verify_result == 0:
raise Exception('Log does not meet the requirements.')
# 评估事件
evaluation_event = [main_character.id_number,
main_character.id_number,
'### EVALUATION ACTION SPACE',
'agent response: %s[SEP]ground truth: %s' % (str(action_space),
str(candidates))]
new_action_index = self.new_action_insert(evaluation_event, now_round_number)
action_index.append(new_action_index)
chosen_character_action_history_description = self.action_history.get_description(chosen_character_id_number, max_num=ACTIONHISTORY_RETRIEVE_NUM)
# ======================================================================================= #
chosen_character = self.characters.get_character_by_id(chosen_character_id_number)
# ======================================================================================= #
# 调用GPT
# 不需要校验
# ======================================================================================= #
chosen_character_environment_summary = chosen_character.perceive(self.rule_setting,
self.resources.get_description(),
chosen_character_action_history_description,
self.all_round_number)
# ======================================================================================= #
self.logger.gprint(thought='',
important_log='important_log',
source_character=chosen_character.id_number,
target_character=chosen_character.id_number,
log_type='Conclusion of environment',
log_content=chosen_character_environment_summary)
self.logger.gprint(thought=thought,
important_log='important_log',
source_character=main_character.id_number,
target_character=chosen_character.id_number,
log_type='Select dialogue role',
log_content='')
# 生成对话事件,标记为### MEET,所有角色可见
action_event = [main_character.id_number, chosen_character.id_number, '### MEET',
"%s chat with %s in round %d, but others don't know what they are talking about." % (main_character.id_number, chosen_character.id_number, now_round_number)]
meet_action_index = self.new_action_insert(action_event, now_round_number)
action_index.append(meet_action_index)
# 选择对话轮数——目前是规则限制好,就对话这么些轮数
chat_round = meeting_chat_round
chat_history = ''
for now_chat_round in range(chat_round):
# ======================================================================================= #
# 调用GPT
# 不需要校验
# ======================================================================================= #
# 对话
number_of_action_history, thought, action_event = main_character.facechat(target_candidate_id_number=chosen_character.id_number,
target_character_description=chosen_character.get_short_description(),
environment_description=main_character_environment_summary,
action_history_description=main_character_action_history_description,
chat_history=chat_history,
plan=plan)
evaluation_event = [main_character.id_number,
main_character.id_number,
'### EVALUATION ACTION HISTORY',
'agent response: %s[SEP]ground truth: %s' % (str(number_of_action_history),
str(len([i for i in main_character_action_history_description.split('\n') if i])))]
new_action_index = self.new_action_insert(evaluation_event, now_round_number)
action_index.append(new_action_index)
# ======================================================================================= #
# 生成对话历史
chat_history += action_event[-1] + '\n'
converse_action_index = self.new_action_insert(action_event, now_round_number)
action_index.append(converse_action_index)
self.logger.gprint(thought=thought,
important_log='important_log',
source_character=main_character.id_number,
target_character=chosen_character.id_number,
log_type='Dialogue content',
log_content=action_event[-1])
# ======================================================================================= #
# 调用GPT
# 不需要校验
# ======================================================================================= #
# 对话
number_of_action_history, thought, action_event = chosen_character.facechat(target_candidate_id_number=main_character.id_number,
target_character_description=main_character.get_short_description(),
environment_description=chosen_character_environment_summary,
action_history_description=chosen_character_action_history_description,
chat_history=chat_history)
evaluation_event = [chosen_character.id_number,
chosen_character.id_number,
'### EVALUATION ACTION HISTORY',
'agent response: %s[SEP]ground truth: %s' % (str(number_of_action_history),
str(len([i for i in chosen_character_action_history_description.split('\n') if i])))]
new_action_index = self.new_action_insert(evaluation_event, now_round_number)
action_index.append(new_action_index)
# ======================================================================================= #
# 生成对话历史
chat_history += action_event[-1] + '\n'
converse_action_index = self.new_action_insert(action_event, now_round_number)
action_index.append(converse_action_index)
self.logger.gprint(thought=thought,
important_log='important_log',
source_character=chosen_character.id_number,
target_character=main_character.id_number,
log_type='Dialogue content',
log_content=action_event[-1])
# ======================================================================================= #
# 调用GPT
# 不需要校验
# ======================================================================================= #
# 双方各自总结对话内容
for index, character in enumerate([main_character, chosen_character]):
environment_summary = [main_character_environment_summary, chosen_character_environment_summary][index]
number_of_chat_round, thought, action_event = character.summarize(environment_description=environment_summary,
chat_history=chat_history)
evaluation_event = [character.id_number,
character.id_number,
'### EVALUATION CHAT ROUND',
'agent response: %s[SEP]ground truth: %s' %
(str(number_of_chat_round), str(chat_round))]
new_action_index = self.new_action_insert(evaluation_event, now_round_number)
action_index.append(new_action_index)
new_action_index = self.new_action_insert(action_event, now_round_number)
action_index.append(new_action_index)
self.logger.gprint(thought=thought,
important_log='important_log',
source_character=character.id_number,
target_character=[main_character, chosen_character][(index+1)%2].id_number,
log_type='Dialogue Summarization',
log_content=action_event[3])
self.finished_states[state_UID] = action_index
if self.test_folder:
self.save(self.test_folder)
def update_stage(self, now_round_number):
'''
更新阶段
Input:
now_round_number: Union[str, int], 当前游戏进行轮数
Output:
None
'''
for character in self.characters.character_list:
state_UID = 'NOW_ROUND:%d+ACTION:%s+CHARACTER:%s'%(now_round_number, 'UPDATE', character.id_number)
if state_UID in self.finished_states: continue
self.finished_states[state_UID] = []
candidates_list = '\n'.join(['%s: %s' % (candidate.id_number, candidate.get_short_description())
for candidate in self.characters.get_all_characters() if candidate.id_number != character.id_number])
candidates_id_number_list = [candidate.id_number for candidate in self.characters.get_all_characters() if candidate.id_number != character.id_number]
self.logger.gprint(thought='',
important_log='important_log',
source_character=character.id_number,
target_character=character.id_number,
log_type='Action stage',
log_content='Update stage'
)
# ======================================================================================= #
# 调用GPT
# 需要校验
# ======================================================================================= #
verify_result = ERROR_RETRY_TIMES
while verify_result >= 0:
if verify_result == 0:
raise Exception('Log does not meet the requirements.')
len_relationship_change=len([candidate.id_number for candidate in self.characters.get_all_characters() if candidate.id_number != character.id_number])
reflect_thought, relationship_change, belief_change, judgement_change = character.update_relation_judgement(
all_action_description=self.action_history.get_description(character.id_number,[int(now_round_number)], max_num=ACTIONHISTORY_RETRIEVE_NUM_UPDATE),
all_character_description=candidates_list,
len_relationship_change=len_relationship_change
)
retry = False
# 格式校验
try:
if ':' in relationship_change[0]:
relationship_change = [int(i.split(':')[-1]) for i in relationship_change]
elif ':' in relationship_change[0]:
relationship_change = [int(i.split(':')[-1]) for i in relationship_change]
else:
relationship_change = [int(i) for i in relationship_change]
except:
verify_result -= 1
self.logger.gprint('ERROR! Log does not meet the requirements: ', gpt_response=relationship_change, candidates='+5, -6, xxxx')
retry = True
# 格式校验
if not retry:
try:
if ':' in belief_change[0]:
belief_change = [int(i.split(':')[-1]) for i in belief_change]
elif ':' in belief_change[0]:
belief_change = [int(i.split(':')[-1]) for i in belief_change]
else:
belief_change = [int(i) for i in belief_change]
except:
verify_result -= 1
self.logger.gprint('ERROR! Log does not meet the requirements: ', gpt_response=belief_change, candidates='+5, -6, xxxx')
retry = True
# 长度evaluation
if not retry:
new_evaluation_event = [character.id_number,
character.id_number,
'### EVALUATION RELATIONSHIP LENGTH',
'agent response: %s[SEP]ground truth: %s' % (len(relationship_change),
len([candidate.id_number for
candidate in
self.characters.get_all_characters()
if
candidate.id_number != character.id_number]))]
action_index = self.new_action_insert(new_evaluation_event, now_round_number)
self.finished_states[state_UID].append(action_index)
# 长度evaluation
new_evaluation_event = [character.id_number,
character.id_number,
'### EVALUATION BELIEF LENGTH',
'agent response: %s[SEP]ground truth: %s' % (len(belief_change),
len(character.belief))]
action_index = self.new_action_insert(new_evaluation_event, now_round_number)
self.finished_states[state_UID].append(action_index)
try:
# 值域evaluation
new_evaluation_event = [character.id_number,
character.id_number,
'### EVALUATION RELATIONSHIP VALUE',
'agent response: %s[SEP]ground truth: %s' % (str([int(i) for i in relationship_change]),
str([max(min(int(i), MAX_RELATION_SCORE_CHANGE),-MAX_RELATION_SCORE_CHANGE) for i in relationship_change]))]
except:
# 值域evaluation
new_evaluation_event = [character.id_number,
character.id_number,
'### EVALUATION RELATIONSHIP VALUE',
'agent response: %s[SEP]ground truth: %s' % (
str([int(i) for i in relationship_change]),'ERROR FORMAT')]
action_index = self.new_action_insert(new_evaluation_event, now_round_number)
self.finished_states[state_UID].append(action_index)
# 值域evaluation
try:
new_evaluation_event = [character.id_number,
character.id_number,
'### EVALUATION BELIEF VALUE',
'agent response: %s[SEP]ground truth: %s' % (str([int(i) for i in belief_change]),
str([max(min(int(i), MAX_BELIEF_SCORE_CHANGE),-MAX_BELIEF_SCORE_CHANGE) for i in belief_change]))]
except:
new_evaluation_event = [character.id_number,
character.id_number,
'### EVALUATION BELIEF VALUE',
'agent response: %s[SEP]ground truth: %s' % (
str([int(i) for i in belief_change]),'ERROR FORMAT')]
action_index = self.new_action_insert(new_evaluation_event, now_round_number)
self.finished_states[state_UID].append(action_index)
if retry: continue
# 对relationship_change进行校验
# 长度校验
if not len(relationship_change) == len([candidate.id_number for candidate in self.characters.get_all_characters() if candidate.id_number != character.id_number]):
verify_result -= 1
self.logger.gprint('ERROR! Log does not meet the requirements: ', gpt_response=relationship_change, candidates='len(relationship_change) == %d != %d'%(len(relationship_change),len([candidate.id_number for candidate in self.characters.get_all_characters() if candidate.id_number != character.id_number])))
continue
# 对Belief_change进行校验
# 长度校验
if not len(belief_change) == len(character.belief):
verify_result -= 1
self.logger.gprint('ERROR! Log does not meet the requirements: ', gpt_response=belief_change, candidates='len(belief_change) == %d'%len(character.belief))
continue
verify_result = -10
# ======================================================================================= #
# 更新信念
for belief, item in zip(character.belief, belief_change):
character.belief[belief] += item
character.belief[belief] = max(character.belief[belief], MIN_BELIEF_SCORE) # 判断最小值
character.belief[belief] = min(character.belief[belief], MAX_BELIEF_SCORE) # 判断最大值
self.logger.gprint(thought='',
important_log='important_log',
source_character=character.id_number,
target_character=belief,
log_type='Belief update',
log_content=character.belief[belief])
# 更新关系分数
for target_character_id_number, change_score in zip(candidates_id_number_list, relationship_change):
if target_character_id_number not in character.relation:
character.relation[target_character_id_number] = INITIAL_RELATION_SCORE
character.relation[target_character_id_number] += change_score
character.relation[target_character_id_number] = max(character.relation[target_character_id_number],
MIN_RELATION_SCORE) # 判断最小值
character.relation[target_character_id_number] = min(character.relation[target_character_id_number],
MAX_RELATION_SCORE) # 判断最大值
self.logger.gprint(thought='',
important_log='important_log',
source_character=character.id_number,
target_character=target_character_id_number,
log_type='Relation update',
log_content=character.relation[target_character_id_number])
# 更新判断分数
for source_character_id_number, target_character_N_change_score in judgement_change.items():
if source_character_id_number not in character.judgement:
character.judgement[source_character_id_number] = {}
for target_character_id_number, change_score in target_character_N_change_score.items():
if target_character_id_number not in character.judgement:
character.judgement[source_character_id_number][
target_character_id_number] = INITIAL_RELATION_SCORE
character.judgement[source_character_id_number][target_character_id_number] += change_score
# 根据关系分数更新支持者
support_character_id_number = 'None'
support_relation_score = character.min_support_relation_score - 1
for target_character_id_number in character.relation:
relation_score = character.relation[target_character_id_number]
if relation_score >= character.min_support_relation_score and relation_score > support_relation_score:
support_character_id_number = target_character_id_number
support_relation_score = relation_score
self.logger.gprint(thought='',
important_log='important_log',
source_character=character.id_number,
target_character=support_character_id_number,
log_type='Support update',
log_content=support_character_id_number)
character.support_character = support_character_id_number
# 生成新的事件
new_action = [character.id_number, character.id_number, '### REFLECTION', "A reflection result of %s in Round %d: %s" %(character.id_number, now_round_number, reflect_thought)]
action_index = self.new_action_insert(new_action, now_round_number)
self.logger.gprint(thought='',
important_log='important_log',
source_character=character.id_number,
target_character=character.id_number,
log_type='Relation status',
log_content=character.relation)
self.logger.gprint(thought='',
important_log='important_log',
source_character=character.id_number,
target_character=character.id_number,
log_type='Environment judgement',
log_content=character.judgement)
self.logger.gprint(thought=reflect_thought,
important_log='important_log',
source_character=character.id_number,
target_character=character.id_number,
log_type='Reflection result',
log_content=reflect_thought)
# Reflection
self.finished_states[state_UID].append(action_index)
if self.test_folder:
self.save(self.test_folder)
self.characters.get_influence_for_main_character()
def succession_settlement(self, whole_information):
'''
针对于继承之战的结算,每个角色可以发言一次,然后再进行投票
Input:
whole_information: bool, 让Agent知道全局信息还是局部信息?
Output:
character_vote_dict: dict 每个角色投票给谁
character_vote_others: 每个角色除了自己,投票给谁
'''
# 所有角色的投票情况
character_vote_dict = {}
character_vote_others = {}
# 所有角色的介绍
candidates = ['%s: %s' % (character.get_id_number(), character.get_short_description()) for character in
self.characters.get_all_characters() if character.main_character]
candidates = '\n'.join(candidates)
# 设置背景信息
action_history = ''
background_information = 'Under the condition that the Agent knows only the actions it should know.'
if whole_information:
background_information = 'Under the condition that the Agent knows only the actions it should know.'
action_history = self.action_history.get_description(character_id_number=None, max_num=ACTIONHISTORY_RETRIEVE_NUM_WHOLE_INFORMATION)
self.logger.gprint(important_log='important_log',
source_character='',
target_character='',
log_type='Stage Change',thought='',
log_content='Open Speech Stage')
# 等全部讲完了,再插入记忆之中
speeches = {}
# 最终投票前的发言
for character in self.characters.character_list:
# 设置背景信息
if not whole_information:
action_history = self.action_history.get_description(character_id_number=character.id_number, max_num=ACTIONHISTORY_RETRIEVE_NUM_PARTIAL_INFORMATION)
# ======================================================================================= #